Applied AI-Accelerated Government Development

Define and Integrate a Feature

Updated

Intermediate

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

ProblemThe patternWhere your platform lesson lands itYou decide
A feature is missing a fileA file contract kept as data and checked; the alternative is a generator or template repository that emits every fileSame on every platform; 37: the pipeline step that runs the checkWhether the contract is checked or generated
A feature is missing from a registryFive registries, each keyed by feature id, checked; the alternative is one manifest per feature that all registries derive fromSame on every platformWhere the single source of truth lives
When the gap is foundAt build, before deployment; the alternative is at pull-request review37: a required check on the protected branch, in GitHub, GitLab, Azure DevOps or BitbucketWhether a gap may merge
What the files must look likeThe reference conventions, shown below; the alternative is your agency’s ownSame on every platformWhich 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.

  1. 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.
  2. Types (src/types/<feature>.ts): Zod schemas for request and response bodies, plus the types inferred from them.
  3. Route (src/app/api/<feature>/route.ts): handlers wrapped in withPermission() (Lesson 5), using the response helpers from Lesson 7.
  4. Hook (src/hooks/use<Feature>.ts): SWR reads and mutations (Lesson 9).
  5. Page (src/app/(protected)/<feature>/page.tsx): the MUI page with the tiered views from Lesson 11.
  6. Tests (tests/<feature>.test.ts): the schemas and the route handlers.
  7. 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:

src/features/contract.ts
// {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.

RegistryFileWhat it holds for the feature
Feature idssrc/config/features.tsThe id itself, in one array
Permission matrixsrc/lib/auth/permissions.tsKeys such as vehicle-fleet:read, each with a minimum role (Lesson 5)
Navigationsrc/config/nav-routes.tsLabel, path, required permission, group
Provenance mapsrc/config/provenance-map.tsThe tables the feature owns and their default data source
Statussrc/config/module-status.tsdevelopment, staging, production, or deprecated, and an owner

Here is the reference feature-ID registry in src/config/features.ts that your agent updates:

src/config/features.ts
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.

ToolPlan before building
Claude Codeclaude, then Shift+Tab or /plan
Codexcodex --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)
Antigravityagy, then Shift+Tab or /plan
Copilotcopilot, 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_fleet table with data_source and audit columns), Zod schemas in src/types/vehicle-fleet.ts, GET and POST handlers in src/app/api/vehicle-fleet/route.ts wrapped in withPermission() and querying through withPool(), SWR hooks in src/hooks/useVehicleFleet.ts, the page in src/app/(protected)/vehicle-fleet/page.tsx, tests in tests/vehicle-fleet.test.ts, and styles in src/styles/vehicle-fleet.module.css.
  • The plan adds "vehicle-fleet" to all five registries (features.ts, permissions.ts, nav-routes.ts, provenance-map.ts, and module-status.ts) without modifying or reordering existing entries.
  • tests/contract/features.test.ts checks that every ID in FEATURE_IDS has every file in FEATURE_FILES and an entry in each registry, and that every directory under src/app/api (except exempt routes) is a registered feature ID, wired into package.json as "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

SESSION Plan read-only, approve, build, then let the validator find the gaps
  1. Typed in the terminal: claude
  2. Mode:Plan mode
  3. 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.
  4. 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?
  5. Mode:Plan approved: plan mode off
  6. 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.
  7. 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.
  8. You type in the session: Now register vehicle-fleet in the five registries with the 'work' group and add the contract validator test.
  9. 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.
  10. You type in the session: Add a directory src/app/api/scratch with a route.ts and run it again. Then remove the directory.
  11. 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.
tests/contract/features.test.ts
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.

⚠What the validator does not check

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:

CheckWhat to look for
Column names matchSQL columns are snake_case and the schema fields must map to them exactly. A mismatch is silent: the API drops the field.
Zod helpersTop-level helpers and the error option, not the older chained methods the pinned major deprecates (see Lesson 2’s baseline)
Every handler wrappedA bare exported handler without withPermission() is unguarded; Lesson 5’s contract test catches it
Provenance column presentThe table has the column from Lesson 10, so values can be traced
Parameterized SQLrequest.input(...), never string interpolation
💬Where the AI earns its keep, and where it does not

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.


KNOWLEDGE CHECK

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?

KNOWLEDGE CHECK

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

Search lessons