<!-- Modulo on-demand di /new — NON un file installato a sé. Caricato via Read dalla § "Routing" del SKILL.md core. -->

> **Modulo `/new`** — eseguilo, poi torna al core § "Routing" per la fase successiva. I `§ "..."` (Context economy, Context Tracking, Trivial-card fast-lane, Risk-signal detector, Fix Application Log) vivono nel **core SKILL.md**.

### Phase 1 — Claim & Context
1. **Update tracker**: set current card, phase = "1-claim".
2. **`depends_on` gate (BEFORE claiming)** — read the card's `depends_on` field. For each listed card ID:
   - Read that card's backlog YAML and check its `status` field.
   - If NOT `DONE` → HALT: log in `## Issues & Flags` and ask the user: "Card <CARD-ID> depends on <DEP-ID> which is `<status>`. Proceed anyway, or wait?" Do not start implementation until the user responds explicitly. **The card status is NOT written until this gate passes** — so a HALT leaves the card untouched (no stale `IN_PROGRESS` for the next run to mis-read).
   - If `DONE` (or the user chose "proceed anyway") → continue.
2b. **Claim** — only now set the card status to `IN_PROGRESS` and assign yourself. **→ Visibility**: TaskUpdate this card's spine task → `in_progress`, and emit a Progress Bar (card change) per § "Progress Visibility".
2c. **Trivial-card classification (BLOCKING gate for steps 3–4)** — evaluate `IS_TRIVIAL(card)` per § "Trivial-card fast-lane". Note: condition 3 (non-source diff) cannot be fully evaluated until the coder has produced the diff, so at this point compute the **provisional** trivial flag from conditions 1+2 only (`review_profile == skip` AND no Step-A trigger sourced from the card YAML text + `files_likely_touched` extensions — if EVERY path in `files_likely_touched` is non-source, condition 3 is provisionally satisfied). If provisionally trivial → **SKIP steps 3, 3a, and 4** (architecture grounding); log `trivial: architecture grounding skipped (review_profile=skip + non-source files_likely_touched + 0 triggers)` and jump to Phase 2. Re-confirm `IS_TRIVIAL` on the ACTUAL committed diff at the review gates (Phase 2.55/3.5/3.7); if the coder unexpectedly touched a source file, the guard flips the card back onto the normal review path there. If NOT provisionally trivial → run steps 3, 3a, 4 as normal.
3. **(skip when provisionally trivial — see 2c)** Invoke the **codebase-architect** agent (MUST per AGENTS.md) to understand the relevant codebase area, existing patterns, and architecture before any implementation. When `features.has_lsp_layer: true`, the architect uses LSP find-references for identifier-shaped lookups — this needs NO handoff from the orchestrator: the architect reads `features.has_lsp_layer` from `baldart.config.yml` directly (the flag is ambient) per `agents/code-search-protocol.md`. Likewise, when `features.has_code_graph: true`, the architect uses the Graphify code graph for structural/relational lookups (ambient flag) per `agents/code-graph-protocol.md`. The orchestrator does NOT propagate either flag. (Earlier doc versions numbered this step 4; the step that read project-status BEFORE the architect was removed because it persisted pre-analysis context — see step 3a.)
3a. Update `${paths.references_dir}/project-status.md` Active Code Context (skip when the file does not exist in the project) — do this AFTER the codebase-architect run (step 3) so the "Active Code Context" reflects the architect's findings (which files are actually in scope), not just the card YAML's `files_likely_touched`. Writing it before the architect run would persist pre-analysis claims that downstream agents (e.g. a parallel card) would then read as truth.
4. **Plan-auditor grounding check** — but first, a **provenance skip (since v4.7.0 — mirror of Step 3d)**: the `/prd` Step 6.6 holistic audit already ran a per-card grounding pass when the card was authored. Re-grounding here is only worth a plan-auditor spawn if something changed since. Skip the plan-auditor when **BOTH** hold:
   - **P1 — provenance present**: the card has `metadata.holistic_audit` with non-empty `audited_at`, `audited_commit`, `audited_set`.
   - **P2 — no drift on this card's claimed paths** since the audit baseline. With `$AC` = `metadata.holistic_audit.audited_commit`, `$MAIN`/`$TRUNK` from the tracker, and this card's `files_likely_touched`/claimed paths (`$CARD_PATHS`):
     ```bash
     # empty AC, AC not in history, or any git error → treat as drift (do NOT skip)
     DRIFT="$(git -C "$MAIN" log --oneline "$AC".."$TRUNK" -- $CARD_PATHS 2>/dev/null || echo "DRIFT")"
     ```
     P2 holds **iff** `$AC` is non-empty AND the command succeeds AND `$DRIFT` is empty.

   (No S2/S3 cross-card conditions — grounding is per-card, and the holistic audit grounded each card individually.) If **P1 ∧ P2 → SKIP** the plan-auditor: log `plan-auditor grounding: SKIPPED (holistic_audit provenance, no drift on claimed paths since <AC short sha>)`, carry the card requirements unchanged into Phase 2, and proceed to step 5. **Fail-safe**: missing/partial provenance, any drift, or any git error → fall through to RUN the plan-auditor as written below (never a silent skip). Independent of the trivial fast-lane (a trivial card already skipped steps 3–4 at step 2c). Otherwise — invoke the **plan-auditor** agent in **QUICK mode** (pass `mode: QUICK`; its contract runs only the grounding checks, and because the codebase-architect findings are passed in below it does NOT re-spawn codebase-architect for this narrow check):
   ```
   mode: QUICK
   Grounding check only (NOT a full audit — do not run the full AUDIT CHECKLIST A-H, and do not
   re-invoke codebase-architect; the findings are pasted below). Verify this backlog card's
   requirements are grounded in the actual codebase.

   Check:
   1. Do all paths in files_likely_touched actually exist?
   2. Are all type/field references in requirements correct per the codebase findings below?
   3. Are any [ASSUMED] items answerable by reading the listed files (i.e., should be verified facts)?
   4. Do any requirements conflict with known anti-patterns from your memory?

   Card YAML:
   [paste full card YAML]

   Codebase-architect findings:
   [paste key findings from step 3]

   Return: PASS | FIXES NEEDED (list exact corrections). No full audit report needed.
   ```
   - If **FIXES NEEDED**: apply corrections to the tracker notes for this card (do NOT modify the backlog YAML). Carry the corrected requirements into the Phase 2 briefing.
   - If **PASS**: proceed.
