Skip to main content
This is the second part of the notes tutorial. It starts where part 1 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. This page applies them.

Step 7. Query, command, component and page

Query

src/features/notes/services/queries/list-notes-query.ts
  • 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.

Command

src/features/notes/services/commands/create-note-command.ts
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.
src/features/notes/components/notes-manager.tsx
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

src/app/[locale]/(app)/notes/page.tsx
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

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 hrefs 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):
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. 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.
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:
A run on the command file alone produced:
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: 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:
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.

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:
Commit it all together: generated files and the migration belong to the change that produced them. Use a Conventional Commits subject in lowercase:
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.

Optional modules in your feature

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

Audit logs

Call trackAudit in the command after a successful write and declare the action in auditActions.

Uploads

Declare a purpose in uploadPurposes, add <FileUpload> to the form and store only the file id.

API keys

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.
  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.
A new folder in src/features/ is always a new feature with a new entry, so it goes through the whole tutorial.

Troubleshooting