> ## 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.

# Build a feature, part 2: implement, verify and commit

> Implement the query, command, component and page of a GatoJS feature, then pass npm run verify, integration and mutation tests and commit the change.

This is the second part of the notes tutorial. It starts where [part 1](https://docs.gatojs.com/guides/build-a-feature.md) ended: the `notes` feature is in the registry, the `notes` table has a migration, the contracts exist, and the command and isolation tests are red with `TypeError: … is not a function`.

The rules behind each file (queries, commands, forms, error handling) are explained in [Code patterns](https://docs.gatojs.com/guides/code-patterns.md). This page applies them.

## Step 7. Query, command, component and page

### Query

```ts src/features/notes/services/queries/list-notes-query.ts theme={null}
import "server-only";

import { prisma } from "@/shared/lib/prisma";
import { getOrgContext } from "@/shared/lib/auth/org-context";
import type { NoteListItem } from "../../contracts/note.types";

export async function listNotesQuery(): Promise<NoteListItem[]> {
  const { organizationId } = await getOrgContext();

  return prisma.note.findMany({
    where: { organizationId },
    orderBy: { createdAt: "desc" },
    select: { id: true, title: true, createdAt: true },
  });
}
```

* The query calls its own guard (`getOrgContext()`) even though the page calls `requireModuleAccess` first. Another page may import it later, and the architecture test requires a guard in every export from `services/queries/`.
* The file has `import "server-only"` and no `"use server"`, so it is not an endpoint, and reading in service mode needs no confirmation.
* Because `Note` has an `organizationId` field, the runtime tenant-scope guard covers it with no core changes: `prisma.note.findMany()` without an organization filter throws `TenantScopeError`. The same applies to commands (`create` needs `data.organizationId`; `update` and `delete` need it in `where`). For a deliberate cross-organization read, wrap the call in `withoutTenantScope(reason, …)` from `@/shared/lib/tenant-scope`. See [Organizations](https://docs.gatojs.com/concepts/organizations.md).

### Command

```ts src/features/notes/services/commands/create-note-command.ts theme={null}
"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/shared/lib/prisma";
import { requireModuleAccess } from "@/shared/lib/auth/require-module-access";
import { assertServiceModeConfirmed } from "@/shared/lib/auth/service-mode";
import { handleCommandError } from "@/shared/utils/error-handling";
import { createNoteSchema } from "../../contracts/note.schemas";
import type { OperationResult } from "@/shared/types/common";

export async function createNoteCommand(
  input: unknown,
  confirmation?: unknown,
): Promise<OperationResult<{ noteId: string }>> {
  try {
    const parsed = createNoteSchema.safeParse(input);
    if (!parsed.success) {
      return {
        success: false,
        error: parsed.error.issues[0]?.message ?? "Invalid input",
      };
    }

    const context = await requireModuleAccess("notes");
    assertServiceModeConfirmed(context, confirmation);

    const note = await prisma.note.create({
      data: {
        organizationId: context.organizationId,
        title: parsed.data.title,
      },
      select: { id: true },
    });

    revalidatePath("/notes");
    return { success: true, data: { noteId: note.id } };
  } catch (error) {
    return handleCommandError(error, "Could not add the note");
  }
}
```

| Step | In the command | Why |
| - | - | - |
| Signature | `"use server"`, `(input: unknown, confirmation?: unknown)`, body in `try` with `handleCommandError` | Every export of a `"use server"` file is a `POST` endpoint, so the file exports only the command. |
| Validate | `createNoteSchema.safeParse(input)` | Bad input stops before the guard queries the database. |
| Guard | `requireModuleAccess("notes")` | Same key as `module.ts` and the page, so the command gets the same access decision as the page. |
| Service mode | `assertServiceModeConfirmed(context, confirmation)` | Right after the context, before Prisma, with the parameter passed through unchanged. See [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md). |
| Narrower rule | none | Every role may add a note. A stricter rule (for example owners only) would check `context.orgRole` here. |
| Write | `organizationId: context.organizationId` | Never from `input`. |
| Finish | `revalidatePath("/notes")` and `{ success: true, data }` | |

`requireModuleAccess` sits inside `try`, so an access denial returns the default message and logs an `error` entry rather than rendering a 404.

### Component

The component calls the command through `run` from `useServiceModeAction()` and renders the dialog the hook returns.

```tsx src/features/notes/components/notes-manager.tsx theme={null}
"use client";

import { format } from "date-fns";
import { pl, enUS } from "date-fns/locale";
import type { Locale as DateFnsLocale } from "date-fns";
import { NotebookPen } from "lucide-react";
import { toast } from "sonner";
import { useLocale, useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import type { z } from "zod";
import { useRouter } from "@/i18n/routing";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FormField, FormLabel, FormError } from "@/components/ui/form";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { useServiceModeAction } from "@/shared/components/service-mode/use-service-mode-action";
import { createNoteCommand } from "../services/commands/create-note-command";
import {
  createNoteSchema,
  type CreateNoteValues,
} from "../contracts/note.schemas";
import type { NoteListItem } from "../contracts/note.types";

const DATE_FNS_LOCALES: Record<string, DateFnsLocale> = { pl, en: enUS };

type CreateNoteFormValues = z.input<typeof createNoteSchema>;

interface NotesManagerProps {
  notes: NoteListItem[];
}

export function NotesManager({ notes }: NotesManagerProps) {
  const router = useRouter();
  const t = useTranslations("notes");
  const dateLocale = DATE_FNS_LOCALES[useLocale()] ?? enUS;
  const serviceModeAction = useServiceModeAction();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<CreateNoteFormValues, unknown, CreateNoteValues>({
    resolver: zodResolver(createNoteSchema),
    defaultValues: { title: "" },
  });

  async function onSubmit(values: CreateNoteValues) {
    const result = await serviceModeAction.run(createNoteCommand, values);
    if (result === null) {
      return;
    }
    if (result.success) {
      toast.success(t("toast-created"));
      reset();
      router.refresh();
    } else {
      toast.error(result.error ?? t("toast-create-error"));
    }
  }
// …
      {serviceModeAction.dialog}
    </Card>
```

The omitted JSX is a card with the form and the list: a `FormField` with `FormLabel`, an `Input` with `{...register("title")}`, a `FormError` showing `t("error-title-required")` when `errors.title` is set, and a submit button. The list shows each note's title and `format(new Date(note.createdAt), "d MMM yyyy", { locale: dateLocale })`, or `t("empty")` when there are none. `src/features/users/components/users-manager.tsx` and `invite-user-dialog.tsx` use the same layout.

* `useForm` takes three type parameters because the schema trims the title: the form input type (`z.input`) differs from the validated output.
* `run` returns `null` when the user clicks **Cancel** in the service-mode dialog; the component then does nothing.
* For writes that don't go through a server action (for example `fetch` to a route handler), get the confirmation from `requestConfirmation()` on the same hook and send it to the server yourself. `null` means cancelled.
* `router.refresh()` from `@/i18n/routing` reloads the page after success, so the query runs again.
* Without `{serviceModeAction.dialog}`, a superadmin in service mode never sees the dialog and `run` waits forever.

### Page

```tsx src/app/[locale]/(app)/notes/page.tsx theme={null}
import { setRequestLocale } from "next-intl/server";
import { requireModuleAccess } from "@/shared/lib/auth/require-module-access";
import { NotesManager } from "@/features/notes/components/notes-manager";
import { listNotesQuery } from "@/features/notes/services/queries/list-notes-query";

interface NotesPageProps {
  params: Promise<{ locale: string }>;
}

export default async function NotesPage({ params }: NotesPageProps) {
  const { locale } = await params;
  setRequestLocale(locale);
  await requireModuleAccess("notes");
  const notes = await listNotesQuery();
  return <NotesManager notes={notes} />;
}
```

The page lives in the `(app)` route group, so it gets the menu, the service-mode banner and the `ServiceModeProvider` that `run` needs. It only reads data and renders; data changes happen only in server actions.

With the implementation in place, the unit tests report `Tests  20 passed (20)` and the isolation tests `Tests  7 passed (7)`. The architecture test `src/__tests__/server-entrypoints-guard.test.ts` passes with the new files and no exceptions.

## Step 8. Gates

### Generated files are up to date

`npx gato generate` must print `Bez zmian` ("no changes"). The CI `verify` job runs the generator and fails if the generated files differ from what you committed.

### `npm run verify` and the core tests

```bash theme={null}
npx gato generate
npm run verify
```

`npm run verify` runs lint, typecheck, unit tests, the production build, workspace package checks and the Claude Code hook tests. Adding `notes` requires no change to any existing test:

* Core tests that compare the registry with hard-coded lists (`access-matrix.test.ts`, `nav.test.ts`, `app-sidebar.test.tsx`) filter the registry to the five core modules (`account`, `auth`, `dashboard`, `organizations`, `users`) through `src/test/core-modules.ts`. Kit modules and project features don't change their expected values.
* `src/shared/lib/modules/__tests__/registry-consistency.test.ts` checks the **whole** registry, `notes` included. For every module it requires unique module keys and unique menu `href`s starting with `/`; a translation loader and a non-empty label for every menu item in every locale; and, for all 24 combinations of global role, organization role and `MULTI_ORG`, that a module's `href` appears in the menu exactly when `canAccessModule` allows it.

This is a consistency check of registry data, not coverage of access rules. If your `module.ts` narrows access (`roles`, `adminOnly`), cover that with your own test next to the feature, with the expected result written as a literal. A missing translation or a duplicate `href` shows up as a `registry-consistency.test.ts` failure naming the module.

### Integration tests

Run the full integration suite (add `INTEGRATION_DATABASE_URL=…` in the shell if your database isn't on port 5432):

```bash theme={null}
npm run test:integration
```

On a core-only project this reports `Tests  45 passed (45)`: 38 core tests and 7 notes tests, in about 5 seconds. Projects with kit modules add their integration tests, and the `uploads` module also needs MinIO running. See [Testing](https://docs.gatojs.com/guides/testing.md#integration-tests).

The `notes` table is not in the `TABLES` list in `src/test/integration/database.ts`, but `resetDatabase()` still clears it, because its foreign key to `organizations` is followed by `TRUNCATE … CASCADE`. A feature table without a foreign key to a core table must be cleared in your own `beforeEach`.

> [!TIP]
>
> Prove the isolation test can fail. Temporarily replace `organizationId` in the query's `where` with the other organization's id and run the test: it must go red. Simply deleting the filter fails earlier, on the tenant-scope guard (`TenantScopeError`), not on the isolation assertion.

### Mutation testing

Mutation testing with Stryker checks whether your tests actually catch bugs: it injects small changes into the code and reruns the tests. Make sure no other Stryker run is active (`pgrep -fl stryker` prints nothing), then run it on the files you changed:

```bash theme={null}
npm run test:mutation:task -- src/features/notes/services/commands/create-note-command.ts
```

A run on the command file alone produced:

```text theme={null}
INFO Instrumenter Instrumented 1 source file(s) with 23 mutant(s)
INFO DryRunExecutor Initial test run succeeded. Ran 20 tests in 1 second
ERROR MutationTestReportHelper Final mutation score 66.67 under breaking threshold 75, setting exit code to 1 (failure).
```

Of 23 mutants, 14 were rejected by TypeScript (`CompileError`, not counted), 6 were `Killed`, 2 `Survived` and 1 had `NoCoverage`: 6 of 9, or 66.67%.

**Why exit code 1.** Without an incremental file (`reports/stryker-incremental.json`, created by a full `npm run test:mutation`), the report covers only the files you passed, and the `break` threshold of 75 applies to them alone. A small file with a few unkillable mutants drops below it easily. Judge each surviving mutant rather than the score:

| Status | Mutation in the validation-message line | Classification |
| - | - | - |
| `Survived` | `issues[0]?.message ?? "Invalid input"` → `… && "Invalid input"` | Message only: tests check for a non-empty error, not its text. A test asserting the exact Zod message would kill it. |
| `Survived` | `issues[0]?.message` → `issues[0].message` | Equivalent: a failed `safeParse` always has at least one issue. |
| `NoCoverage` | `"Invalid input"` → `""` | Equivalent: the fallback is unreachable for the same reason. |

The killed mutants were the ones that matter: removing `assertServiceModeConfirmed`, an empty key in `requireModuleAccess`, an empty path in `revalidatePath`, and flipped `success` values.

Then run the gate:

```bash theme={null}
npm run test:mutation:gate
```

It prints `Bramka mutacji: OK (raporty: reports/mutation/mutation.json).` ("mutation gate: OK"), because feature files are not on the `critical` list in `mutation-gate.json`. The query is covered only by integration tests, so a unit mutation run reports its mutants as `NoCoverage`; use `npm run test:mutation:integration` to mutate `services/` files under the integration tests. How the gate works is explained in [Built for AI agents](https://docs.gatojs.com/guides/ai-agents.md#the-mutation-gate).

### Check in the browser

Run `npm run dev`, sign in and open `/notes`. You should see a **Notes** item in the menu, a card with a **Title** field and an **Add note** button, and "No notes yet." when the list is empty. After adding a note it appears with its date; an empty title shows the validation message under the field.

A superadmin in an organization they don't belong to (service mode) sees that organization's empty list, and **Add note** opens the service-mode confirmation dialog. After confirming, the note is saved in that organization.

## Step 9. Commit

Stage everything and review the list:

```bash theme={null}
git add -A
git status --short
```

```text theme={null}
M  .wa/kit.json
A  prisma/migrations/20261028044413_add_notes/migration.sql
A  prisma/schema/notes.prisma
M  prisma/schema/organizations.prisma
A  src/app/[locale]/(app)/notes/page.tsx
A  src/features/notes/components/notes-manager.tsx
A  src/features/notes/contracts/note.schemas.ts
A  src/features/notes/contracts/note.types.ts
A  src/features/notes/i18n/en.json
A  src/features/notes/i18n/pl.json
A  src/features/notes/module.ts
A  src/features/notes/services/__tests__/notes-isolation.integration.test.ts
A  src/features/notes/services/commands/__tests__/create-note-command.test.ts
A  src/features/notes/services/commands/create-note-command.ts
A  src/features/notes/services/queries/list-notes-query.ts
M  src/modules.client.generated.ts
M  src/modules.generated.ts
```

Commit it all together: generated files and the migration belong to the change that produced them. Use a [Conventional Commits](https://www.conventionalcommits.org) subject in lowercase:

```bash theme={null}
git commit -m "feat(notes): organization notes"
```

On commit, lint-staged runs `eslint --fix` and Prettier on staged files, and commitlint checks the message. On deployment, `npx prisma migrate deploy` applies the `add-notes` migration. More on commits and gates in [Working with the kit](https://docs.gatojs.com/guides/working-with-the-kit.md).

## Optional modules in your feature

If your project includes these kit modules, your feature can plug into them through its `module.ts`:

> [card] [Audit logs](https://docs.gatojs.com/modules/audit-logs.md)
>
> Call `trackAudit` in the command after a successful write and declare the action in `auditActions`.

> [card] [Uploads](https://docs.gatojs.com/modules/uploads.md)
>
> Declare a purpose in `uploadPurposes`, add `<FileUpload>` to the form and store only the file id.

> [card] [API keys](https://docs.gatojs.com/modules/api-keys.md)
>
> Declare a scope in `apiScopes` and call `authenticateApiKey` first in your route handler.

## Adding to an existing feature

To extend a feature that already has an entry in `.wa/kit.json` (say, deleting notes), you don't add a new entry, but you sometimes change the existing one.

1. **Run the generator only when needed.** After adding a `module.ts`, `env.ts`, `auth.ts`, `auth-client.ts`, `audit-sink.ts` or `i18n/<locale>.json` file to a feature, or after changing the entry in `.wa/kit.json` (`schemaRelations`, `env`, `compose`, `ciSteps`). New commands, queries, components, pages or keys in an existing translation file don't need it: the registry imports files rather than copying their content.
2. **Plan and write tests first**, as in [step 6](https://docs.gatojs.com/guides/build-a-feature.md#step-6-tests-before-code).
3. **Scope by organization.** When a command updates or deletes a record by an `id` from the input, use `{ id, organizationId }` in `where`; an `id` alone may point at another organization's record. A rule narrower than page access, such as owner-only deletes, checks `context.orgRole` after `assertServiceModeConfirmed`.
4. **Add an isolation test** for the new command or query: user A passes the `id` of a record in organization B, the command refuses, and B's record is unchanged in the database.
5. **Schema changes:** `npx prisma migrate dev --name <name>`, then `npm run db:generate`, and commit the migration with the change. A new relation to `User` or `Organization` needs a new `schemaRelations` item and a generator run first; never `prisma format`.
6. **New pages** in `src/app/[locale]/(app)/<route>/page.tsx` call `requireModuleAccess` with the feature key. Add the route pattern to the entry's `files` so ownership stays complete.
7. **Access or menu changes in `module.ts`** (`nav`, `roles`, `adminOnly`, `multiOrgRoles`, `public`) don't require changes to core tests; cover your own rules with your own test.
8. **Gates** as in [step 8](#step-8-gates).

A new folder in `src/features/` is always a new feature with a new entry, so it goes through the whole tutorial.

## Troubleshooting

| Message | When | Fix |
| - | - | - |
| `Bez zmian` after adding `module.ts` | The feature has no pattern in `.wa/kit.json`. | [Add the entry](https://docs.gatojs.com/guides/build-a-feature.md#step-3-add-the-entry-to-projectmodules). |
| `404 This page could not be found.` on the feature page | Feature not in the registry, or a different key in `requireModuleAccess` than in `module.ts`. | Check the entry, the generator run and the key. |
| `Type "Note" is neither a built-in type, nor refers to another model, composite type, or enum.` | The region has the relation, the schema file doesn't exist yet. | Save the schema file. |
| ``… is missing an opposite relation field on the model `Organization`. Either run `prisma format` or add it manually.`` | The schema file exists, `schemaRelations` or the generator run is missing. | Add `schemaRelations` and run the generator. Don't run `prisma format`. |
| `Field "notes" is already defined on model "Organization".` | The relation was added manually or by `prisma format`, and again by the generator. | Delete the line outside the `wa:relations` region. |
| `error TS2339: Property 'note' does not exist on type 'PrismaClient'.` | The client wasn't regenerated after the migration. | `npm run db:generate`. |
| `Failed to resolve import "../create-note-command" … Does the file exist?` | Tests written before the code without a stub file. | Create the file with `export {};`. |
| `TypeError: createNoteCommand is not a function` | Red for the right reason: the export is missing. | Implement it (step 7). |
| `Invariant: static generation store missing in revalidatePath /notes` | Integration test calls a command with `revalidatePath` without mocking `next/cache`. | `vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }))`. |
| Failure in `registry-consistency.test.ts` naming a module | Missing menu label translation in one locale, or a duplicate `href` or key. | Fix the translation or `module.ts`. |
| `Final mutation score … under breaking threshold 75` | A task run without an incremental file. | Classify the surviving mutants. |


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