# Spec Workflow Rules

Rules governing spec-first development, conformance verification, and spec maintenance.
Parent: [process.md](process.md) | Index: [rules/index.md](index.md)

### Live Spec Policy

A `docs/SPEC.md` is a **living document**. It is never "done" — it grows with every change to its
package. The spec is the canonical description of what the package is _right now_, not what it was
when it was first written.

**Universal update mandate.** Every PR that introduces any of the following MUST update the
governing `docs/SPEC.md` in the same PR:

| What changed                                   | SPEC section to update                  |
| ---------------------------------------------- | --------------------------------------- |
| New or removed public export                   | Public API Surface                      |
| New or changed type or interface               | Type Ownership                          |
| New class or `implements`/`extends` relation   | Class Contract Registry                 |
| New or changed error type or code              | Error Taxonomy                          |
| New or changed lifecycle event                 | State Lifecycle / Event Architecture    |
| New or changed behavior or semantics           | Architecture Overview, relevant section |
| New extension point (abstract class, callback) | Extension Points                        |

A PR that changes package behavior without updating the SPEC is an **incomplete change** — treated
the same as a missing test or a build failure.

**Incremental evolution.** Only the sections affected by a change need to be updated. Never
rewrite the whole document for a localized change. Add, edit, or remove only the rows, paragraphs,
or tables that describe the changed behavior.

**Spec-first invariant.** Write the new SPEC section(s) before writing implementation code. The
spec is the design artifact. Implementation fills in what the spec already describes. Back-filling
the spec after implementation is a process violation — the spec must come first.

**Spec drift is a process violation.** If `docs/SPEC.md` no longer accurately describes the
current state of its package, every subsequent PR on that package is incomplete. When drift is
detected, schedule a SPEC catch-up as a dedicated backlog item before continuing normal work. See
[`spec-code-conformance`](../skills/spec-code-conformance/SKILL.md) for the drift resolution loop.

### Spec-First Development

- Any change touching a contract boundary (package imports, class dependencies, service connections, cross-package types) MUST update or create the governing spec BEFORE writing implementation code.
- Spec format follows the boundary type:
  - HTTP API → standardized API specification (e.g., OpenAPI)
  - Package public surface → `docs/SPEC.md`
  - Class/interface dependency → contract definition in the owning package
- Every spec change MUST include a verification test plan.
- Implementation code that does not conform to its governing spec is a bug.
- See [`spec-first-development`](../skills/spec-first-development/SKILL.md) skill for the procedural workflow.
- For any new gap, fix, or improvement: write a spec document to `.agents/spec-docs/draft/` first using [`backlog-writer`](../skills/backlog-writer/SKILL.md), then run [`backlog-pipeline`](../skills/backlog-pipeline/SKILL.md).

### User Request Implementation Gate (mandatory, zero exceptions)

When the user sends any message requesting implementation, code changes, feature additions, fixes,
or modifications, the agent MUST follow this sequence regardless of how the request is phrased:

**Allowed before spec exists:**

- Read files, explore the codebase (`Read`, `grep`, `find`, `git log`, `Bash` with read-only commands)
- Ask clarifying questions
- Write spec documents (backlog draft, SPEC.md)

**Not allowed before spec exists:**

- `Write` or `Edit` to any `.ts`, `.tsx`, `.js`, `.mjs` file
- Creating new source code files
- Running code generation commands

**Sequence for any user-requested code change:**

1. Read-only exploration to understand the codebase (allowed immediately)
2. Create backlog draft: `.agents/spec-docs/draft/<TYPE>-NNN-<slug>.md`
   - Use [`backlog-writer`](../skills/backlog-writer/SKILL.md)
   - All required frontmatter and sections must be present
3. Run [`backlog-pipeline`](../skills/backlog-pipeline/SKILL.md) through GATE-APPROVAL
4. Implement only after GATE-APPROVAL passes

**Waiver**: If the user explicitly says "skip the spec" or "just fix it now", the agent must
acknowledge the waiver in its response before proceeding, and note it as a process exception.

**Automated enforcement**: `.claude/hooks/spec-first-gate.sh` (UserPromptSubmit hook) injects
this reminder when implementation-intent keywords are detected in the user's prompt.

### HARD GATE: No Immediate Implementation

Any gap, improvement, or fix discovered during development MUST follow this sequence before writing a single line of code:

