> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Built for AI agents

> How GatoJS keeps AI coding agents honest: separate test-writer and implementer roles, hooks that lock tests, a mutation gate for critical files, agent instructions and architecture tests.

GatoJS is built to be worked on with AI coding agents, and to stay correct when they do. The process that built the kit ships with every project: agent instructions, Claude Code hooks, subagent definitions, project skills, Stryker and a mutation gate.

The core idea: **the agent that writes the code must not be the one that decides whether the code is correct.** Tests are written first, by a different agent, from a spec rather than from the code. The implementer cannot edit them. Then a third agent attacks the tests with mutation testing.

> [!NOTE]
>
> The agent-facing files in a project (`AGENTS.md`, `CLAUDE.md`, the agents and skills in `.claude/`) are currently written in Polish. Agents read them fine; English translations are planned.

## What ships in your project

| File | Purpose |
| - | - |
| `AGENTS.md` | Full instructions for any agent (Claude Code, Codex, Cursor, Copilot): what the kit is, priorities, a task router, commands, hard rules, testing rules, commits. |
| `CLAUDE.md` | A short list of the most expensive-to-break rules, plus `@AGENTS.md` to import the full instructions into Claude Code. |
| `.claude/settings.json` | Registers two `PreToolUse` hooks and an allow-list of safe commands. |
| `.claude/hooks/block-comments.mjs` | Blocks edits that add code comments. |
| `.claude/hooks/protect-tests.mjs` | Blocks edits to test files during the implementation phase. |
| `.claude/agents/test-writer.md`, `test-reviewer.md` | Subagent definitions for the adversarial testing process. |
| `.claude/skills/` | Project skills: `wa-code-review`, `wa-new-module`, `wa-upgrade-dependency`. |
| `stryker.config.json`, `stryker.integration.config.json`, `mutation-gate.json` | Mutation testing and the gate for critical files. |
| `src/__tests__/architecture/` | Tests that keep the instructions consistent with the code. |

Hooks and subagents work only in Claude Code. Other tools get the instructions in `AGENTS.md`, and the rules are enforced there by CI and code review.

## Why tests are written by someone else

A test written by the code's author, after the code, usually restates the code's assumptions and passes. Research on LLM-generated tests points the same way: assertions derived from code describe what the code does, not what it should do; tests generated after buggy code inherit the bug; and agents that are allowed to edit tests sometimes change or delete them instead of fixing the code.

So "write good tests" isn't enough as an instruction. The kit separates who writes tests and from what, blocks the implementer from changing them, and measures test strength with a tool that can't be argued with: a mutant is either killed or it survives.

An audit of the kit's own core tests bore this out. Tests were strong for pure functions and weak in two places only Stryker found: a mocked file hid the fact that the admin-role check in `getAdminUserOrNull` had no test at all (any signed-in user could have invited others and every test would pass), and 13 of 15 blocked better-auth paths could be removed without a red test.

## The roles

| Role | Gets | Does not |
| - | - | - |
| Orchestrator (main agent session) | The task plan. | Write tests or code. It starts subagents and toggles the phase file. |
| `test-writer` | The task's behaviors and mutations to kill, signatures, contracts from `contracts/`, existing tests as a style reference. | Read the implementation or the implementer's reasoning. Existing code is a black box. |
| Implementer | The plan and the finished tests. | Change tests. A test it believes is wrong goes in its report. |
| `test-reviewer` | The task's diff and the Stryker reports. Tools: `Read`, `Grep`, `Glob`, `Bash`. | Edit files, or add exceptions to `mutation-gate.json`. It only proposes them. |
| You | The reviewer's report and the pull request. | — |

## The task flow