5. **Update tracker**: phase = "1-claim DONE", log codebase-architect key findings (1-2 lines) and plan-auditor result (PASS or corrections applied).
5b. **Persist the architecture baseline for reuse (since v3.35.0)** — write the **untruncated codebase-architect task result verbatim** (the full Task-tool output: file paths, type signatures, patterns, high-risk paths) to `/tmp/arch-baseline-<CARD-ID>.md`. This is NOT the 1-2-line tracker summary from step 5 — serialize the agent's complete output to disk BEFORE you summarize it for the tracker, so Phase 3.7's per-card `/codexreview` (lean mode, reuses this file instead of re-spawning `codebase-architect`) gets enough detail to ground a reviewer. If you summarize first and write the summary, the lean contract is defeated.

### Phase 2 — Implement (self-healing, up to 3 retries)
6. **Update tracker**: phase = "2-implement".
6b. **Agent dispatch (router)** — read `owner_agent` from the card YAML and resolve the spawn target per the table in § Agent Routing above:

   ```
   Let raw = card.owner_agent (string, may be missing).
   # Epic guard FIRST — an epic is a tracker, not implementable work.
   If card is an epic (id ends "-00" OR filename ends "-epic.yml" OR review_profile == "skip"
       with no requirements): SKIP — do NOT dispatch to any agent. Log
       "[ROUTER] card <ID> is an epic (tracker) — skipped, not implemented" and move to the next card.
   Switch on raw:
     - "coder"           → spawn = "coder",       briefing = "coder"
     - "ui-expert"       → spawn = "ui-expert",   briefing = "ui-expert"
     - "plan"            → spawn = "coder",       briefing = "coder"
                           + log: "[ROUTER] plan-only briefing not yet implemented — using coder"
     - "visual-designer" → spawn = "coder",       briefing = "coder"
                           + log: "[ROUTER] visual-designer briefing not yet implemented — using coder"
     - "motion-expert"   → spawn = "coder",       briefing = "coder"
                           + log: "[ROUTER] motion-expert briefing not yet implemented — using coder"
     - "" | missing | "claude"
                         → spawn = "coder",       briefing = "coder"
                           + log: "[ROUTER] card <ID> has no valid owner_agent (got '<raw>'); defaulting to coder"
     - anything else     → HALT. Log: "[ROUTER] card <ID> has unknown owner_agent '<raw>' — not in {coder, ui-expert, plan, visual-designer, motion-expert}. Ask the user how to proceed."
   ```

   Log the resolved `spawn` and `briefing` in the tracker (1 line: `"router: owner_agent=<raw> → spawn=<agent>, briefing=<variant>"`). This is the audit trail for which specialist actually handled the card.