1. **Architecture review** — analyse the problem and affected scope.
2. **Spec document** — write to `.agents/spec-docs/draft/` using [`backlog-writer`](../skills/backlog-writer/SKILL.md). All required sections and frontmatter must be present.
3. **Gate pipeline** — run [`backlog-pipeline`](../skills/backlog-pipeline/SKILL.md) to advance through GATE-WRITE → GATE-APPROVAL before any implementation.
4. **User approval** — GATE-APPROVAL requires an explicit user sign-off quoted in the Evidence Log.
5. **Implement** — code only after GATE-APPROVAL passes. Use [`backlog-gate-guard`](../skills/backlog-gate-guard/SKILL.md) for GATE-IMPLEMENT, GATE-VERIFY, and GATE-COMPLETE.

No exceptions. One-line fixes, evaluation findings, and "obvious" improvements all require this gate.
A spec update is also required for any change touching a contract boundary (see Spec-First Development).

**Status levels (frontmatter `status:` field):** `draft → review-ready → approved → in-progress → verifying → done`
**Lifecycle folders:** `spec-docs/draft/` → `spec-docs/backlog/` → `spec-docs/todo/` → `spec-docs/active/` → `spec-docs/done/`
Each status transition is a gate. Every gate must leave an Evidence Log entry (PASS / FAIL / NON-COMPLIANCE).

### Spec-Code Conformance Verification

- Any SPEC.md or contract document change MUST be followed by a conformance verification loop before the change is considered complete.
- The spec is the source of truth. The loop compares every spec assertion against implementation code, lists all gaps, and fixes the **code** (not the spec) to match.
- Each code fix MUST include a corresponding contract test.
- The loop repeats until zero discrepancies remain, then regression tests for all affected packages MUST pass.
- A spec change without conformance verification is an incomplete change.
- **Any code change MUST be preceded by a spec update.** Update the SPEC first to describe the intended state, then modify code to conform. Never modify code without updating or verifying the governing spec.
- See [`spec-code-conformance`](../skills/spec-code-conformance/SKILL.md) skill for the full procedure.

### ABSOLUTE RULE: Verification does not modify SPEC to match code

- During SPEC-Code verification, if a mismatch is found, **ALWAYS fix the code to match the SPEC**. NEVER modify the SPEC to match the code as a verification fix.
- The SPEC is the source of truth during verification. Modifying the SPEC to match code during verification **invalidates the entire verification process**.
- If the code was intentionally changed and the SPEC is now outdated, this is a **process violation** — the SPEC should have been updated BEFORE or TOGETHER WITH the code change, not during the verification step.
- **Exception: SPEC itself is wrong.** If the SPEC contains errors, contradictions, or inaccuracies, it is valid to correct the SPEC — but this must be done as a **separate deliberate action** before code verification:
  1. Stop code verification
  2. Validate and correct the SPEC (separate step, clearly intentional)
  3. Confirm the SPEC is accurate
  4. Restart code verification from scratch against the corrected SPEC
- The key distinction: fixing a genuinely wrong SPEC is acceptable. Changing a correct SPEC to avoid fixing code is not.

### Reverse Spec Verification (Code → Spec)

- Any refactoring that affects package boundaries (dependency changes, export additions/removals, class splits/moves) MUST be followed by a reverse verification of the affected package's SPEC.md.
- The verification checks that the SPEC still accurately describes the current code — not just that the code matches the spec.
- A refactoring without updated SPEC.md is an incomplete change, same as a spec change without conformance verification.

### Document Authority and Content Placement

Architecture documents, design documents, and package SPEC files have different authority. A change
is incomplete when durable content is left only in the wrong document class.

| Document class                                                                                                                               | Authority                                                                                  | Must contain                                                                                                                                               | Must not contain                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Architecture documents: `.agents/specs/ARCHITECTURE-MAP.md`, `.agents/specs/architecture-map/*.md`, package-local `docs/ARCHITECTURE-MAP.md` | Stable structural boundaries, owner placement, dependency direction, layer rules, topology | Package ownership, allowed/forbidden dependency edges, product-shell boundaries, cross-package topology, update requirements                               | Package-local public API detail, implementation plans, option analysis, transient backlog, marketing prose     |
| Design documents: `.design/**/*.md`, `docs/plans/*-design.md`, `docs/superpowers/**/*design*.md`                                             | Planning and decision rationale before the accepted contract is updated                    | Problem statement, alternatives, recommendation, tradeoffs, research notes, implementation phases, affected files, test strategy                           | Final package contract truth, stable dependency rules, API source of truth after implementation                |
| Package/app SPEC files: `packages/*/docs/SPEC.md`, `apps/*/docs/SPEC.md` where present                                                       | Owner contract for one package or app                                                      | Scope, owned responsibilities, non-goals, public API, class/interface contracts, lifecycle/events, persistence/protocol details, verification requirements | Cross-repository topology owned by the architecture map, implementation diary, details owned by other packages |
| Cross-cutting specs under `.agents/specs/*.md`                                                                                               | Shared contract truth when no single package owns the whole contract                       | Protocols, shared lifecycle models, command/background/verification contracts, reusable policy spanning packages                                           | Package-local API inventories that belong in package SPEC files                                                |
| Public docs and READMEs                                                                                                                      | User-facing explanation and usage guidance                                                 | Supported behavior, setup instructions, examples, migration notes, package overview                                                                        | Hidden contracts that are not represented in SPEC/API/architecture docs                                        |