```mermaid theme={null}
flowchart TD
    plan["Task plan:<br/>behaviors and mutations to kill"] --> writer["test-writer writes tests<br/>from the plan, not the code"]
    writer --> red{"Red for the<br/>right reason?"}
    red -->|"no: syntax/import error,<br/>or already green"| writer
    red -->|"yes"| phaseOn["Orchestrator writes implement<br/>to .superpowers/phase"]
    phaseOn --> impl["Implementer writes code.<br/>protect-tests blocks Edit/Write<br/>on test files"]
    impl --> wrong{"Test wrong or<br/>contradicts the plan?"}
    wrong -->|"yes"| report["Implementer stops and reports it"]
    wrong -->|"no, tests green"| phaseOff["Orchestrator deletes<br/>.superpowers/phase"]
    phaseOff --> reviewer["test-reviewer: mutation run,<br/>classify survivors, gate, checklist"]
    reviewer --> verdict{"Verdict"}
    verdict -->|"back to tester"| fix["test-writer adds tests<br/>that kill the gaps"]
    fix --> reviewer
    verdict -->|"OK"| review["Code review, pull request"]
    review --> human["A human approves any<br/>proposed gate exceptions"]
```

**1. Plan**

Each task lists **behaviors** (input → expected result as a literal) and **mutations to kill** (code changes a test must catch, such as "membership check removed"). The [feature tutorial](https://docs.gatojs.com/guides/build-a-feature.md#plan-behaviors-and-the-mutations-to-kill) shows a full example.

**2. Tests first**

`test-writer` writes the tests, runs them and returns each test with the mutation it kills. Tests must be red for the right reason: a missing export or a wrong value, not a syntax or import error. Create empty stub files (`export {};`) for the code under test so imports resolve. For integration tests, tell the writer to use `npm run test:integration -- <files>`, because its default `npx vitest run` skips them.

**3. Implementation phase**

The orchestrator writes `implement` to `.superpowers/phase` and starts the implementer. The `protect-tests` hook now rejects any edit to a test file.

**4. End of phase**

When the tests are green, the orchestrator deletes the phase file.

**5. Test review**

`test-reviewer` finds the task's production files (`git diff --name-only <base>...HEAD`, minus tests and generated files), runs `npm run test:mutation:task` on them and classifies every `Survived` or `NoCoverage` mutant in the changed lines as a **gap** (observable behavior change: needs a test), **equivalent** (indistinguishable from the original, with a reason) or **message/log** (text with no contract). Security logic (auth, organizations, roles, guards, sign-up) may have no gaps. It then runs `npm run test:mutation:gate` and a checklist, and returns **OK** or **back to the test writer** with the list of gaps.

**6. Fix and repeat**

On "back to tester", `test-writer` adds tests that kill the reported mutants and the review repeats. The phase file must be gone, because the hook blocks every agent, the tester included.

**7. Code review and pull request**

Test review comes before code review. Proposed gate exceptions go into the pull request for a human to approve.

If you write code and tests yourself without agents, skip the phase file and subagents, but the same testing rules apply. Before handing in a change to a file on the `critical` list, run `npm run test:mutation:task -- <files>` and `npm run test:mutation:gate` yourself; CI does not run mutations automatically.

## Testing rules

| Rule | Why |
| - | - |
| The expected value is a literal or comes from the spec. Never compute it with production code, a copy of its algorithm, a loop or a helper. | A test that computes the result the same way inherits the bug and always agrees. |
| Every mutation in "mutations to kill" has a test that fails when it is applied. | Those are the bugs the plan's author considered most dangerous. |
| Every boundary (server action, query, parser) has negative tests: invalid Zod input, no session, another organization, too low a role, a failing dependency, a double call. | Authors tend to test only the happy path. |
| Mock only I/O: Prisma in unit tests, mail, network, `auth.api`. Never mock the file holding the security rule under test, and never assert on the mock itself. | Mocking the rule switches it off, which is exactly how the admin-role gap went unnoticed. |
| Pure functions with an invariant (parser, serializer, normalizer, slug) get a property test with `test.prop` from `@fast-check/vitest`. | The library generates inputs the author didn't think of. |
| A bug fix has a test that fails without the fix. | It proves the test can see the bug. |
| Test names describe the behavior from the contract's point of view. | A red test tells you what broke. |

For example, an invitation's expiry is checked against a literal date, not `now + 48 * 60 * 60 * 1000`:

```ts src/features/users/services/commands/__tests__/invite-user-command.test.ts theme={null}
it("invitation expires exactly 48 hours after creation", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-03-10T08:00:00.000Z") });
  try {
    mockPrisma.user.findUnique.mockResolvedValueOnce(null);

    await inviteUserCommand(validInput);

    const { expiresAt } = mockPrisma.invitation.create.mock.calls[0][0].data;
    expect(expiresAt).toEqual(new Date("2026-03-12T08:00:00.000Z"));
  } finally {
    vi.useRealTimers();
  }
});
```

## The implementation phase and the protect-tests hook

`.claude/settings.json` registers both hooks as `PreToolUse` for the `Edit|Write` tools:

```json .claude/settings.json theme={null}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/block-comments.mjs\"" },
          { "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/protect-tests.mjs\"" }
        ]
      }
    ]
  }
}
```

Exit code 2 from a hook blocks the edit and shows the hook's message to the agent. Any other non-zero result is a non-blocking error: the edit goes through. A broken hook therefore silently stops protecting you, which is why both hooks have tests in `npm run verify` (`npm run test:hooks`).

`protect-tests.mjs` blocks an edit when `.superpowers/phase` contains exactly `implement` (after trimming whitespace) and the path matches:

```js .claude/hooks/protect-tests.mjs theme={null}
const TEST_PATH = /(^|\/)(__tests__|e2e)\/|\.(test|spec)\.[cm]?[jt]sx?$/;
```

That covers every file in a `__tests__/` or `e2e/` directory at any depth and every `*.test.*` or `*.spec.*` JavaScript or TypeScript file. The agent sees:

```text theme={null}
Zablokowane: faza implementacji (.superpowers/phase = implement), testy są tylko do odczytu.
Jeśli test jest błędny albo sprzeczny ze specyfikacją, zatrzymaj się i zgłoś to w raporcie zamiast go zmieniać.
```

("Blocked: implementation phase, tests are read-only. If a test is wrong or contradicts the spec, stop and report it instead of changing it.")

Turn the phase on and off in the root of the implementer's working copy:

```bash theme={null}
mkdir -p .superpowers && printf 'implement\n' > .superpowers/phase
rm .superpowers/phase
```

The hook reads the file on every edit, so the change applies immediately. It looks in two places: the working copy containing the edited file (the nearest directory with a `.git` entry, so a git worktree has its own phase) and the session's project directory (`$CLAUDE_PROJECT_DIR`). Write the phase file in the implementer's worktree, not the main checkout: a file in the main checkout blocks test edits in every Claude Code session for that repository. `.superpowers/` is in `.gitignore`.

> [!WARNING]
>
> A phase file left behind by an interrupted task keeps blocking test edits, including yours and `test-writer`'s. If you see "Zablokowane: faza implementacji" and no task is running, delete `.superpowers/phase` in the edited working copy and in the main checkout.

What the hook does **not** block:

| Gap | Caught by |
| - | - |
| Writes through the shell (`sed -i`, heredocs, `cp`) | `test-reviewer`'s checklist item on test changes in the implementer's diff |
| Test helpers outside `__tests__/` (`src/test/fake-prisma.ts`, `src/test/integration/`) | Diff review |
| Test and mutation config (`vitest*.ts`, `playwright.config.ts`, `stryker*.json`, `mutation-gate.json`), the hooks and `.claude/settings.json` | Diff review |
| Tools other than Claude Code | Diff review |

Committing the tests before the implementation makes the review easy:

```bash theme={null}
git diff --stat <tests-commit>..HEAD -- '**/__tests__/**' '**/*.test.*' '**/*.spec.*' 'e2e/**' src/test mutation-gate.json 'vitest*.ts' playwright.config.ts 'stryker*.json' .claude/
```

Every change on that list in the implementer's diff needs a justification.

### The block-comments hook

Project code has no comments: names should explain the code. `block-comments.mjs` rejects an edit that adds a comment line to a `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mts` or `.cts` file, with `Blocked: this edit adds code comments. The code must explain itself.` It allows `// WHY: …` (at most 3 lines) for a non-obvious reason the code can't show, and tool directives (`@ts-expect-error`, `eslint-disable…`, `@vitest-environment`, `prettier-ignore`, shebangs). Comments that only moved are not flagged, and paths under `node_modules`, `generated` and `components/ui` are exempt. ESLint has no such rule, so comments written through the shell or another editor are caught only in review.

## Mutation testing

Stryker makes mutants of your code and, for each one, runs the tests that cover the changed line. It works on a copy in `.stryker-tmp/`, so your files don't change. Typical mutators: `ConditionalExpression` (condition replaced by a constant), `EqualityOperator` (`>` → `>=`), `StringLiteral` (string emptied), `ObjectLiteral` (object replaced by `{}`), `BooleanLiteral` (`true` ↔ `false`).

| Status | Meaning | Score |
| - | - | - |
| `Killed` | At least one test failed. | detected |
| `Timeout` | Tests didn't finish in time. | detected |
| `Survived` | Tests covered the mutant and passed. | undetected |
| `NoCoverage` | No test runs the line. | undetected |
| `CompileError`, `RuntimeError`, `Ignored` | Rejected by TypeScript, couldn't run, or excluded. | not counted |

**Mutation score** = (`Killed` + `Timeout`) / (`Killed` + `Timeout` + `Survived` + `NoCoverage`).

### Two configurations

| | `stryker.config.json` | `stryker.integration.config.json` |
| - | - | - |
| Commands | `npm run test:mutation`, `npm run test:mutation:task` | `npm run test:mutation:integration` |
| Tests | Unit tests | Integration tests on the `_test` database |
| Mutates | `src/shared/lib/`, `src/shared/utils/`, `services/` and `contracts/` of every feature, `src/i18n/`, `src/app/api/`, `scripts/lib/` (not `prisma.ts`, `logger.ts`, tests) | `src/features/*/services/**`, `org-context.ts`, `require-module-access.ts` |
| Thresholds `high` / `low` / `break` | 85 / 75 / 75 | 80 / 70 / none |
| Reports | `reports/mutation/` | `reports/mutation-integration/` |

Components and pages are not mutated: business logic belongs in `services/`. A score below `break` sets exit code 1. `AGENTS.md` forbids lowering the threshold to let a change through.

### Running it on a task

**1. Make sure no other Stryker is running**

`pgrep -fl stryker` should print nothing. Two runs at once overwrite each other's reports, share the test database (which inflates scores) and compete for CPU (timeouts count as detected).

**2. Run it on the task's files**

```bash theme={null}
npm run test:mutation:task -- src/a.ts,src/b.ts
```

Comma-separated, no spaces. `--force` retests every mutant even when incremental results exist.

**3. Read your files' rows**

With an incremental file (`reports/stryker-incremental.json`), the final score covers the whole project; look at your files' rows in the terminal table or in `reports/mutation/mutation.html`, which also shows each mutant's code. Without it, the report covers only your files and `break` applies to them alone.

**4. Run the integration config if needed**

Files also mutated by the integration config show mutants only integration tests can kill as undetected. Run `npm run test:mutation:integration` (with `INTEGRATION_DATABASE_URL` if needed) so the gate can merge both reports.

**5. Run the gate**

`npm run test:mutation:gate`.

Property tests (`test.prop`) use a fixed seed under Stryker (set in `vitest.setup.ts` when `STRYKER_MUTATOR_WORKER` is present), because Stryker selects tests by name and fast-check puts the seed in the name. Normal `npm test` runs draw a new seed every time.

To exclude a file from mutation, add a `!` pattern to `mutate`. A `// Stryker disable` comment would be blocked by the comments hook.

## The mutation gate

The `break` threshold applies to the whole score, so it lets individual gaps through. In auth, organization, user and kit module services, any gap is a potential security bug. The gate (`npm run test:mutation:gate`) therefore checks **critical files** one by one: every undetected mutant must be killed by a test or have an approved exception.

`mutation-gate.json` has two lists. `critical` holds path prefixes:

```json mutation-gate.json theme={null}
{
  "critical": [
    "src/shared/lib/auth/",
    "src/shared/lib/tenant-scope/",
    "src/features/auth/services/",
    "src/features/organizations/services/",
    "src/features/users/services/",
    "scripts/lib/mutation-gate.ts",
    "src/shared/lib/audit.ts",
    "src/features/audit-logs/services/",
    "src/features/api-keys/services/",
    "src/features/uploads/services/"
  ],
  "allowed": [
    {
      "file": "src/features/auth/services/signup-gate.ts",
      "mutator": "ObjectLiteral",
      "original": "{ id: true }",
      "replacement": "{}",
      "reason": "equivalent: the result is only checked for presence"
    }
  ]
}
```

`allowed` holds exceptions with five fields: `file`, `mutator`, `original` (the exact code the mutant changes, with indentation and newlines), `replacement` and a non-empty `reason`. Three kinds of reason are accepted: an **equivalent mutant**, **message or log text only**, or a **deliberate configuration constant**. Your own critical code can be added to the `critical` list.

How the gate decides:

1. It reads `reports/mutation/mutation.json` and `reports/mutation-integration/mutation.json` (or the paths you pass). With no report, it fails.
2. It merges the reports: a mutant detected in either one counts as detected.
3. An exception with an empty `reason` is a violation.
4. Every `Survived` or `NoCoverage` mutant in a critical file without a matching exception is a violation. Matching is by file, mutator, original and replacement, not by line number, so exceptions survive code moving around (but one exception also covers identical mutants added later).
5. An exception for a file in the report that matches no mutant is **stale** and also fails the gate.

> [!WARNING]
>
> Exceptions are added and approved by a **human** in a pull request. Agents, including `test-reviewer`, only propose them. `test-reviewer` has `Bash`, so this is a convention enforced by review, not a technical block.

When the gate is red, open the HTML report, look at the mutant and decide whether it changes observable behavior. If it does, it's a gap: add a test that kills it. If it doesn't, propose an exception, copying `original` and `replacement` exactly from the gate's message. A stale exception means the mutant is now killed or the code changed: delete or update it.

## Agent instructions

`AGENTS.md` holds the full rules; `CLAUDE.md` repeats the ones that cost the most when broken (the `organizationId` filter and guards, the service-mode confirmation, no comments, generated files, tests before code, the `verify` gate) and imports `AGENTS.md` with `@AGENTS.md`. Claude Code reads only `CLAUDE.md` when both exist, so the import gives it the full rules while other tools read `AGENTS.md` directly. One source of truth means a rule change lands in one place.

`AGENTS.md` opens with a **task router**: a table from "task" to "where to look", so an agent starts from its row instead of searching the whole file. Paths to `docs/…` in it refer to the GatoJS repository, because `docs/` is not copied into projects. Size matters: Codex silently truncates instructions above 32 KiB.

> [!TIP]
>
> Next.js 16.3+ appends a rules block to `AGENTS.md` when an AI agent starts `next dev`. The kit's `next.config.ts` sets `agentRules: false` to prevent that, and an architecture test keeps it set. If an older project shows ` M AGENTS.md` after `next dev`, restore it with `git restore AGENTS.md`.

### Permissions

`permissions.allow` in `.claude/settings.json` lists commands Claude Code runs without asking: `npm run verify`, `npm run lint`, `npm run typecheck`, `npx tsc --noEmit`, `npm test`, `npm run test`, `npm run test:hooks`, `npm run test:mutation:gate`, `npm run wa -- generate` and read-only `git status`, `git diff`, `git log` and `git show`.

Test commands are allowed only as exact strings. A wildcard like `Bash(npm test *)` would also allow `npm test -- -c vitest.integration.config.ts`, which truncates the `_test` database. For the same reason integration, e2e and mutation commands are not on the list, nor are migrations, installs, `rm`, `git push` or Docker. Put your own rules in `.claude/settings.local.json`, not in the kit's `settings.json`.

## Project skills

A skill is a folder `.claude/skills/<name>/` with a `SKILL.md`. Claude Code loads it when a task matches its description, or on `/<name>`. Other tools reach the same files through links in the task router.

| Skill | When | Contents |
| - | - | - |
| `wa-code-review` | Before handing in work, before a commit, on a pull request. | `npm run verify` first, then the invariants the gate can't check: `organizationId` filters and guards, the service-mode contract, `withoutTenantScope` only with a reason, generated files and regions, the module/core boundary, tests by another agent, gate exceptions only from humans, i18n in every locale, no comments. |
| `wa-new-module` | A new project feature or kit module. | Choosing `projectModules` vs. a kit module, the steps from the [feature tutorial](https://docs.gatojs.com/guides/build-a-feature.md) in short, and the traps (`schemaRelations` instead of `prisma format`, `npm run db:generate` after a migration). |
| `wa-upgrade-dependency` | Bumping an npm dependency, an `npm audit` alert. | Changelog, bump, `npm run verify`, integration and e2e tests; separate steps for better-auth and Prisma (tables, migrations, `schemaRelations`) and for Next.js (codemods). |

Code review does not depend on any external bot: `wa-code-review` is the checklist.

## Architecture tests keep the instructions honest

Instructions rot when the code moves on. The tests in `src/__tests__/architecture/` check what neither TypeScript nor ESLint can, and they run in `npm test`, so in every `npm run verify`:

| Test | Invariant |
| - | - |
| `agent-instructions-fit-the-budget` | `AGENTS.md` is at most 31,744 bytes: Codex's 32 KiB limit minus 1 KiB of headroom. |
| `documented-commands-exist` | Every `npm run <script>` in `AGENTS.md`, `CLAUDE.md`, `README.md` and `.md` files in `.claude/` exists in `package.json`. |
| `cited-paths-exist` | Every path in backticks or a link target in `AGENTS.md`, `CLAUDE.md` and `.claude/**/*.md` exists. |
| `i18n-keys-exist-in-every-locale` | Every translation file exists for every locale with the same set of keys. |
| `env-example-passes-validation` | `.env.example` passes the environment schema, including project modules' variables. |
| `client-bundles-stay-server-free` | No `"use client"` file imports Prisma, `@/env`, `server-only`, `node:*` or server auth modules. |
| `node-version-is-one-number` | `.nvmrc`, the `Dockerfile` and the workflows agree on the Node major version. |
| `next-config-agent-rules` | `next.config.ts` keeps Next.js from writing agent rules into the project. |

Separately, `src/__tests__/server-entrypoints-guard.test.ts` checks that every server entry point (server actions, queries, route handlers) calls a guard before Prisma. See [Code patterns](https://docs.gatojs.com/guides/code-patterns.md).

A failing architecture test names the file and the value, for example `CLAUDE.md: npm run nope`. Fix the file, not the test.

## Pitfalls when working with agents

* **`npm run test:e2e` started by an agent** stops at the database reset, because Prisma refuses it without your consent. Run e2e tests yourself. See [Testing](https://docs.gatojs.com/guides/testing.md#end-to-end-tests).
* **A leftover phase file** blocks test edits for everyone. Delete `.superpowers/phase`.
* **Hooks only see `Edit` and `Write`.** Shell writes, other AI tools and your editor bypass them; review the diff.
* **Hooks run from the session's project directory.** A Claude Code session started in the main checkout uses the main checkout's hook versions, even while working in a worktree.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.