Define and Integrate a Feature
Updated
IntermediateWhat you'll learn
~40 min- List the files a feature must have and the registries it must appear in, and keep both as data
- Plan a feature read-only first, approve the plan, then generate it with one prompt and a second prompt for its registrations
- Write a validator that fails the build when a feature lacks a file or a registration
- Decide which of your agency's conventions belong in the contract and which do not
Two halves of one problem
A new feature in the reference app (Next.js, any OIDC identity provider, SQL Server, containers; Lessons 34 to 37 land it on your cloud and code host) has to exist in two ways. It has to exist as files: a migration, types, a route, a hook, a page, tests, styles. And it has to exist in the platform’s lists: who may use it, where it appears in navigation, which tables it owns, what state it is in. Miss a file and the build or a test usually tells you. Miss a list entry and the feature fails quietly: the page loads but every call is denied, or it works and no one can find it.
Treat the two halves as one pattern. The feature integration contract is the list of files a feature must have. The registration ledger is the set of registries a feature must appear in (a registry here is just a config file keyed by feature id). A validator reads both and fails the build on a gap. This site does the same thing for its own content: the trainings catalog runs validateCatalog() at build time and refuses a malformed entry, and scripts/prebuild-checks.sh runs before every build.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| A feature is missing a file | A file contract kept as data and checked; the alternative is a generator or template repository that emits every file | Same on every platform; 37: the pipeline step that runs the check | Whether the contract is checked or generated |
| A feature is missing from a registry | Five registries, each keyed by feature id, checked; the alternative is one manifest per feature that all registries derive from | Same on every platform | Where the single source of truth lives |
| When the gap is found | At build, before deployment; the alternative is at pull-request review | 37: a required check on the protected branch, in GitHub, GitLab, Azure DevOps or Bitbucket | Whether a gap may merge |
| What the files must look like | The reference conventions, shown below; the alternative is your agency’s own | Same on every platform | Which conventions the validator enforces |
The feature integration contract
The reference app’s contract is seven files per feature. The list is a decision, not a law; edit it to match your agency’s conventions, then keep it in one place.
- Migration (
migrations/<date>_create_<feature>.sql): the SQL Server table, with the provenance column from Lesson 10 and the audit columns your database team expects. - Types (
src/types/<feature>.ts): Zod schemas for request and response bodies, plus the types inferred from them. - Route (
src/app/api/<feature>/route.ts): handlers wrapped inwithPermission()(Lesson 5), using the response helpers from Lesson 7. - Hook (
src/hooks/use<Feature>.ts): SWR reads and mutations (Lesson 9). - Page (
src/app/(protected)/<feature>/page.tsx): the MUI page with the tiered views from Lesson 11. - Tests (
tests/<feature>.test.ts): the schemas and the route handlers. - Styles (
src/styles/<feature>.module.css): module-scoped styles that sit in the layers from Lesson 4.
Keep them as data in this reference contract file (src/features/contract.ts), so the validator and your agent read the same list:
// {id} is the kebab-case feature id; {Pascal} is the same id in PascalCase.export const FEATURE_FILES = [ "migrations/*_create_{snake}.sql", "src/types/{id}.ts", "src/app/api/{id}/route.ts", "src/hooks/use{Pascal}.ts", "src/app/(protected)/{id}/page.tsx", "tests/{id}.test.ts", "src/styles/{id}.module.css",] as const;The registration ledger
The ledger is the five places a feature must be listed. Four are files that hold a record per feature; the fifth is the list of feature ids that the others are checked against.
| Registry | File | What it holds for the feature |
|---|---|---|
| Feature ids | src/config/features.ts | The id itself, in one array |
| Permission matrix | src/lib/auth/permissions.ts | Keys such as vehicle-fleet:read, each with a minimum role (Lesson 5) |
| Navigation | src/config/nav-routes.ts | Label, path, required permission, group |
| Provenance map | src/config/provenance-map.ts | The tables the feature owns and their default data source |
| Status | src/config/module-status.ts | development, staging, production, or deprecated, and an owner |
Here is the reference feature-ID registry in src/config/features.ts that your agent updates:
export const FEATURE_IDS = ["vehicle-fleet" /* add yours here */] as const;export type FeatureId = (typeof FEATURE_IDS)[number];Give the other three config files the type Record<FeatureId, ...> and the compiler fails when a record is missing. The permission matrix is keyed by resource:action strings, so the compiler cannot check it; the validator does.
Plan first, read-only
A feature touches a dozen files and five registries, so the first turn is a plan, not an edit. Open the agent and switch it to plan mode inside the session, let it read the contract and the registries, and approve the plan before it writes a line.
| Tool | Plan before building |
|---|---|
| Claude Code | claude, then Shift+Tab or /plan |
| Codex | codex --sandbox read-only, then /plan or Shift+Tab (plan mode is an in-session command with no launch flag; the sandbox flag is what keeps the session read-only; leaving /plan does not lift that sandbox, so once you approve the plan, switch to Auto with /permissions before the edits) |
| Antigravity | agy, then Shift+Tab or /plan |
| Copilot | copilot, then Shift+Tab or /plan |
Lesson 2 holds the dated four-tool equivalents table and Lesson 1 holds permissions, sandbox and egress; use whichever tool your agency approved. Module 19 lesson 5 (the subagent, background, worktree ladder) covers what to do when one feature grows past a single session.
Plan the change with your agent
You will use the vehicle-fleet feature from here to Lesson 15: a tracker for fleet vehicle assignments. If src/features/contract.ts and the five registry files shown above are not in your folder yet, the agent can scaffold their starter stubs first. Open your workspace agent at the project root, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and start with a short request:
Read src/features/contract.ts and our five feature registries (or scaffold their starter stubs if missing), and plan a "vehicle-fleet" feature for tracking fleet assignments, including its contract validator test. Ask me anything unclear before writing code.What to check in the plan before you approve
- The plan covers all seven files in
FEATURE_FILES: the SQL Server migration (vehicle_fleettable withdata_sourceand audit columns), Zod schemas insrc/types/vehicle-fleet.ts,GETandPOSThandlers insrc/app/api/vehicle-fleet/route.tswrapped inwithPermission()and querying throughwithPool(), SWR hooks insrc/hooks/useVehicleFleet.ts, the page insrc/app/(protected)/vehicle-fleet/page.tsx, tests intests/vehicle-fleet.test.ts, and styles insrc/styles/vehicle-fleet.module.css. - The plan adds
"vehicle-fleet"to all five registries (features.ts,permissions.ts,nav-routes.ts,provenance-map.ts, andmodule-status.ts) without modifying or reordering existing entries. tests/contract/features.test.tschecks that every ID inFEATURE_IDShas every file inFEATURE_FILESand an entry in each registry, and that every directory undersrc/app/api(except exempt routes) is a registered feature ID, wired intopackage.jsonas"prebuild".
If the agent asks which navigation group to use or tries to write files and registries in one unreviewed jump, guide it:
Use the work group in nav-routes.ts, generate the seven contract files first, and then update the registries and validator.What you get
- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/features/contract.ts and our five feature registries (or scaffold their starter stubs if missing), and plan a "vehicle-fleet" feature for tracking fleet assignments, including its contract validator test. Ask me anything unclear before writing code.
- The tool replies: Read-only mode: I can read files and run read-only commands, and I will not edit anything. Plan: - Create the seven files FEATURE_FILES lists, with the migration under migrations/ and the route under src/app/api/vehicle-fleet/. - Add an entry to features.ts, permissions.ts, nav-routes.ts, provenance-map.ts and module-status.ts. - Prove it with the contract test, run through the prebuild step. Question before I write: nav-routes.ts has two groups, 'work' and 'admin'. Which group should hold vehicle-fleet?
- Mode:Plan approved: plan mode off
- You type in the session: Use the work group in nav-routes.ts, generate the seven contract files first, and then update the registries and validator.
- The tool replies: Created the seven files the contract lists: - migrations/20261104_create_vehicle_fleet.sql: table with the provenance and audit columns, SQL Server syntax - src/types/vehicle-fleet.ts: create and update schemas, row type - src/app/api/vehicle-fleet/route.ts: GET and POST, both inside withPermission(), queries through withPool, parameterized - src/hooks/useVehicleFleet.ts - src/app/(protected)/vehicle-fleet/page.tsx - tests/vehicle-fleet.test.ts: ten cases, DB and session mocked - src/styles/vehicle-fleet.module.css I did not touch any registry. Those are the next step.
- You type in the session: Now register vehicle-fleet in the five registries with the 'work' group and add the contract validator test.
- The tool replies: Edited features.ts, permissions.ts, nav-routes.ts, provenance-map.ts and module-status.ts. Added tests/contract/features.test.ts and set "prebuild" to run it. Before the nav entry went in I ran the validator: 1 failed: feature vehicle-fleet is missing from nav-routes.ts. Add an entry with path /vehicle-fleet. After the entry: all passed. The build now runs this test first, so a feature with a missing file or registry stops before deployment.
- You type in the session: Add a directory src/app/api/scratch with a route.ts and run it again. Then remove the directory.
- The tool replies: 1 failed: src/app/api/scratch is not a registered feature id. Add it to FEATURE_IDS or remove the directory. I removed the directory and reran: all passed. The failure message names the directory, so a reviewer can act on it without reading the test.
Illustrative session in Claude Code; the exact wording varies.
Prove it
The validator is a Vitest file. Vitest is already in the baseline (Lesson 2), it runs in the same step as your other tests, and "prebuild": "vitest run tests/contract" makes npm run build stop on a failure.
REFERENCE TEST tests/contract/features.test.ts: build-time validator for feature files and registry entries open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";import { describe, it, expect } from "vitest";import { FEATURE_FILES } from "@/features/contract";import { FEATURE_IDS } from "@/config/features";import { PERMISSIONS } from "@/lib/auth/permissions";import { NAV_ROUTES } from "@/config/nav-routes";import { PROVENANCE_MAP } from "@/config/provenance-map";import { MODULE_STATUS } from "@/config/module-status";
const root = process.cwd();const snake = (s: string) => s.replaceAll("-", "_");const pascal = (s: string) => s.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join("");
function present(pattern: string, id: string): boolean { const p = pattern.replaceAll("{id}", id).replaceAll("{snake}", snake(id)).replaceAll("{Pascal}", pascal(id)); if (!p.includes("*")) return existsSync(join(root, p)); const [dir, file] = [p.slice(0, p.lastIndexOf("/")), p.slice(p.lastIndexOf("/") + 1)]; const re = new RegExp("^" + file.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace("\\*", ".*") + "$"); return existsSync(join(root, dir)) && readdirSync(join(root, dir)).some((f) => re.test(f));}
describe.each([...FEATURE_IDS])("feature %s", (id) => { it.each([...FEATURE_FILES])("has file %s", (pattern) => { expect(present(pattern, id), `missing file for ${id}: ${pattern}`).toBe(true); }); it("is in the permission matrix", () => { expect(Object.keys(PERMISSIONS).some((k) => k.startsWith(`${id}:`)), `${id} has no keys in permissions.ts`).toBe(true); }); it("is in navigation", () => { expect(NAV_ROUTES.some((n) => n.path === `/${id}`), `feature ${id} is missing from nav-routes.ts`).toBe(true); }); it("is in the provenance map", () => expect(PROVENANCE_MAP[id], `${id} missing from provenance-map.ts`).toBeDefined()); it("has a status", () => expect(MODULE_STATUS[id], `${id} missing from module-status.ts`).toBeDefined());});
// Not features: sign-in routes, and the lesson 18 liveness probe (a publicRoute() in lesson 5's ROUTE_POLICY)const EXEMPT = ["auth", "health"];
it("every api directory is a registered feature", () => { const dirs = readdirSync(join(root, "src/app/api"), { withFileTypes: true }) .filter((d) => d.isDirectory() && !EXEMPT.includes(d.name)).map((d) => d.name); expect(dirs.filter((d) => !(FEATURE_IDS as readonly string[]).includes(d))).toEqual([]);});Two planted faults to run once and record. Delete the nav entry and the navigation test must fail naming the feature. Add an empty src/app/api/scratch/route.ts and the last test must fail naming the directory. A validator that has never failed has not shown it works.
It proves a file exists and an entry exists. It does not prove the entry is right: a permission key with the wrong minimum role passes. Lesson 5’s decision table and your review cover that. Keep the validator to presence; the more it tries to understand, the more it breaks on legitimate variation.
Check the generated output
The validator catches missing pieces. Review what it cannot:
| Check | What to look for |
|---|---|
| Column names match | SQL columns are snake_case and the schema fields must map to them exactly. A mismatch is silent: the API drops the field. |
| Zod helpers | Top-level helpers and the error option, not the older chained methods the pinned major deprecates (see Lesson 2’s baseline) |
| Every handler wrapped | A bare exported handler without withPermission() is unguarded; Lesson 5’s contract test catches it |
| Provenance column present | The table has the column from Lesson 10, so values can be traced |
| Parameterized SQL | request.input(...), never string interpolation |
Replicating seven files from a pattern is the kind of work an AI tool does faster and more consistently than copy and find-and-replace. Judging whether the permission minimums are right for your agency is not. Let the tool do the first and keep the second.
A feature's tests pass and its page renders locally. After deployment, users with the operator role see the navigation link, but every create request returns 403. Which registry is the likely gap, and which check should have caught it?
Why does the validator also check that every directory under src/app/api is a registered feature, instead of only checking the registered features?
Key takeaway
Define a feature as a contract of files plus a ledger of registrations, keep both as data, and let one validator read them and fail the build on a gap. Add the disk-driven check too, so a feature that exists but is not listed cannot hide. The seven files and five registries are the reference app’s choice; the alternative is a generator or a single manifest, and the decision is where your agency wants the source of truth to live.
- LEADERSHIP DECISION
- Where the source of truth for a feature lives (files and ledger, generator, or manifest) and who owns it.
- PRACTITIONER ACTION
- Add the contract validator and the disk-driven check to CI, then run both planted faults once.
- SUCCESS MEASURE
- Calendar time: a feature gap is caught at the pull request, not in review of the finished feature.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided