Pre-Implement Spec Skill
Performs a thorough pre-implementation analysis of a specification to catch issues before any code is written. Produces a structured report covering backward compatibility, spec completeness, risk assessment, AGENTS.md compliance, and a remediation plan.
Workflow
Phase 1 — Load Context
- Read the target spec file(s) fully from
.ai/specs/ or .ai/specs/enterprise/.
- Read
BACKWARD_COMPATIBILITY.md — the 13 contract surface categories.
- Scan the tagged
.ai/lessons.md index by affected module/area/topic and open only matching lesson records.
- Using the Task Router in
AGENTS.md, identify all relevant AGENTS.md guides for affected modules/packages.
- Read the code-review checklist at
.agents/skills/om-code-review/references/review-checklist.md.
- Identify all existing modules, entities, events, and API routes that the spec touches (use Explore subagents for large scopes).
Phase 2 — Backward Compatibility Audit
For each phase/step in the spec, check against ALL 13 contract surface categories:
| # |
Surface |
Check |
| 1 |
Auto-discovery file conventions |
Does the spec rename/remove any convention files or exports? |
| 2 |
Type definitions & interfaces |
Does the spec remove/narrow required fields on public types? |
| 3 |
Function signatures |
Does the spec change required params or return types? |
| 4 |
Import paths |
Does the spec move modules without re-export bridges? |
| 5 |
Event IDs |
Does the spec rename/remove event IDs or payload fields? |
| 6 |
Widget injection spot IDs |
Does the spec rename/remove spot IDs? |
| 7 |
API route URLs |
Does the spec rename/remove API endpoints or response fields? |
| 8 |
Database schema |
Does the spec rename/remove columns or tables? |
| 9 |
DI service names |
Does the spec rename registration keys? |
| 10 |
ACL feature IDs |
Does the spec rename feature IDs (stored in DB)? |
| 11 |
Notification type IDs |
Does the spec rename notification type strings? |
| 12 |
CLI commands |
Does the spec rename/remove CLI commands? |
| 13 |
Generated file contracts |
Does the spec change generated export names or BootstrapData? |
For each violation found:
- Classify severity: Critical (must fix before implementation) or Warning (needs deprecation bridge)
- Propose a migration path (re-export, dual-emit, alias, etc.)
- Note if a "Migration & Backward Compatibility" section is missing from the spec
Phase 3 — Spec Completeness Check
Verify the spec includes all required sections (per spec-writing skill):
For each missing section, note what should be added and why.
Phase 4 — AGENTS.md Compliance
Check that the spec's proposed implementation follows all relevant AGENTS.md rules:
Module structure:
- Does the spec place code in the correct location? (
packages/core/, packages/ui/, apps/mercato/src/modules/)
- Does it follow auto-discovery conventions? (files in correct directories with correct exports)
- Does
setup.ts declare defaultRoleFeatures for new features in acl.ts?
Data & security:
- Does the spec mention zod validation for new inputs?
- Does it use
findWithDecryption for entity queries?
- Are tenant scoping requirements addressed?
- Encryption maps mechanism — every PII / GDPR-relevant column the spec adds (names, addresses, contacts, free-text notes about people, integration credentials, secrets, document numbers) MUST be declared in a module-level
<module>/encryption.ts exporting defaultEncryptionMaps (type from @open-mercato/shared/modules/encryption). Reads MUST go through findWithDecryption / findOneWithDecryption (5-arg (em, entity, where, options?, scope?)). Equality-lookup columns declare a sibling hashField. Hand-rolled AES, crypto.subtle, custom KMS, or "encrypt later" stubs are violations. See packages/core/AGENTS.md → Encryption + apps/docs/docs/user-guide/encryption.mdx.
API & UI canonical mechanisms (no DIY substitutes):
- CRUD APIs use
makeCrudRoute({ entity, entityId, operations, schema, indexer: { entityType } }). Custom write routes use the mutation guard registry: map the route to create/update/delete (action endpoints usually update), collect registered guards, append bridgeLegacyGuard(container) when present, call runMutationGuards(...) with { userFeatures } before mutation, merge modifiedPayload, and run returned afterSuccessCallbacks after while catching/logging callback failures. See packages/core/AGENTS.md → API Routes / CRUD Factory.
- API route files export per-method
metadata (requireAuth / requireFeatures) — flag any top-level export const requireAuth.
- Backend forms use
<CrudForm> with createCrud / updateCrud / deleteCrud and createCrudFormError; lists use <DataTable> with stable entityId + extensionTableId. No raw <form>, no raw fetch. See packages/ui/AGENTS.md.
- HTTP via
apiCall / apiCallOrThrow from @open-mercato/ui/backend/utils/apiCall. Non-CrudForm writes wrapped in useGuardedMutation.
- Cache resolved via DI (
container.resolve('cache')); tags include tenant:<id> / org:<id>; invalidation declared per write path. Flag any spec proposing new Redis(...) or raw SQLite. See packages/cache/AGENTS.md.
- Are keyboard shortcuts mentioned (
Cmd/Ctrl+Enter, Escape) for every dialog?
- Are i18n keys planned (
useT() / resolveTranslations(), never hardcoded labels)?
Design System compliance for every UI mock / className snippet (root AGENTS.md → Design System Rules + .ai/ds-rules.md + .ai/ui-components.md):
- Semantic status tokens — flag any
text-red-* / bg-green-* / text-amber-* / text-emerald-* / bg-blue-* shades the spec proposes; require text-status-error-text / bg-status-success-bg / border-status-warning-border / text-status-info-icon / text-destructive instead.
- Tailwind text scale — flag any arbitrary sizes (
text-[11px], text-[13px], text-[15px], p-[13px], rounded-[24px], z-[9999]); require text-xs / text-sm / text-base / text-lg / text-xl / text-2xl or the text-overline token for 11px uppercase labels.
- Shared primitives —
<StatusBadge>, <Alert>, <FormField>, <SectionHeader>, <CollapsibleSection>, <LoadingMessage> / <Spinner> / <DataLoader>, <EmptyState>.
- Icons — lucide-react in page body (never inline
<svg>); aria-label on icon-only buttons; page.meta.ts icons via the React.createElement('svg', …) pattern.
- Boy Scout rule on any line the spec touches in an existing page.
Events & side effects:
- Are new events declared with
createModuleEvents() (with as const)?
- Do cross-module side effects use events (not direct imports)?
- Are subscribers idempotent?
Commands:
- Are write operations implemented as undoable commands?
- Is
extractUndoPayload() referenced?
Phase 5 — Risk Assessment
Identify risks in these categories:
Technical risks:
- Cross-module coupling introduced
- Performance implications (N+1 queries, large payloads)
- Migration complexity (data backfill, schema changes)
- Concurrency issues (race conditions in events/workers)
Integration risks:
- Impact on existing tests
- Impact on existing UI flows
- Impact on existing API consumers
- Impact on search indexes
Dependency risks:
- Requires changes in multiple packages
- Depends on features not yet implemented
- Circular dependency potential
For each risk, assign: High / Medium / Low severity and a mitigation strategy.
Phase 6 — Gap Analysis
Identify what's missing from the spec that would be needed for implementation:
- Missing entity definitions or unclear data models
- Missing API endpoint specifications
- Missing error handling descriptions
- Missing undo/redo behavior descriptions
- Missing event declarations for side effects
- Missing search configuration
- Missing cache invalidation strategy
- Missing worker/queue definitions
- Missing permission/ACL definitions
- Missing i18n key planning
- Missing test scenarios
Phase 7 — Output Report
Produce a structured report in this format:
# Pre-Implementation Analysis: {Spec Title}
## Executive Summary
{2-3 sentences: overall readiness, critical blockers, recommendation}
## Backward Compatibility
### Violations Found
| # | Surface | Issue | Severity | Proposed Fix |
|---|---------|-------|----------|-------------|
| 1 | {category} | {description} | Critical/Warning | {migration path} |
### Missing BC Section
{Note if spec lacks "Migration & Backward Compatibility" section}
## Spec Completeness
### Missing Sections
| Section | Impact | Recommendation |
|---------|--------|---------------|
| {section} | {what breaks without it} | {what to add} |
### Incomplete Sections
| Section | Gap | Recommendation |
|---------|-----|---------------|
| {section} | {what's missing} | {what to add} |
## AGENTS.md Compliance
### Violations
| Rule | Location | Fix |
|------|----------|-----|
| {rule from AGENTS.md} | {spec section/step} | {how to fix} |
## Risk Assessment
### High Risks
| Risk | Impact | Mitigation |
|------|--------|-----------|
| {risk} | {impact} | {mitigation} |
### Medium Risks
| Risk | Impact | Mitigation |
|------|--------|-----------|
### Low Risks
| Risk | Impact | Mitigation |
|------|--------|-----------|
## Gap Analysis
### Critical Gaps (Block Implementation)
- {gap}: {what's needed}
### Important Gaps (Should Address)
- {gap}: {what's needed}
### Nice-to-Have Gaps
- {gap}: {what's needed}
## Remediation Plan
### Before Implementation (Must Do)
1. {action}: {description}
### During Implementation (Add to Spec)
1. {action}: {description}
### Post-Implementation (Follow Up)
1. {action}: {description}
## Recommendation
{Ready to implement / Needs spec updates first / Needs major revision}
Save the report as .ai/specs/analysis/ANALYSIS-{spec-id}.md.
Subagent Strategy
| Task |
Agent Type |
When |
| Explore existing code for BC impact |
Explore |
Always — scan for existing event IDs, spot IDs, API routes, types |
| Read multiple AGENTS.md files |
Explore |
When spec touches 3+ modules |
| Scan for affected test files |
Explore |
Check which tests might break |
| Analyze entity/migration impact |
general-purpose |
When spec includes data model changes |
Launch parallel Explore agents for independent code areas (events, API routes, widgets, types).
Rules
- MUST read the full spec before starting analysis
- MUST check ALL 13 backward compatibility categories — no shortcuts
- MUST verify against actual codebase (not just spec text) — use Explore agents to find real event IDs, spot IDs, API routes
- MUST produce the structured report format — no free-form summaries
- MUST save the report to
.ai/specs/analysis/
- MUST classify every finding with severity
- MUST propose concrete fixes for every violation and gap
- MUST NOT modify any code — this skill is analysis only
- MUST NOT modify the spec directly — propose changes in the report for user review
- MUST scan
.ai/lessons.md and open only lesson records whose module/area/topic tags match the spec
1---2name: om-pre-implement-spec3description: Analyze a spec before implementation: BC audit, risk assessment, gap analysis. Produces a readiness report with BC violations, missing sections, and suggested improvements. Triggers on "analyze spec", "pre-implement", "spec readiness", "BC analysis", "spec gap analysis".4---56# Pre-Implement Spec Skill78Performs a thorough pre-implementation analysis of a specification to catch issues before any code is written. Produces a structured report covering backward compatibility, spec completeness, risk assessment, AGENTS.md compliance, and a remediation plan.910## Workflow1112### Phase 1 — Load Context13141. Read the target spec file(s) fully from `.ai/specs/` or `.ai/specs/enterprise/`.152. Read `BACKWARD_COMPATIBILITY.md` — the 13 contract surface categories.163. Scan the tagged `.ai/lessons.md` index by affected module/area/topic and open only matching lesson records.174. Using the Task Router in `AGENTS.md`, identify all relevant AGENTS.md guides for affected modules/packages.185. Read the code-review checklist at `.agents/skills/om-code-review/references/review-checklist.md`.196. Identify all existing modules, entities, events, and API routes that the spec touches (use Explore subagents for large scopes).2021### Phase 2 — Backward Compatibility Audit2223For each phase/step in the spec, check against ALL 13 contract surface categories:2425| # | Surface | Check |26|---|---------|-------|27| 1 | Auto-discovery file conventions | Does the spec rename/remove any convention files or exports? |28| 2 | Type definitions & interfaces | Does the spec remove/narrow required fields on public types? |29| 3 | Function signatures | Does the spec change required params or return types? |30| 4 | Import paths | Does the spec move modules without re-export bridges? |31| 5 | Event IDs | Does the spec rename/remove event IDs or payload fields? |32| 6 | Widget injection spot IDs | Does the spec rename/remove spot IDs? |33| 7 | API route URLs | Does the spec rename/remove API endpoints or response fields? |34| 8 | Database schema | Does the spec rename/remove columns or tables? |35| 9 | DI service names | Does the spec rename registration keys? |36| 10 | ACL feature IDs | Does the spec rename feature IDs (stored in DB)? |37| 11 | Notification type IDs | Does the spec rename notification type strings? |38| 12 | CLI commands | Does the spec rename/remove CLI commands? |39| 13 | Generated file contracts | Does the spec change generated export names or BootstrapData? |4041For each violation found:42- Classify severity: **Critical** (must fix before implementation) or **Warning** (needs deprecation bridge)43- Propose a migration path (re-export, dual-emit, alias, etc.)44- Note if a "Migration & Backward Compatibility" section is missing from the spec4546### Phase 3 — Spec Completeness Check4748Verify the spec includes all required sections (per spec-writing skill):4950- [ ] TLDR & Overview51- [ ] Problem Statement52- [ ] Proposed Solution53- [ ] Architecture (design decisions)54- [ ] Data Models (entity structures, if applicable)55- [ ] API Contracts (endpoint definitions, if applicable)56- [ ] UI/UX (wireframes or descriptions, if applicable)57- [ ] Risks & Impact Review (failure scenarios, severity, mitigation)58- [ ] Phasing (delivery breakdown)59- [ ] Implementation Plan (detailed steps per phase)60- [ ] Integration Test Coverage (test scenarios for API + UI paths)61- [ ] Final Compliance Report (spec-writing checklist results)62- [ ] Changelog6364For each missing section, note what should be added and why.6566### Phase 4 — AGENTS.md Compliance6768Check that the spec's proposed implementation follows all relevant AGENTS.md rules:6970**Module structure**:71- Does the spec place code in the correct location? (`packages/core/`, `packages/ui/`, `apps/mercato/src/modules/`)72- Does it follow auto-discovery conventions? (files in correct directories with correct exports)73- Does `setup.ts` declare `defaultRoleFeatures` for new features in `acl.ts`?7475**Data & security**:76- Does the spec mention zod validation for new inputs?77- Does it use `findWithDecryption` for entity queries?78- Are tenant scoping requirements addressed?79- **Encryption maps mechanism — every PII / GDPR-relevant column the spec adds (names, addresses, contacts, free-text notes about people, integration credentials, secrets, document numbers) MUST be declared in a module-level `<module>/encryption.ts` exporting `defaultEncryptionMaps` (type from `@open-mercato/shared/modules/encryption`). Reads MUST go through `findWithDecryption` / `findOneWithDecryption` (5-arg `(em, entity, where, options?, scope?)`). Equality-lookup columns declare a sibling `hashField`. Hand-rolled AES, `crypto.subtle`, custom KMS, or "encrypt later" stubs are violations. See `packages/core/AGENTS.md` → Encryption + `apps/docs/docs/user-guide/encryption.mdx`.**8081**API & UI canonical mechanisms** (no DIY substitutes):82- **CRUD APIs use `makeCrudRoute({ entity, entityId, operations, schema, indexer: { entityType } })`. Custom write routes use the mutation guard registry: map the route to `create`/`update`/`delete` (action endpoints usually `update`), collect registered guards, append `bridgeLegacyGuard(container)` when present, call `runMutationGuards(...)` with `{ userFeatures }` before mutation, merge `modifiedPayload`, and run returned `afterSuccessCallbacks` after while catching/logging callback failures.** See `packages/core/AGENTS.md` → API Routes / CRUD Factory.83- **API route files export per-method `metadata`** (`requireAuth` / `requireFeatures`) — flag any top-level `export const requireAuth`.84- **Backend forms use `<CrudForm>`** with `createCrud` / `updateCrud` / `deleteCrud` and `createCrudFormError`; lists use `<DataTable>` with stable `entityId` + `extensionTableId`. No raw `<form>`, no raw `fetch`. See `packages/ui/AGENTS.md`.85- **HTTP via `apiCall` / `apiCallOrThrow`** from `@open-mercato/ui/backend/utils/apiCall`. Non-`CrudForm` writes wrapped in `useGuardedMutation`.86- **Cache resolved via DI** (`container.resolve('cache')`); tags include `tenant:<id>` / `org:<id>`; invalidation declared per write path. Flag any spec proposing `new Redis(...)` or raw SQLite. See `packages/cache/AGENTS.md`.87- Are keyboard shortcuts mentioned (`Cmd/Ctrl+Enter`, `Escape`) for every dialog?88- Are i18n keys planned (`useT()` / `resolveTranslations()`, never hardcoded labels)?8990**Design System compliance for every UI mock / className snippet** (root `AGENTS.md` → Design System Rules + `.ai/ds-rules.md` + `.ai/ui-components.md`):91- Semantic status tokens — flag any `text-red-*` / `bg-green-*` / `text-amber-*` / `text-emerald-*` / `bg-blue-*` shades the spec proposes; require `text-status-error-text` / `bg-status-success-bg` / `border-status-warning-border` / `text-status-info-icon` / `text-destructive` instead.92- Tailwind text scale — flag any arbitrary sizes (`text-[11px]`, `text-[13px]`, `text-[15px]`, `p-[13px]`, `rounded-[24px]`, `z-[9999]`); require `text-xs` / `text-sm` / `text-base` / `text-lg` / `text-xl` / `text-2xl` or the `text-overline` token for 11px uppercase labels.93- Shared primitives — `<StatusBadge>`, `<Alert>`, `<FormField>`, `<SectionHeader>`, `<CollapsibleSection>`, `<LoadingMessage>` / `<Spinner>` / `<DataLoader>`, `<EmptyState>`.94- Icons — lucide-react in page body (never inline `<svg>`); `aria-label` on icon-only buttons; `page.meta.ts` icons via the `React.createElement('svg', …)` pattern.95- Boy Scout rule on any line the spec touches in an existing page.9697**Events & side effects**:98- Are new events declared with `createModuleEvents()` (with `as const`)?99- Do cross-module side effects use events (not direct imports)?100- Are subscribers idempotent?101102**Commands**:103- Are write operations implemented as undoable commands?104- Is `extractUndoPayload()` referenced?105106### Phase 5 — Risk Assessment107108Identify risks in these categories:109110**Technical risks**:111- Cross-module coupling introduced112- Performance implications (N+1 queries, large payloads)113- Migration complexity (data backfill, schema changes)114- Concurrency issues (race conditions in events/workers)115116**Integration risks**:117- Impact on existing tests118- Impact on existing UI flows119- Impact on existing API consumers120- Impact on search indexes121122**Dependency risks**:123- Requires changes in multiple packages124- Depends on features not yet implemented125- Circular dependency potential126127For each risk, assign: **High** / **Medium** / **Low** severity and a mitigation strategy.128129### Phase 6 — Gap Analysis130131Identify what's missing from the spec that would be needed for implementation:132133- Missing entity definitions or unclear data models134- Missing API endpoint specifications135- Missing error handling descriptions136- Missing undo/redo behavior descriptions137- Missing event declarations for side effects138- Missing search configuration139- Missing cache invalidation strategy140- Missing worker/queue definitions141- Missing permission/ACL definitions142- Missing i18n key planning143- Missing test scenarios144145### Phase 7 — Output Report146147Produce a structured report in this format:148149```markdown150# Pre-Implementation Analysis: {Spec Title}151152## Executive Summary153{2-3 sentences: overall readiness, critical blockers, recommendation}154155## Backward Compatibility156157### Violations Found158| # | Surface | Issue | Severity | Proposed Fix |159|---|---------|-------|----------|-------------|160| 1 | {category} | {description} | Critical/Warning | {migration path} |161162### Missing BC Section163{Note if spec lacks "Migration & Backward Compatibility" section}164165## Spec Completeness166167### Missing Sections168| Section | Impact | Recommendation |169|---------|--------|---------------|170| {section} | {what breaks without it} | {what to add} |171172### Incomplete Sections173| Section | Gap | Recommendation |174|---------|-----|---------------|175| {section} | {what's missing} | {what to add} |176177## AGENTS.md Compliance178179### Violations180| Rule | Location | Fix |181|------|----------|-----|182| {rule from AGENTS.md} | {spec section/step} | {how to fix} |183184## Risk Assessment185186### High Risks187| Risk | Impact | Mitigation |188|------|--------|-----------|189| {risk} | {impact} | {mitigation} |190191### Medium Risks192| Risk | Impact | Mitigation |193|------|--------|-----------|194195### Low Risks196| Risk | Impact | Mitigation |197|------|--------|-----------|198199## Gap Analysis200201### Critical Gaps (Block Implementation)202- {gap}: {what's needed}203204### Important Gaps (Should Address)205- {gap}: {what's needed}206207### Nice-to-Have Gaps208- {gap}: {what's needed}209210## Remediation Plan211212### Before Implementation (Must Do)2131. {action}: {description}214215### During Implementation (Add to Spec)2161. {action}: {description}217218### Post-Implementation (Follow Up)2191. {action}: {description}220221## Recommendation222{Ready to implement / Needs spec updates first / Needs major revision}223```224225Save the report as `.ai/specs/analysis/ANALYSIS-{spec-id}.md`.226227## Subagent Strategy228229| Task | Agent Type | When |230|------|-----------|------|231| Explore existing code for BC impact | Explore | Always — scan for existing event IDs, spot IDs, API routes, types |232| Read multiple AGENTS.md files | Explore | When spec touches 3+ modules |233| Scan for affected test files | Explore | Check which tests might break |234| Analyze entity/migration impact | general-purpose | When spec includes data model changes |235236Launch parallel Explore agents for independent code areas (events, API routes, widgets, types).237238## Rules239240- MUST read the full spec before starting analysis241- MUST check ALL 13 backward compatibility categories — no shortcuts242- MUST verify against actual codebase (not just spec text) — use Explore agents to find real event IDs, spot IDs, API routes243- MUST produce the structured report format — no free-form summaries244- MUST save the report to `.ai/specs/analysis/`245- MUST classify every finding with severity246- MUST propose concrete fixes for every violation and gap247- MUST NOT modify any code — this skill is analysis only248- MUST NOT modify the spec directly — propose changes in the report for user review249- MUST scan `.ai/lessons.md` and open only lesson records whose module/area/topic tags match the spec