Document authority is determined by path and role, not by a broad word in the filename. For
example, `content/guide/architecture.md` is public user documentation, while
`.agents/specs/architecture-map/*.md` is architecture authority.

Authority order by question:

- Package-local behavior, public API, lifecycle, events, persistence, and class/interface contracts
  are owned by the package/app SPEC.
- Cross-package ownership, dependency direction, product-shell boundaries, and deployment topology
  are owned by architecture documents.
- HTTP/API wire contracts are owned by the relevant API specification.
- Design documents, task files, backlog files, PR notes, and chat history do not override accepted
  SPEC, API, or architecture documents.

Content promotion rules:

- When a design decision becomes accepted, promote the durable contract into the owner SPEC, API
  spec, or architecture document in the same PR.
- Keep rationale, rejected alternatives, research notes, and phased implementation plans in design,
  task, or backlog documents.
- Do not duplicate package-local API details in architecture maps; link the owning SPEC instead.
- Do not keep cross-package ownership rules only in a package SPEC; update the relevant architecture
  map subdocument.
- Do not use README, website content, task files, or backlog files as the only source of contract
  truth.

### Structural Architecture Documentation

- Any change that creates, removes, renames, or reassigns responsibilities across workspace packages MUST update the architecture documents that describe the structure in the same PR.
- Required structural docs include `.agents/project-structure.md` for package inventory/dependency direction, `.agents/specs/ARCHITECTURE-MAP.md` as the architecture-map router, and the relevant `.agents/specs/architecture-map/*.md` subdocument for cross-cutting architecture that spans packages.
- Package `docs/SPEC.md` files remain required for owner-level contracts; architecture docs do not replace package specs.
- If a package has a package-local architecture map such as `docs/ARCHITECTURE-MAP.md`, changes to package composition, import edges, execution modes, or class/interface ownership MUST update that map in the same PR.
- Do not append subsystem details to the architecture-map router when a focused subdocument owns that area.
- A structural architecture change without updated structure/spec architecture documents is incomplete.

### GATE-CONFORMANCE (architecture conformance gate)

- **Purpose:** verify that the canonical architecture documents still match code reality (the
  doc-vs-code drift that the per-spec `Architecture Review` section self-asserts but does not validate).
- **Mechanical core (deterministic, non-prose):** `pnpm harness:conformance`
  (`scripts/harness/check-architecture-conformance.mjs`) composes `check-dependency-direction.mjs` with
  a workspace-package-name guard and emits a machine-readable JSON summary. Exit 0 = conformant, 1 = violations.
- **Analytic layer:** the [`architecture-conformance-audit`](../skills/architecture-conformance-audit/SKILL.md)
  skill set (dependency-graph-extraction → doc-claim-verification → conformance-finding-report →
  improvement-proposal-authoring) produces the `.design/architecture-audit/<date>/` report + proposal.
- **Trigger:** runs as part of the blocking `harness:scan` aggregate (the `conformance` scan in
  `run-all-scans.mjs`, promoted in INFRA-007 once `pnpm harness:conformance` reached 0 violations), so it
  gates every PR and release. Also runnable on demand via `pnpm harness:conformance`.
- **PASS/FAIL:** PASS when `harness:conformance` exits 0 and no unresolved P0 finding remains; FAIL
  otherwise. Run via [`backlog-gate-guard`](../skills/backlog-gate-guard/SKILL.md).

### Cross-Package SPEC Reference Policy

- SPEC.md MUST NOT hardcode counts, lists, or implementation details owned by another package (e.g., "6 built-in tools" when the tools are owned by a different package).
- When referencing another package's details, either reference the owning package's SPEC or describe only what is observable from the current package's own code.
- If cross-package details must be stated, annotate with the owning package name so staleness can be tracked (e.g., "8 built-in tools (per agent-tools)").
