Implement Spec Skill
Implements a specification (or selected phases) end-to-end using a team of coordinated subagents. Every code change MUST pass the code-review checklist before the phase is considered done.
Pre-Flight
- Identify the spec: Locate the target spec file in
.ai/specs/.
- Load context: Read spec fully. Match affected tasks to the Task → Context Map in
AGENTS.md and read all listed files (guides and skills).
- Load code-review checklist: Read
.ai/skills/code-review/references/review-checklist.md — this is the acceptance gate for every phase.
- Load lessons: Read
.ai/lessons.md for known pitfalls.
- Scope phases: If the user specifies phases (e.g. "phases c-e"), filter to only those. Otherwise implement all phases sequentially.
Implementation Workflow
For each phase in the spec, execute these steps:
Step 1 — Plan the Phase
Read the phase from the spec. For each step within the phase:
- Identify files to create or modify (all paths under
src/modules/)
- Identify which guides and skills apply (use the Task → Context Map in
AGENTS.md)
- List required exports, conventions, and patterns from the relevant guides
- Note any cross-module impacts (events, extensions, widgets, enrichers)
Present a brief plan to the user before coding.
Step 2 — Implement
Use subagents liberally to parallelize independent work:
- One subagent per independent file/component when files don't depend on each other
- Sequential execution when there are dependencies (e.g., entity before API route before backend page)
For every piece of code, enforce these code-review rules inline:
| Area |
Rule |
| Types |
No any — use zod + z.infer |
| API routes |
Export openApi and per-method metadata with requireAuth / requireFeatures (no top-level export const requireAuth) |
| CRUD APIs |
Use makeCrudRoute({ entity, entityId, operations, schema, indexer: { entityType } }) from @open-mercato/shared/lib/crud/factory. Custom write routes MUST call validateCrudMutationGuard before the mutation and runCrudMutationGuardAfterSuccess after success. See AGENTS.md → Mandatory Module Mechanisms. |
| Entities |
Standard columns, snake_case, UUID PKs, indexed organization_id + tenant_id |
| Security |
findWithDecryption, tenant scoping, zod validation |
| Encryption maps |
For every PII / GDPR-relevant column the phase touches, declare in <module>/encryption.ts exporting defaultEncryptionMaps (type from @open-mercato/shared/modules/encryption). Reads via findWithDecryption / findOneWithDecryption (5-arg (em, entity, where, options?, scope?)). Equality-lookup columns declare a sibling hashField. NEVER hand-rolled AES/KMS, crypto.subtle, or "encrypt later" stubs. See AGENTS.md → CRITICAL Rule #11 (Encryption maps) + the "Encryption maps" row of the Mandatory Module Mechanisms table; .ai/skills/data-model-design/SKILL.md § Sensitive Data and Encryption Maps; .ai/skills/module-scaffold/SKILL.md § Encryption maps. |
| UI |
<CrudForm>/<DataTable> (with stable entityId + extensionTableId), apiCall (never raw fetch), flash(), <LoadingMessage>/<ErrorMessage> |
| Design System |
Semantic status tokens (no text-red-* / bg-green-*); Tailwind text scale (no text-[13px] / text-[11px]); shared primitives StatusBadge / Alert / FormField / SectionHeader / CollapsibleSection / LoadingMessage / Spinner / DataLoader / EmptyState; lucide-react icons in PAGE BODY (never inline <svg>); aria-label on every icon-only button; Boy Scout rule on touched lines. See AGENTS.md → CRITICAL Rule #10 (Strict Design System alignment) + .ai/skills/backend-ui-design/SKILL.md. |
| Cache |
Resolve via DI (container.resolve('cache')); tag with tenant:<id> / org:<id>; declare invalidation per write path. NEVER new Redis(...) or raw SQLite. |
| Events |
createModuleEvents() with as const, subscribers export metadata; cross-module side effects via subscribers, never direct imports |
| i18n |
useT() client, resolveTranslations() server, no hardcoded strings |
| Imports |
Package-level @open-mercato/<pkg>/... for framework imports |
| Mutations |
useGuardedMutation when not using CrudForm; pass retryLastMutation in injection context |
| Keyboard |
Cmd/Ctrl+Enter submit, Escape cancel on dialogs |
| Naming |
Modules plural snake_case, events module.entity.past_tense, features module.action |
Step 3 — Unit Tests
For every new feature/function implemented in the phase:
- Create unit tests colocated with the source (e.g.,
*.test.ts or __tests__/)
- Test happy path + key edge cases
- Test error paths for validation and authorization
- Mock external dependencies (DI services, data engine)
- Verify tests pass:
yarn test
Step 4 — Integration Tests
If the spec defines integration test scenarios (or the phase adds API endpoints / UI flows):
- Follow the
integration-tests skill workflow (.ai/skills/integration-tests/SKILL.md)
- Place tests in
src/modules/<module>/__integration__/TC-{CATEGORY}-{XXX}.spec.ts
- Tests MUST be self-contained: create fixtures in setup, clean up in teardown
- Tests MUST NOT rely on seeded/demo data
- Run and verify:
npx playwright test --config .ai/qa/tests/playwright.config.ts <path> --retries=0
If the spec does not explicitly list integration scenarios but the phase adds significant API or UI behavior, propose test scenarios to the user before writing them.
Step 5 — Documentation
For each new feature:
- Add/update locale files for new i18n keys
- If new entities with user-facing text: create
translations.ts
- If new convention files: run
yarn generate
- Update relevant guides or
AGENTS.md if the feature introduces new patterns developers should follow
Step 6 — Self-Review (Code-Review Gate)
Before marking a phase complete, run a self-review against the checklist (.ai/skills/code-review/references/review-checklist.md):
- Architecture & Module Independence (section 1)
- Security (section 2)
- Data Integrity & ORM (section 3)
- API Routes (section 4) — if applicable
- Events & Commands (section 5) — if applicable
- UI & Backend Pages (section 6) — if applicable
- Naming Conventions (section 7)
- Anti-Patterns (section 8)
Fix any violations before proceeding to the next phase.
Step 7 — Update Spec with Progress
After completing each phase, update the spec file:
- Add an
## Implementation Status section at the bottom (or update it if it exists)
- Use this format:
## Implementation Status
| Phase | Status | Date | Notes |
|-------|--------|------|-------|
| Phase A — Foundation | Done | 2026-02-20 | All steps implemented, tests passing |
| Phase B — Menu Injection | Done | 2026-02-21 | 3/3 steps complete |
| Phase C — Events Bridge | In Progress | 2026-02-22 | Step 1-2 done, step 3 pending |
| Phase D — Enrichers | Not Started | — | — |
- For the current phase, mark individual steps:
### Phase C — Detailed Progress
- [x] Step 1: Create event definitions
- [x] Step 2: Implement SSE bridge
- [ ] Step 3: Add client-side hooks
Step 8 — Verification
After all targeted phases are complete:
- Generate check:
yarn generate — must complete without errors
- Type check:
yarn typecheck — must pass (if available)
- Build check:
yarn build — must pass
- Unit test check:
yarn test — must pass
- Integration test check: run any new integration tests — must pass
- Migration check:
yarn db:generate — if any entities changed (verify the resulting SQL is scoped correctly; manual SQL is acceptable only when avoiding unrelated churn, and the touched .snapshot-open-mercato.json must match)
Report results to the user. If any check fails, fix and re-verify.
Subagent Strategy
| Task |
Agent Type |
When |
| Research existing patterns |
Explore |
Before implementing unfamiliar patterns |
| Implement independent files |
general-purpose |
When files have no dependencies on each other |
| Run tests |
Bash |
After each phase |
| Self-review |
general-purpose |
After each phase, against checklist |
| Integration tests |
general-purpose |
After phases with API/UI changes |
Concurrency rule: Launch parallel subagents only for truly independent work. Sequential for dependent files.
Rules
- MUST read the full spec before starting implementation
- MUST read all guides and skills listed in the Task → Context Map before coding
- MUST pass every applicable code-review checklist item before marking a phase done
- MUST update the spec with implementation progress after each phase
- MUST run
yarn build after final phase to verify no build breaks
- MUST create unit tests for all new behavioral code
- MUST create or propose integration tests for phases with API endpoints or UI flows
- MUST NOT skip the self-review step — it is the quality gate
- MUST NOT introduce
any types, hardcoded strings, raw fetch, or other anti-patterns
- MUST keep subagents focused — one task per subagent, clear boundaries
- MUST report blockers to the user immediately rather than working around them silently
- MUST run
yarn generate after creating or modifying module convention files
- MUST run
yarn db:generate after creating or modifying entities (and confirm migration with user before applying)
1---2name: implement-spec-23description: Implement a specification (or specific phases of a spec) using coordinated subagents. Handles multi-phase spec implementation with unit tests, integration tests, documentation, and code-review compliance. Use when the user says "implement spec", "implement the spec", "implement phases", "build from spec", or "code the spec". Tracks progress by updating the spec with implementation status.4---56# Implement Spec Skill78Implements a specification (or selected phases) end-to-end using a team of coordinated subagents. Every code change MUST pass the code-review checklist before the phase is considered done.910## Pre-Flight11121. **Identify the spec**: Locate the target spec file in `.ai/specs/`.132. **Load context**: Read spec fully. Match affected tasks to the **Task → Context Map** in `AGENTS.md` and read all listed files (guides and skills).143. **Load code-review checklist**: Read `.ai/skills/code-review/references/review-checklist.md` — this is the acceptance gate for every phase.154. **Load lessons**: Read `.ai/lessons.md` for known pitfalls.165. **Scope phases**: If the user specifies phases (e.g. "phases c-e"), filter to only those. Otherwise implement all phases sequentially.1718## Implementation Workflow1920For **each phase** in the spec, execute these steps:2122### Step 1 — Plan the Phase2324Read the phase from the spec. For each step within the phase:25- Identify files to create or modify (all paths under `src/modules/`)26- Identify which guides and skills apply (use the Task → Context Map in `AGENTS.md`)27- List required exports, conventions, and patterns from the relevant guides28- Note any cross-module impacts (events, extensions, widgets, enrichers)2930Present a brief plan to the user before coding.3132### Step 2 — Implement3334Use subagents liberally to parallelize independent work:35- **One subagent per independent file/component** when files don't depend on each other36- **Sequential execution** when there are dependencies (e.g., entity before API route before backend page)3738For every piece of code, enforce these code-review rules inline:3940| Area | Rule |41|------|------|42| Types | No `any` — use zod + `z.infer` |43| API routes | Export `openApi` and per-method `metadata` with `requireAuth` / `requireFeatures` (no top-level `export const requireAuth`) |44| **CRUD APIs** | **Use `makeCrudRoute({ entity, entityId, operations, schema, indexer: { entityType } })` from `@open-mercato/shared/lib/crud/factory`. Custom write routes MUST call `validateCrudMutationGuard` before the mutation and `runCrudMutationGuardAfterSuccess` after success. See `AGENTS.md` → Mandatory Module Mechanisms.** |45| Entities | Standard columns, snake_case, UUID PKs, indexed `organization_id` + `tenant_id` |46| Security | `findWithDecryption`, tenant scoping, zod validation |47| **Encryption maps** | **For every PII / GDPR-relevant column the phase touches, declare in `<module>/encryption.ts` exporting `defaultEncryptionMaps` (type from `@open-mercato/shared/modules/encryption`). Reads via `findWithDecryption` / `findOneWithDecryption` (5-arg `(em, entity, where, options?, scope?)`). Equality-lookup columns declare a sibling `hashField`. NEVER hand-rolled AES/KMS, `crypto.subtle`, or "encrypt later" stubs. See `AGENTS.md` → CRITICAL Rule #11 (Encryption maps) + the "Encryption maps" row of the Mandatory Module Mechanisms table; `.ai/skills/data-model-design/SKILL.md` § Sensitive Data and Encryption Maps; `.ai/skills/module-scaffold/SKILL.md` § Encryption maps.** |48| UI | `<CrudForm>`/`<DataTable>` (with stable `entityId` + `extensionTableId`), `apiCall` (never raw `fetch`), `flash()`, `<LoadingMessage>`/`<ErrorMessage>` |49| **Design System** | **Semantic status tokens (no `text-red-*` / `bg-green-*`); Tailwind text scale (no `text-[13px]` / `text-[11px]`); shared primitives `StatusBadge` / `Alert` / `FormField` / `SectionHeader` / `CollapsibleSection` / `LoadingMessage` / `Spinner` / `DataLoader` / `EmptyState`; lucide-react icons in PAGE BODY (never inline `<svg>`); `aria-label` on every icon-only button; Boy Scout rule on touched lines. See `AGENTS.md` → CRITICAL Rule #10 (Strict Design System alignment) + `.ai/skills/backend-ui-design/SKILL.md`.** |50| **Cache** | **Resolve via DI (`container.resolve('cache')`); tag with `tenant:<id>` / `org:<id>`; declare invalidation per write path. NEVER `new Redis(...)` or raw SQLite.** |51| Events | `createModuleEvents()` with `as const`, subscribers export `metadata`; cross-module side effects via subscribers, never direct imports |52| i18n | `useT()` client, `resolveTranslations()` server, no hardcoded strings |53| Imports | Package-level `@open-mercato/<pkg>/...` for framework imports |54| Mutations | `useGuardedMutation` when not using CrudForm; pass `retryLastMutation` in injection context |55| Keyboard | `Cmd/Ctrl+Enter` submit, `Escape` cancel on dialogs |56| Naming | Modules plural snake_case, events `module.entity.past_tense`, features `module.action` |5758### Step 3 — Unit Tests5960For every new feature/function implemented in the phase:61- Create unit tests colocated with the source (e.g., `*.test.ts` or `__tests__/`)62- Test happy path + key edge cases63- Test error paths for validation and authorization64- Mock external dependencies (DI services, data engine)65- Verify tests pass: `yarn test`6667### Step 4 — Integration Tests6869If the spec defines integration test scenarios (or the phase adds API endpoints / UI flows):70- Follow the `integration-tests` skill workflow (`.ai/skills/integration-tests/SKILL.md`)71- Place tests in `src/modules/<module>/__integration__/TC-{CATEGORY}-{XXX}.spec.ts`72- Tests MUST be self-contained: create fixtures in setup, clean up in teardown73- Tests MUST NOT rely on seeded/demo data74- Run and verify: `npx playwright test --config .ai/qa/tests/playwright.config.ts <path> --retries=0`7576If the spec does not explicitly list integration scenarios but the phase adds significant API or UI behavior, propose test scenarios to the user before writing them.7778### Step 5 — Documentation7980For each new feature:81- Add/update locale files for new i18n keys82- If new entities with user-facing text: create `translations.ts`83- If new convention files: run `yarn generate`84- Update relevant guides or `AGENTS.md` if the feature introduces new patterns developers should follow8586### Step 6 — Self-Review (Code-Review Gate)8788Before marking a phase complete, run a self-review against the checklist (`.ai/skills/code-review/references/review-checklist.md`):89901. **Architecture & Module Independence** (section 1)912. **Security** (section 2)923. **Data Integrity & ORM** (section 3)934. **API Routes** (section 4) — if applicable945. **Events & Commands** (section 5) — if applicable956. **UI & Backend Pages** (section 6) — if applicable967. **Naming Conventions** (section 7)978. **Anti-Patterns** (section 8)9899Fix any violations before proceeding to the next phase.100101### Step 7 — Update Spec with Progress102103After completing each phase, update the spec file:104- Add an `## Implementation Status` section at the bottom (or update it if it exists)105- Use this format:106107```markdown108## Implementation Status109110| Phase | Status | Date | Notes |111|-------|--------|------|-------|112| Phase A — Foundation | Done | 2026-02-20 | All steps implemented, tests passing |113| Phase B — Menu Injection | Done | 2026-02-21 | 3/3 steps complete |114| Phase C — Events Bridge | In Progress | 2026-02-22 | Step 1-2 done, step 3 pending |115| Phase D — Enrichers | Not Started | — | — |116```117118- For the current phase, mark individual steps:119120```markdown121### Phase C — Detailed Progress122- [x] Step 1: Create event definitions123- [x] Step 2: Implement SSE bridge124- [ ] Step 3: Add client-side hooks125```126127### Step 8 — Verification128129After all targeted phases are complete:1301311. **Generate check**: `yarn generate` — must complete without errors1322. **Type check**: `yarn typecheck` — must pass (if available)1333. **Build check**: `yarn build` — must pass1344. **Unit test check**: `yarn test` — must pass1355. **Integration test check**: run any new integration tests — must pass1366. **Migration check**: `yarn db:generate` — if any entities changed (verify the resulting SQL is scoped correctly; manual SQL is acceptable only when avoiding unrelated churn, and the touched `.snapshot-open-mercato.json` must match)137138Report results to the user. If any check fails, fix and re-verify.139140## Subagent Strategy141142| Task | Agent Type | When |143|------|-----------|------|144| Research existing patterns | Explore | Before implementing unfamiliar patterns |145| Implement independent files | general-purpose | When files have no dependencies on each other |146| Run tests | Bash | After each phase |147| Self-review | general-purpose | After each phase, against checklist |148| Integration tests | general-purpose | After phases with API/UI changes |149150**Concurrency rule**: Launch parallel subagents only for truly independent work. Sequential for dependent files.151152## Rules153154- MUST read the full spec before starting implementation155- MUST read all guides and skills listed in the Task → Context Map before coding156- MUST pass every applicable code-review checklist item before marking a phase done157- MUST update the spec with implementation progress after each phase158- MUST run `yarn build` after final phase to verify no build breaks159- MUST create unit tests for all new behavioral code160- MUST create or propose integration tests for phases with API endpoints or UI flows161- MUST NOT skip the self-review step — it is the quality gate162- MUST NOT introduce `any` types, hardcoded strings, raw `fetch`, or other anti-patterns163- MUST keep subagents focused — one task per subagent, clear boundaries164- MUST report blockers to the user immediately rather than working around them silently165- MUST run `yarn generate` after creating or modifying module convention files166- MUST run `yarn db:generate` after creating or modifying entities (and confirm migration with user before applying)