7. Spawn the **resolved agent** (from step 6b) using this **standardized mission briefing** — fill in each section from the card YAML, tracker, and codebase-architect findings. When `briefing = "ui-expert"`, ALSO include the additional UI sections marked **[UI-ONLY]** below:

   ```
   ## MISSION BRIEFING — <CARD-ID>

   ### Card Specification (verbatim — do not paraphrase)
   Requirements:
   [copy full requirements list from card YAML, including any corrections from the plan-auditor grounding check (step 4)]

   Acceptance Criteria:
   [copy full acceptance_criteria list from card YAML]

   ### Unknowns & Conditional Requirements (MANDATORY — resolve before coding)
   [If card has `unknowns` field: copy verbatim. If empty or absent: "None."]

   Each unknown that says "verify X; if missing → do Y" is a BINARY-OUTCOME ITEM.
   You MUST actively verify and produce one of the two outcomes (implementation OR TODO comment).
   See `coder.md § Conditional Requirements — Binary-Outcome Items`.

   ### Migration context (include ONLY when this card appears in the tracker `## Migration` manifest's `affects_cards`)
   The required DB migration `<summary>` was ALREADY APPLIED to the active DB before this batch
   started (Phase 0 step 1b, modality `<id>`). The schema is LIVE — run REAL validation against it
   (`validation_commands`, queries, DB-generated types). Do NOT defer the schema-apply AC and do NOT
   build against a stubbed/absent schema: the table/column exists. If `## Migration` shows
   `status: degraded` instead (artifact missing / not applied), treat the schema as NOT yet live and
   follow the card's normal owner-gated deferral path.

   ### Business Context (WHY this feature exists)
   [paste business_rationale field from card YAML]
   [if field is empty/missing, read PRD Section 1b from card's links.prd path]

   ### Codebase Context
   [paste codebase-architect key findings: file paths, exact line numbers, type signatures, existing patterns to follow]
   [include any corrections or anti-patterns flagged by plan-auditor grounding check]

   ### Design Reference (UI cards only — include if card has links.design)
   Design file: [path from card's links.design field]
   Read the design.html file and use it as the visual reference for your implementation.
   The design was approved by the user — your implementation MUST match it.

   ### [UI-ONLY] Registry-first BLOCKING pre-work (include ONLY when briefing = "ui-expert")
   You are spawned as `ui-expert`. Before writing any UI code, you MUST complete
   the registry-first cascade defined in
   `framework/.claude/agents/ui-expert.md` § "Authoritative Style Reference —
   Registry-First Protocol" (the SSOT lives in
   `framework/agents/design-system-protocol.md`). Reproduce its 5 steps
   verbatim, do NOT paraphrase or skip:

   1. Read `${paths.design_system}/INDEX.md` (component index + Canonical
      Authority Matrix).
   2. Read `${paths.ui_guidelines}` (visual language, typography,
      accessibility, brand voice).
   3. Read `${paths.design_system}/tokens-reference.md` (token contract —
      SSOT for every color / spacing / shadow / radius / motion value).
   4. For EACH primitive in scope on this card, read
      `${paths.design_system}/components/<Name>.md`. "In scope" = any
      component named in the mockup, the requirements, or `files_likely_touched`.
   5. For EACH pattern in scope, read the relevant
      `${paths.design_system}/patterns/<topic>.md`.

   State, in your first response, which Authority Matrix rows govern this
   card, which component specs you read (step 4), and which patterns you
   read (step 5). Skipping this declaration = the orchestrator will reject
   the implementation and re-spawn.

   The `features.has_design_system: true` flag in `baldart.config.yml` is
   the precondition for the full cascade. When `features.has_design_system:
   false`, only step 2 applies — log the gap, recommend `/design-system-init`
   if drift is visible, and proceed with coder-level diligence (no cascade
   enforced).

   ### [UI-ONLY] Implementation-only constraint (include ONLY when briefing = "ui-expert")
   This `/new` invocation gives you the role of IMPLEMENTER, not designer:

   - DO NOT redesign the mockup. The mockup at `links.design` is the
     user-approved visual contract for this card.
   - DO NOT silently adapt a mockup detail that conflicts with the registry
     (e.g. a custom shadow not in `tokens-reference.md`, a font size off the
     type scale, a color outside the palette). If you find such a conflict:
     STOP, log it in the tracker as `[DS-DRIFT] mockup-vs-registry`, and ask
     the user which side to honor.
   - DO NOT extend scope into business logic, API calls, state management, or
     validation rules. Those belong to a sibling `coder` card (see
     `backlog-phase.md § Rule B`). If a requirement appears to need logic,
     STOP and ask — do not implement it.

   ### [UI-ONLY] Post-Intervention Coherence Check (include ONLY when briefing = "ui-expert")
   Before declaring the card done, you MUST reconcile the three design-system
   sources in the SAME commit as your UI change, per
   `framework/agents/design-system-protocol.md § Post-Intervention Coherence Check`:

   - `${paths.design_system}/INDEX.md` — add / update entries for any primitive
     introduced or modified. Drift code: `DS_INDEX_DRIFT`.
   - `${paths.design_system}/components/<Name>.md` — ship the per-component
     spec for any new primitive; update the spec when a primitive's API or
     visual changes. Drift code: `DS_COMPONENT_STALE`.
   - `${paths.design_system}/tokens-reference.md` — add / update token entries
     when introducing new semantic tokens. Drift code: `DS_TOKENS_DRIFT`.

   The four conditions defined in `design-system-protocol.md` are the SSOT —
   reproduce them in your completion report under a `design_system_coherence:`
   block listing which conditions applied and which artifacts you updated.
   Omitting the block = the orchestrator treats the card as not done.

   ### File Permissions (ENFORCED — no exceptions)
   MAY EDIT — your files for this card:
   [list from ownership map for this card]

   MUST READ ONLY — shared dependencies:
   [list from ownership map: files owned by other cards that this card reads]

   FORBIDDEN:
   - Do NOT edit any file outside the MAY EDIT list above
   - Do NOT refactor unrelated code
   - Do NOT add unrequested features or extra error handling beyond what's specified
   - Do NOT modify test files unless the card explicitly requires it

   ### Database Indexes (if card has `db_indexes` — or legacy `firestore_indexes` — field)
   This card requires the following indexes shipped in the SAME commit as the query
   code. Missing indexes degrade performance or break production (variant per
   `stack.database` — see `framework/.claude/agents/coder.md § Database Index Invariant`).

   [paste db_indexes entries from card YAML, formatted as:]
   | Entity | Dialect | Fields | Kind | Query Location | PRD Ref |
   |--------|---------|--------|------|----------------|---------|
   | [entity] | [stack.database] | [field1 ASC, field2 DESC] | [composite/covering/GIN/GSI] | [file path] | [IDX-N] |

   **Where to ship the index — pick the artifact matching `stack.database`:**

   - `firestore` → append to `firestore.indexes.json` under `indexes[]`:
     ```json
     {
       "collectionGroup": "<entity>",
       "queryScope": "COLLECTION",
       "fields": [
         { "fieldPath": "<field1>", "order": "ASCENDING" },
         { "fieldPath": "<field2>", "order": "DESCENDING" }
       ]
     }
     ```
     Stage `firestore.indexes.json` together with the query code.
   - `postgres` / `supabase` / `mysql` / `sqlite` → add a migration file under the
     project's migrations dir (`migrations/`, `db/migrate/`, `supabase/migrations/`,
     `prisma/migrations/` per project convention) with `CREATE INDEX ...` or the
     Prisma `@@index([...])` directive. For Supabase, RLS policies live in the same
     migration when relevant.
   - `mongodb` → add `db.<entity>.createIndex(...)` to the project's index-bootstrap
     script (path declared in `.baldart/overlays/new.md § Schema Bootstrap`), or run
     it as part of the migration command.
   - `dynamodb` → update the table definition in the project's IaC (CDK / Terraform /
     SAM / SST) with the matching GSI/LSI.
   - Stack `none` or unset → if you still see `db_indexes` on the card, ask the user
     to confirm the persistence target before staging anything.

   Stage the index artifact alongside the query code in the SAME commit. Verification
   (post-deploy index propagation) is handled in the Production Readiness Checklist
   section below, branched by `stack.deployment`.

   ### Expected Output Locations
   [pre-fill from codebase-architect: for each requirement, the file:line where the change should go]

   ### Project Anti-Patterns & NFRs (ENFORCED)
   Violating these is a BLOCKER in code review.

   Deprecated patterns — the orchestrator MUST fill this from the project's own AGENTS.md / MEMORY.md / coding-standards.md before sending the briefing. If the project documents none, write "None documented." Do NOT pass placeholder example text to the coder (it wastes tokens and confuses the agent):
   [resolved list of this project's deprecated/anti-patterns, or "None documented."]

   Performance MUST rules (adapt to your stack):
   - Bounded reads on every database query (`.limit()` / equivalent)
   - Cursor-based pagination, not offset
   - No per-row fetches in loops — batch instead
   - Database indexes declared in schema config (same commit as the query that needs them)

   Security MUST rules:
   - No stack traces in HTTP responses — generic messages + error codes only
   - No PII in console.log or error tracking
   - No hardcoded secrets — env vars only
   - ALL non-public routes MUST use the project's auth middleware

   Coding standards (agents/coding-standards.md):
   - Use the project's canonical terminology (document it in coding-standards.md)
   - Honor the design-system theming contract (e.g. text/background pairing rules)
   - Honor the project's image-format and asset-pipeline rules

   Design System SSOT (MANDATORY for UI cards):
   - Master reference: `${paths.design_system}/INDEX.md` (component index + Canonical Authority
     Matrix + Quick rules MUST). Read this BEFORE touching any UI file.
   - For each UI component you modify or create, read `${paths.design_system}/components/<Name>.md`.
   - Merchant-themed surfaces MUST follow the pairing rule in
     `the project's theming pattern doc (listed in `.baldart/overlays/ui-design.md`)`.
   - Motion MUST follow `the project's motion pattern doc (listed in `.baldart/overlays/ui-design.md`)` (reduced-motion variants
     required). The coder agent's own hardening (see `.claude/agents/coder.md`) already enforces
     this — this briefing is an explicit reminder for UI-touching cards.
   - No hardcoded hex/shadow/border values in component styling — canonical tokens only.

   ### Batch Lessons (from prior cards in this batch)
   [If tracker `## Lessons Learned` has entries, paste them here.
    If empty or first card: "First card — no lessons yet."]

   ### MANDATORY: Numbered Requirements Checklist (anti-skip measure)
   Before you start coding, print this checklist to confirm you see ALL requirements:
   ```
   REQUIREMENTS TO IMPLEMENT:
   [x] R1: [requirement text]
   [x] R2: [requirement text]
   ...
   ACCEPTANCE CRITERIA TO SATISFY:
   [x] AC1: [criterion text]
   [x] AC2: [criterion text]
   ...
   CONDITIONAL / BINARY-OUTCOME ITEMS (from unknowns + requirements with "verify if / if missing"):
   [ ] C1: [item text] → Branch to take: A (found+implement) | B (missing+TODO)
   [ ] C2: [item text] → Branch to take: A (found+implement) | B (missing+TODO)
   ...
   Total: N requirements + M acceptance criteria + K conditional items = X items
   ```
   You MUST implement ALL items. Skipping even one is a failure.
   For each conditional item: verify actively, then produce the correct branch artifact.

   ### MANDATORY: Completion Report
   When implementation is done, output this block in EXACTLY this format.
   This report is NOT optional — if you omit it, the orchestrator will flag
   your implementation as incomplete and spawn a fix agent.

   ```completion-report
   card: <CARD-ID>
   requirements:
     - id: 1
       text: "[verbatim requirement text]"
       status: done | not_implemented
       evidence: "src/path/to/file.ts:LINE_NUMBER"
       notes: "[if not_implemented: explain why]"
     - id: 2
       [repeat for each requirement]
   acceptance_criteria:
     - id: 1
       text: "[verbatim criterion text]"
       status: done | not_implemented
       evidence: "src/path/to/file.ts:LINE_NUMBER"
   items_total: [N]
   items_done: [M]
   items_skipped: [list of skipped item IDs, or "none"]
   conditional_items:
     - item: "[verbatim text of conditional requirement]"
       branch_taken: "A-found" | "B-missing"
       evidence: "src/path/to/file.ts:LINE_NUMBER"
       notes: "[if B-missing: exact TODO location and text left; otherwise omit]"
   ```

   Per-requirement / per-AC `status` is BINARY: `done` or `not_implemented` (the legacy
   `partial`/`blocked` values are removed — see `coder.md`). The orchestrator re-derives the
   finer Done/Partial/Missing classification itself in Phase 2.5 by reading the code; the coder
   report is a starting signal, not ground truth.
   If `items_skipped` is not "none", you MUST explain why each was skipped.
   The orchestrator treats any `not_implemented` or skipped item as a gap requiring a fix agent.
   `conditional_items` MUST list every binary-outcome item from the card. If the card has no
   conditional requirements, omit the field. `branch_taken: B-missing` MUST have a `notes`
   field with the exact file path and line where the TODO comment was written.
   ```

8. **Run the verification gates and CAPTURE their output to disk** (so step 9 can pass it to a fix agent) — **redirect, never `tee`/stream inline** (per § "Context economy" → Gate-output discipline). Each is its own gate:
   ```bash
   cd <worktree-path>
   npm run lint        > /tmp/lint-<CARD-ID>.txt  2>&1; echo "lint:$?"
   # tsc is its OWN blocking gate — run it ONLY when stack.language includes "typescript"
   # (do NOT assume `npm run build` covers tsc — Next.js dev builds and many setups skip it):
   npx tsc --noEmit    > /tmp/tsc-<CARD-ID>.txt   2>&1; echo "tsc:$?"   # guard: when stack.language includes "typescript"
   npm test            > /tmp/test-<CARD-ID>.txt  2>&1; echo "test:$?"  # if tests exist
   npm run build       > /tmp/build-<CARD-ID>.txt 2>&1; echo "build:$?"
   ```
   The `echo "<gate>:$?"` lines surface only the **exit code** inline — the full log stays on disk. When `stack.language` does NOT include `typescript`, skip the `tsc` line (no equivalent gate). Capturing to `/tmp/*-<CARD-ID>.txt` guarantees the failing output is available for step 9. On a non-zero exit, read a **bounded** extract only (`tail -n 30 /tmp/<gate>-<CARD-ID>.txt`), never the whole log — do NOT run the gates without redirect-to-file capture.
9. **If any check fails**: categorize the error (`lint | TypeScript | test | build`), log it in the tracker as `retry-cause: <category>`.
   **Code-recovery check (MUST do before rewriting)**: before spawning a fix agent or rewriting code, check whether lint-staged or a pre-commit hook removed code that is actually needed (e.g. a field "unused" at commit time but consumed by later code). Inspect the captured diff and `git diff`/`git log -p` for the worktree branch and restore the needed code by an explicit file write. **Do NOT `git stash pop` inside the worktree** — `refs/stash` is globally shared across worktrees (`$GIT_COMMON_DIR`), so a stash created or popped in a worktree can corrupt another worktree's state (see Phase 4 WORKTREE COMMIT RULE). If you need to set work aside in a worktree, make a clearly-labelled WIP commit and record its hash in the tracker for later squash, never a stash.
   When spawning a fix agent: scope it exclusively to this card's Edit-allowed files (from `## File Ownership Map`) — it MUST NOT touch files owned by other cards. Pass the fix agent: the **path** to the captured gate log (`/tmp/<gate>-<CARD-ID>.txt` — it Reads the log itself; do NOT inline-paste the full log into its prompt), the error category, and the explicit list of files it may edit. Do NOT ask the user — just fix and re-run. Fix the code, not the tests (unless the test itself is wrong). Repeat up to **3 times**. **Stuck-loop guard**: compare the failing error's fingerprint (file:line + message) between retries; if the SAME error reproduces on 2 consecutive retries, the fix is not converging (often a constraint outside the card's ownership map) — stop early, log `[STUCK-LOOP] <error>` in `## Issues & Flags`, and escalate to the user rather than burning the 3rd retry on an identical failure.
10. If still failing after 3 retries (or on a stuck loop), log the failure in `## Issues & Flags` and ask the user before continuing.
11. **Update tracker**: phase = "2-implement DONE", log files changed (short list), retry count, retry causes (e.g., `"2 retries: TypeScript x1, lint x1"`), and test results (new + existing test count, pass/fail).
11b. **File diff gate** — verify the coder only touched its allowed files. The coder commits its work (per `coder.md`), so a bare `git diff --name-only HEAD` is vacuous (clean tree). Detect what the card's commits actually changed against the trunk, with an uncommitted-fallback:
   ```bash
   cd <worktree-path>
   git diff --name-only "$TRUNK...HEAD" 2>/dev/null || git diff --name-only HEAD~1..HEAD
   ```
   (`$TRUNK` is the trunk branch resolved in Phase 0; if the worktree branched from a different base, the `HEAD~1..HEAD` fallback covers the last commit.)
   Compare against this card's allowed files in `## File Ownership Map`.
   - **All within allowed set** → proceed to Phase 2.5.
   - **Any file outside allowed set** → log the violation in `## Issues & Flags` (`"unauthorized file: <path>"`), then spawn a **targeted revert agent** (`subagent_type: general-purpose`, **`model: "haiku"`** — a file-scoped revert is mechanical git plumbing, not code authoring, so it does NOT need `coder`/opus; this is the sanctioned plumbing carve-out to REGISTRY.md's "never haiku" rule) with an **explicit ROLE BOUNDARY**: "Mechanical file-scoped revert only — restore ONLY these files to their pre-commit state, do NOT write, fix, or refactor any code. Do not touch any other file: [list unauthorized files]". Re-run build + lint to confirm clean state after revert. Update tracker with revert outcome, then proceed to Phase 2.5.
