---
name: prd
effort: high
description: "Structured PRD creation skill. Use when the user says /prd, 'crea un prd', 'nuova funzionalita', 'pianifica feature', or wants to plan a new feature end-to-end. Also handles /prd-add, 'aggiungi requisito', 'serve anche', 'manca un endpoint' for change requests on active PRD sessions — runs ICIAS impact analysis to determine which phases need SKIP/PATCH/REDO. Produces PRD + UI design + backlog cards, all validated and committed. Multi-turn conversation: asks questions, waits for answers, iterates through discovery, design, spec writing, card creation, and validation phases."
---

# /prd — Structured PRD Skill

Turn a feature idea into implementation-ready artifacts: PRD, UI design, and backlog
cards. Anti-drift by design — rigid step sequence, persistent state, visible progress.

## Project Context

**Reads from `baldart.config.yml`:** `paths.prd_dir`, `paths.backlog_dir`, `paths.references_dir`, `paths.design_system`, `paths.ui_guidelines`, `paths.metrics` (default `docs/metrics`), `git.trunk_branch`, `git.merge_strategy`, `identity.audience_segments`, `identity.language`.
**Gated by features:** `features.has_prd_workflow` (skill REFUSES to run when `false`), `features.has_backlog` (Step 5 BLOCKING when `true`), `features.has_design_system` (Step 3 BLOCKING reads), `features.has_adrs` (architectural decisions get logged as ADRs in `paths.adrs_dir`).
**Overlay:** loads `.baldart/overlays/prd.md` if present — project-specific terminology, card layout overrides, segment names, mandated review gates.
**On missing/empty keys:** ask the user; do not assume defaults. See `framework/agents/project-context.md` § 3.

## Effort

**Baseline:** `effort: high` (frontmatter). **Inline override:** pass
`effort=<low|medium|high|xhigh|max>` anywhere in the invocation to scale
reasoning depth for this run — detect it once at kickoff and strip the token
before consuming user input. Level→behavior mapping, parsing contract, and
precedence caveats: `framework/agents/effort-protocol.md`.


---

## EXECUTION MODEL

This skill is a **multi-turn conversation**. You do NOT produce all artifacts in one
message. You ask questions, wait for answers, and iterate.

**Flow overview:**

| Step | Phase | Reference |
|------|-------|-----------|
| 0 | Context Recovery | [discovery-phase.md](references/discovery-phase.md) |
| 1 | Kickoff | [discovery-phase.md](references/discovery-phase.md) |
| 1.2 | Obsidian provisional back-reference (only if a spec note was given) | [discovery-phase.md](references/discovery-phase.md) + [obsidian-backref.md](references/obsidian-backref.md) |
| 1.6 | Mockup Intake | [discovery-phase.md](references/discovery-phase.md) |
| 2 | Discovery Question Loop (+ Codex completeness cross-check at exit, v4.19.0) | [discovery-phase.md](references/discovery-phase.md) |
| 2→CR | Change Request (auto/manual) | the canonical **`prd-add` skill** ([../prd-add/SKILL.md](../prd-add/SKILL.md)) — worktree-aware (`references/prd-add-phase.md` is a redirect stub, not the implementation) |
| 2.5 | Research (opzionale) | [research-phase.md](references/research-phase.md) |
| 3 | UI Design (3a-3d) | [ui-design-phase.md](references/ui-design-phase.md) |
| 4 | Write PRD | [prd-writing-phase.md](references/prd-writing-phase.md) |
| 4.5 | API Performance Gate | [api-perf-gate.md](references/api-perf-gate.md) |
| 4b | Confirm Specs (§ "Present and Confirm") | [prd-writing-phase.md](references/prd-writing-phase.md) |
| 5 | Backlog Cards | [backlog-phase.md](references/backlog-phase.md) |
| 6 | Quality Audit | [validation-phase.md](references/validation-phase.md) |
| 7 | Resolution, Commit & Merge | [validation-phase.md](references/validation-phase.md) |
| 7.6 | Obsidian back-reference — FINAL (upgrades the 1.2 provisional block; only if a spec note was given) | [validation-phase.md](references/validation-phase.md) + [obsidian-backref.md](references/obsidian-backref.md) |

**Before starting each phase, read the corresponding reference file.**

---

## HARD RULES

1. Follow steps in order. NEVER skip a step or jump ahead.
2. Every step MUST update the state file before proceeding.
3. Every gate MUST be satisfied before moving to the next step.
4. Use TaskCreate/TaskUpdate for ALL progress tracking.
5. When context is compressed or session resumes: run Step 0 first.
6. **ONE question per message during discovery. Never batch questions.**
7. No code generation. This skill produces planning artifacts only.
8. Use exact terminology from `agents/coding-standards.md` and the project's terminology section in `.baldart/overlays/prd.md` (audience segments come from `identity.audience_segments`; domain entities are listed in the overlay).
9. Update `${paths.references_dir}/project-status.md` Active Code Context at session start and at commit (AGENTS.md MUST). Skip when the file does not exist in the project.
   **Worktree-mode exception (HARD RULE 17):** when the PRD runs inside a docs worktree (default since v3.22.0), the session-start update is **SKIPPED** — writing `project-status.md` in the worktree wouldn't be visible to other terminals working on the main repo, and writing it on the main repo would pollute `git status` for parallel sessions (exactly what worktree isolation is meant to prevent). The at-commit update still applies and runs inside the worktree as the last write before rebase + merge — see [validation-phase.md](references/validation-phase.md) § Step 7.
10. **STOP means STOP.** When you see `STOP`, end your message. Do not make more tool
    calls. Do not continue to the next step. Wait for the user.
11. **Every message MUST end with the Progress Bar.** No exceptions.
12. **Scope Expansion Detection.** During discovery (Step 2), after every user answer,
    check if the response introduces NEW structural entities (endpoints, collections,
    pages, roles, flows) not in the original feature description. If detected, pause
    and offer to run `/prd-add` for impact analysis. See discovery-phase.md for protocol.
13. **`canonical_docs` completeness.** Every card generated from a PRD MUST have
    `canonical_docs.ssot_registry_entry` populated (exact row name from the project's SSOT registry — typically `${paths.references_dir}/ssot-registry.md` if it exists; skip when absent). Cards with `data_fields` MUST also have `canonical_docs.data_model_refs` populated with the matching `${paths.references_dir}/collections/*.md` paths (or the project's data-model docs as defined in the overlay). The `prd-card-writer` agent enforces this during Step 5. Missing `canonical_docs` = card is not DONE.
14. **Design System SSOT alignment (UI PRDs).** During UI Design phase (Step 3), when `features.has_design_system: true`, you MUST read `${paths.design_system}/INDEX.md` (component index + authority matrix + Quick rules MUST) before generating mockups or component specs. For each UI surface in the PRD, identify the relevant component docs under `${paths.design_system}/components/<Name>.md` and cite them in PRD Section "Canonical Sources". New UI pages/components described in the PRD MUST reuse existing components when available and MUST NOT propose hardcoded hex / shadow / border values when a token contract exists. Multi-tenant theming surfaces (when `features.multi_tenant_theming: true`) MUST reference the project's theming pattern doc; motion specs MUST reference the project's motion pattern doc. Both are listed in `.baldart/overlays/prd.md`.
15. **Backlog structure: epic + children (MANDATORY — zero tolerance).** Every PRD that
    produces backlog cards MUST organize them as **1 epic + N children**, regardless of N:
    - **Epic**: `${paths.backlog_dir}/FEAT-XXXX-00-<slug>-epic.yml`. Tracker only — no implementation
      work. Contains AC-EPIC list, Definition of Done, business_rationale, scope,
      scope_boundaries, `execution_strategy` (with `groups:` — each carrying `level:`
      and `cards:` — computed from the
      dependency graph), and `documentation_impact` map with `owner_card` per doc.
      `group.parent` = the PRD slug string (NOT a FEAT-ID). `group.sequence: 0`.
      `parallel_group: 0`. `depends_on: []`, `blocks: []`.
    - **Children**: `${paths.backlog_dir}/FEAT-XXXX-NN-<sub-slug>.yml` for N=1..M. Each has
      `group.parent: FEAT-XXXX-00` (the epic's actual ID), `group.sequence: N`,
      and `depends_on` / `blocks` referencing sibling child IDs.

    **FORBIDDEN PATTERNS** — the `prd-card-writer` agent MUST refuse and the skill
    MUST halt:
    - Flat cards `FEAT-XXXX-<slug>.yml` (no `-NN-` segment, no epic parent).
    - `group.parent` set to a placeholder string like `TIPS-EPIC` instead of the
      actual epic FEAT-XXXX-00 id.
    - Skipping the epic when there is only one child card.
    - Reusing the same `FEAT-XXXX` integer for unrelated work (each epic reserves
      the full integer space).

    **Canonical examples**: `FEAT-0875-00..08` (Survey Analytics Redesign),
    `FEAT-0876-00..11` (Menu TIPS). See `assets/epic-template.yml` for the epic
    structure and `assets/card-template.yml` for child structure.
16. **Mockup Intake (MANDATORY).** Subito dopo Kickoff (Step 1) e prima di entrare in
    Discovery (Step 2), esegui Step 1.6 — chiedi all'utente se ha mockup a disposizione.
    Se **sì**: chiedi formato (immagini in chat / path locali — singoli file, **archivi
    `.zip`**, **o una cartella già estratta di un bundle Claude Design** — / misti),
    **STOP**, attendi. Sull'arrivo:
    - **chat-images** / file singoli in **local-paths**: copia in `${paths.prd_dir}/<slug>/mockups/`,
      passa subito all'analisi.
    - **`.zip` OPPURE cartella bundle Claude Design** (firma: `.design-canvas.state.json`
      e/o più `*.html` con slot `id="s<N>"`; es. export "Download as .zip" o la cartella
      scaricata dell'intero workspace): esegui Step 1.6.4b. Prima fa un **passaggio
      strutturale** (canvas-anchor sul titolo feature → estrazione slot `id="s<N>"` =
      screen-ID → arricchimento dal manifest `.design-canvas.state.json` → render degli
      artboard canvas-only via [canvas-intake-recipe.md](references/canvas-intake-recipe.md));
      lo **scoring per keyword** resta solo come fallback (bundle generico o canvas
      ambiguo). In entrambi i casi presenta la selezione, **STOP**, attendi conferma,
      poi materializza solo il sottoinsieme confermato in `${paths.prd_dir}/<slug>/mockups/`.
      Il PRD non aborta mai sull'intake: ogni fallimento ricade sul fallback + STOP gate.

    Quindi analizza in dettaglio (vedi
    [discovery-phase.md](references/discovery-phase.md) § "Mockup analysis schema"), popola
    `## UI Design` nello state, poi entra in Discovery. Se **no**: marca
    `mockups.status: none` e procedi col flow standard. Il decision tree di Step 3 (UI Design)
    consuma `mockups.status` + `screens_in_scope[]` per scegliere ramo Full / Hybrid / Skip
    senza ulteriore intervento. Le ambiguità rilevate dall'analisi mockup
    (`mockup_analysis.screens[].gaps[]`) DEVONO diventare domande mirate in Discovery o
    essere esplicitamente waivate.

    **Nota — handoff esterno post-intake.** Se l'utente risponde NO al mockup intake, lo
    Step 3.0 in UI Design gli chiederà se vuole generare i mockup internamente (workflow
    `ui-design`) o fare handoff a **Claude Design**. Nel ramo handoff la skill genera un
    prompt context-rich pronto da incollare, fa STOP, e al rientro con i path locali
    riusa esattamente questa stessa procedura di Step 1.6 → Step 3 entra in Hybrid mode.
    Vedi [ui-design-phase.md](references/ui-design-phase.md) § "Step 3.0 — Mockup Source Decision".

17. **Worktree isolation (MANDATORY since v3.22.0).** Every PRD session runs inside
    a dedicated **docs worktree** created by the `worktree-manager` skill in
    programmatic docs mode — never on the consumer's main checkout. The worktree
    isolates PRD artefacts from other parallel Claude sessions: `git status` on
    the main repo stays clean, accidental stashes / commits / push from sibling
    `/new` runs cannot pick up PRD files, and the merge back into the trunk branch
    (`git.trunk_branch`) becomes a single atomic operation.

    **Why this exists.** Without the worktree, every PRD pollutes the main
    checkout with `${paths.prd_dir}/<slug>/PRD.md`, `${paths.prd_dir}/sessions/...`,
    `${paths.backlog_dir}/FEAT-XXXX-*.yml`, plus design assets and updated
    SSOT/project-status files. With 5-10 parallel sessions, this is unworkable.

    **Lifecycle (deterministic, no opt-in):**
    - **Step 1 (Kickoff)** — after computing `<slug>`, before writing ANY file,
      capture the main-repo root: run `git rev-parse --show-toplevel` **from the
      main checkout (before any `cd` into the worktree)** and save the absolute
      result as `$MAIN` in the state file under `## Worktree` (`main_path`). Then
      call `worktree-manager` programmatic `nw-docs` with `{ slug: <slug> }`.
      Save the returned `path` as `$WORKTREE_PATH` in the same `## Worktree`
      section (path, branch, kind: "docs", main_path). Then `cd "$WORKTREE_PATH"`
      and run `pwd` to verify. From this moment, EVERY file write happens inside
      the worktree. Both `$MAIN` and `$WORKTREE_PATH` MUST be persisted now so they
      survive context compaction; the Step 7.5 finalization gate begins with a
      presence-and-non-empty guard on `$MAIN` and HALTS with a clear message if the
      field is absent (never operates on an undefined `$MAIN`). See
      [discovery-phase.md](references/discovery-phase.md) § Step 1.
    - **Step 0 (Context Recovery)** — when resuming a `/prd` or running
      `/prd-add`, scan `.worktrees/registry.json` for entries with
      `kind: "docs"` matching the slug; if found, `cd` into that worktree
      before scanning for state files. See [discovery-phase.md](references/discovery-phase.md) § Step 0.
    - **Step 7 (Commit & Merge)** — commit happens inside the worktree, then
      `worktree-manager` programmatic `mw-docs` is invoked immediately to
      rebase onto `origin/<git.trunk_branch>` and land the PRD via the configured
      `git.merge_strategy`. Seamless by default, no confirmation gate (the
      user opted into the full pipeline when they ran `/prd`). If the user
      explicitly says "non mergiare" / "lascia il worktree", honor the
      override and stop after the commit. See [validation-phase.md](references/validation-phase.md) § Step 7.

    **Path resolution rule (CRITICAL — read carefully).** Claude Code's
    `Write` / `Edit` / `Read` tools require ABSOLUTE paths and **do NOT
    expand shell variables**. All `${paths.X}` references in this skill and
    its phase references are relative to the worktree for the entire
    session — but you must construct the final absolute path **textually
    by concatenation**, never by passing the literal string `$WORKTREE_PATH`
    to a tool call.

    The variable name `$WORKTREE_PATH` used throughout this document is a
    **placeholder for the absolute path returned by `nw-docs` at Step 1**
    (e.g. `/Users/alice/my-project/.worktrees/prd-menu-info`). Substitute
    that absolute path before every Write/Edit. Worked example:

    ```
    # State: nw-docs returned path="/Users/alice/my-project/.worktrees/prd-menu-info"
    # Goal: write PRD.md for slug=menu-info

    # ❌ WRONG #1 — writes to main repo, defeats isolation:
    Write(file_path="/Users/alice/my-project/docs/prd/menu-info/PRD.md")

    # ❌ WRONG #2 — literal $WORKTREE_PATH string:
    Write(file_path="$WORKTREE_PATH/docs/prd/menu-info/PRD.md")
    # Claude Code rejects ("path must be absolute") or creates a literal
    # directory named "$WORKTREE_PATH" in the current cwd.

    # ❌ WRONG #3 — relative path (also rejected by Write/Edit):
    Write(file_path="docs/prd/menu-info/PRD.md")

    # ✅ RIGHT — substitute the absolute path you got from nw-docs:
    Write(file_path="/Users/alice/my-project/.worktrees/prd-menu-info/docs/prd/menu-info/PRD.md")
    ```

    Before every Write/Edit, mentally check: "does this path string start
    with the absolute `nw-docs` path I saved at Step 1?" If not, you've
    broken isolation. The exception is `/tmp/...` paths used for transient
    reports (e.g., audit phase Step 2 step f) — those are intentionally
    outside any worktree.

    **Forbidden operations during the session:**
    - `git checkout` / `git switch` / `git branch` on the main repo (worktree-manager Safety Rules).
    - `git stash` anywhere (shared `refs/stash` across worktrees — see Safety Rules in worktree-manager).
    - Writing to the main repo's `${paths.prd_dir}`, `${paths.backlog_dir}`,
      or `${paths.references_dir}` directly. Only the merge in Step 7 touches the trunk branch (`git.trunk_branch`).

    **Exception — when the worktree cannot be created.** If `git worktree add`
    fails (e.g., `.worktrees/` not in `.gitignore`, disk full, repo not a git
    repository, or the consumer has explicitly disabled docs worktrees via
    overlay), STOP and report the error to the user. Do NOT silently fall back
    to writing on the main repo — that defeats the entire purpose of this rule.
18. **Opt-in session telemetry (`-stats` / `--stats`).** Unlike `/new`, this skill
    has no flag parser — it is conversational. So detect the opt-in ONCE at **Step 1
    (Kickoff)**: inspect `$ARGUMENTS` for the token `-stats` or `--stats`. If present,
    set `stats_enabled: true` in the state-file header (the field exists in
    `assets/state-template.md`); otherwise `false`. Persisting it in the state file is
    what makes it survive context compression and Step 0 resume. The Metrics Log step
    (inside Step 7) reads this field and, when `true`, post-processes the session
    transcripts for REAL per-role token + wall-clock cost. The token itself is NOT part
    of the feature description — strip it before recording the user's verbatim feature
    text in `## Feature Description`.
19. **Obsidian back-reference (MANDATORY when a spec note was given — TWO-PHASE since
    v4.27.0).** If the user kicked off the PRD from an Obsidian note (any of: `[[Note]]`
    wikilink, `obsidian://open?…` URI, or a pasted `.md` path), the same note becomes the
    durable index the user can later query ("come è stata sviluppata la feature X, dov'è
    finita"). It is written in two phases against ONE slug-keyed marker block
    (`<!-- BALDART:prd:<slug> START/END -->`), so the second write replaces the first in
    place (idempotent, no duplicates):
    - **Provisional** — at Step 1 detection (discovery-phase Step 1 point 2): a lightweight
      `status: drafting` block with slug + branch `prd/<slug>` + planned PRD path. So the
      note reflects "a PRD was started here" **immediately**, even if the run is later
      paused or abandoned before merge.
    - **Final** — at the END of the run, **after** the merge (validation-phase Step 7 item
      9) so paths/IDs/SHA are final (Step 7.6): the full payload — feature slug, PRD path,
      epic + card IDs, branch, merge commit/PR, Canonical Sources as `resources:`,
      `status: planned`.

    The note lives in the user's **vault, outside the worktree and outside git** — a plain
    filesystem write, never staged/committed. Both writes are **NON-BLOCKING**: no spec
    note, unresolved vault path, or an unwritable note all skip with a log line, never
    aborting the PRD. SSOT for the marker contract + write procedure + both modes:
    [obsidian-backref.md](references/obsidian-backref.md). See also discovery-phase.md Step
    1 point 2 and validation-phase.md Step 7.6.

---

## TEMPLATES

Use these templates when creating artifacts:

| Artifact | Template |
|----------|----------|
| Session state file | [assets/state-template.md](assets/state-template.md) |
| PRD document | [assets/prd-template.md](assets/prd-template.md) |
| Backlog epic (always 1) | [assets/epic-template.yml](assets/epic-template.yml) |
| Backlog child card (N≥1) | [assets/card-template.yml](assets/card-template.yml) |

**State file location:** `$WORKTREE_PATH/${paths.prd_dir}/sessions/YYYY-MM-DD-<slug>-state.md`
**PRD location:** `$WORKTREE_PATH/${paths.prd_dir}/<slug>/PRD.md`
**Design location:** `$WORKTREE_PATH/${paths.prd_dir}/<slug>/design.html`
**Cards location:**
- Epic: `$WORKTREE_PATH/${paths.backlog_dir}/FEAT-XXXX-00-<slug>-epic.yml` (mandatory when `features.has_backlog: true`)
- Children: `$WORKTREE_PATH/${paths.backlog_dir}/FEAT-XXXX-NN-<sub-slug>.yml` for N=1..M (at least 1)

**`$WORKTREE_PATH`** is set in Step 1 (Kickoff) by `worktree-manager nw-docs` —
see HARD RULE 17. Until Step 1 has run, no file writes are allowed; until then
the value lives only in the state file `## Worktree` section.

---

## PROGRESS BAR — MANDATORY ON EVERY MESSAGE

At the END of every message (after all text, before stopping), display:

```
---
📋 **Progresso PRD: <slug>**

| # | Fase | Stato |
|---|------|-------|
| 1.6 | Mockup intake | ⬜/🔄/✅/⏭️ |
| 2 | Discovery & comprensione | ⬜/🔄/✅ |
| 2.5 | Ricerca best practice | ⬜/🔄/✅/⏭️ |
| 3 | Design UI & approvazione | ⬜/🔄/✅/⏭️ |
| 4 | Conferma specifiche | ⬜/🔄/✅ |
| 5 | Creazione backlog cards | ⬜/🔄/✅ |
| 6-7 | Validazione, commit & merge | ⬜/🔄/✅ |

Comprensione: X% (N/M dimensioni coperte) — ISA: N punti identificati
Mockup: ⬜ non chiesto / 🔄 in attesa / ✅ N mockup / ⏭️ nessuno
Ricerca: ⬜ non valutata / 🔍 in corso (background) / ✅ completata / ⏭️ non necessaria
Step 3 mode: full / hybrid / mockup-only / skipped (impostato dopo Step 1.6 e refinementato a Step 3)
Prossimo passo: <what happens next>
```

Legend: ⬜ = da fare, 🔄 = in corso, ✅ = completato, ⏭️ = saltato (N/A)

**If your message doesn't end with this table, you violated the skill rules.**

---

## CONTEXT LOADING — Before Discovery (MANDATORY)

Before entering the discovery loop, load codebase context using the **context-primer**
(`/cont`) skill. This centralizes all codebase exploration in one place.

1. Extract 2-4 keywords from the user's feature description.
2. Invoke the `Skill` tool with `skill: "context-primer"` passing the keywords
   (e.g., `args: "prize scanning scratch card wheel"`).
3. The context-primer launches `codebase-architect` which routes through the
   canonical registry, docs, backlog, source code, and git history — returning a
   compact summary. When `features.has_lsp_layer: true`, the symbol-lookup tier is
   automatically used for identifier-shaped queries (transitive via
   `agents/code-search-protocol.md`); when `features.has_code_graph: true`, the
   architect uses the Graphify code graph for structural/relational queries
   (transitive via `agents/code-graph-protocol.md`).
4. Additionally, route through `${paths.references_dir}/ssot-registry.md` and `rg`
   over `${paths.references_dir}/`, `${paths.backlog_dir}/`, and `.claude/agents/`
   for the feature domain to surface related PRDs, ADRs, and specs not covered by
   context-primer. Verify implementation and stateful claims against repo docs/code.
5. Check `${paths.references_dir}/traceability-matrix.md` for source-to-doc mappings (if the project maintains one — skip when absent).

The loaded context lives in conversation history and informs ALL subsequent
discovery dimensions — avoiding redundant per-dimension agent launches.

## QUICK REFERENCE — COMPREHENSION DIMENSIONS

**`COMPREHENSION_DIMENSION_COUNT = 11`** (dimensions 0–10) — named constant, SSOT
defined here. Dimension 10 (Test strategy) is the single test dimension, so
**non-test = 10** (dimensions 0–9). The research-launch `~75%` trigger references
this constant by name (`8/10 non-test dimensions covered`) so it fires at a stable
point — see [research-phase.md](references/research-phase.md) § Trigger Evaluation.
If you add or remove a dimension below, update the constant in BOTH places.

The 11 dimensions (= `COMPREHENSION_DIMENSION_COUNT`) to cover during discovery:

0. **Business rationale** — why this feature, why now? (business motivation, market signal, expected impact, strategic alignment). Can be resolved from user's initial description or by explicit question (ALWAYS first in discovery loop).
1. **Target users** — who uses this feature?
2. **User journey** — how does the user flow work?
3. **Data model impact** — new collections, fields, interfaces?
4. **API impact** — new/modified endpoints?
5. **UI impact** — new pages, components, layouts?
6. **Permissions/roles** — access control changes?
7. **Edge cases** — what can go wrong?
8. **Rollout/migration** — feature flags, data migration, backwards compat?
9. **Integration surface** — where in the existing system must reference/link to this feature?
10. **Test strategy** — E2E needed? scenarios? credentials?

Dimension 0 is resolved first: from user's initial description (auto) or explicit question.
Dimensions 1-8 can be resolved by: context-primer context (auto), targeted codebase-architect (if needed), user answer, or N/A.
Dimension 9 uses automated codebase scan + user validation (see discovery-phase.md).
Dimension 10 uses a built-in evaluation tree (see discovery-phase.md).

**Mockup-driven pre-population (when Step 1.6 produced `mockups.status: provided`):**
- Dimension 5 (UI impact) is largely pre-resolved from `mockup_analysis.screens[]`
  — log as covered with source `mockup-analysis`. Only ask UI questions for
  ambiguities in `mockup_analysis.screens[].gaps[]` or for screens NOT in the mockups.
- Dimension 2 (User journey) is partially pre-resolved from `mockup_analysis.user_flow`
  — ask only for the connective steps that aren't visible from the mockup sequence
  (entry point, exit, error branches).
- All other dimensions follow the normal flow — mockups do not pre-resolve data
  model, API contract, permissions, edge cases, rollout, ISA, or test strategy.

---

## COMPLETED PROGRESS BAR (for final message)

```
---
📋 **Progresso PRD: <slug>**

| # | Fase | Stato |
|---|------|-------|
| 1.6 | Mockup intake | ✅/⏭️ |
| 2 | Discovery & comprensione | ✅ |
| 2.5 | Ricerca best practice | ✅/⏭️ |
| 3 | Design UI & approvazione | ✅/⏭️ |
| 4 | Conferma specifiche | ✅ |
| 5 | Creazione backlog cards | ✅ |
| 6-7 | Validazione, commit & merge | ✅ |

Comprensione: 100%
Mockup: ✅ N mockup analizzati / ⏭️ nessuno fornito
Ricerca: ✅ completata / ⏭️ non necessaria
Step 3 mode: full / hybrid / mockup-only / skipped
**Pronto per l'implementazione.**
```

---

## Metrics Log (MONITORING SIGNAL — non-blocking; runs inside Step 7, BEFORE the commit)

After cards are created and audited (Steps 5-6) and BEFORE the explicit stage list in
validation-phase.md Step 7 point 6 (point 5 is the invocation of this very Metrics Log
step), log this PRD run to the skill-runs file.

**Location (HARD RULE 17 applies):**
`$WORKTREE_PATH/${paths.metrics}/skill-runs.jsonl` (`paths.metrics` default: `docs/metrics`)

The file is committed together with the rest of the PRD artefacts in Step 7,
so it flows into the trunk branch (`git.trunk_branch`) via `mw-docs` atomically with the PRD.

**Conflict resilience.** JSONL is line-oriented and additive: when two parallel
PRDs both append a line and one rebases onto the other, the doc-friendly conflict
protocol in `worktree-manager` step 4b auto-resolves the `.jsonl` conflict by
keeping both lines (this is the one canonical case where "keep both sides" is
exactly the correct semantics). No special handling needed.

**Steps:**

> **Telemetry instrument-at-source (W4).** Every field below has a NAMED producer that
> computes it at this phase — never reconstruct a field by post-hoc LLM parsing of prose,
> and never add a field with no producer. The record is **assembled fully in memory
> (including the optional `cost` object) and appended exactly ONCE** — there is no
> append-then-rewrite of an already-written line.

1. **Assemble the record in memory** (do NOT write to disk yet). The orchestrator at this
   Step-7 phase is the producer for each field — count them from the created backlog YAML
   files:
   - `cards_created`: total cards created in this PRD run
   - `ac_coverage_ratio`: total acceptance_criteria count / total user_stories count across all cards
   - `isa_count`: number of ISA items identified (from the progress bar "ISA: N punti")
   - `has_test_plan_pct`: % of cards that have a `test_plan` field (even if `e2e_required: false`)
   - `has_db_indexes_pct`: % of cards that have a `db_indexes` field (covers any persistence layer; legacy `firestore_indexes` cards count too)
   - `discovery_iterations`: approximate number of Q&A rounds with the user (count AskUserQuestion calls in this session, default 1 if unknown)

   Base shape (the `cost` key is filled by step 2, then the whole object is appended in step 3):

   ```json
   {"ts":"<ISO-8601-UTC>","skill":"prd","run_id":"prd-<slug>","prd_slug":"<slug>","cards_created":0,"ac_coverage_ratio":0.0,"isa_count":0,"has_test_plan_pct":0.0,"has_db_indexes_pct":0.0,"discovery_iterations":1,"prd_path":"${paths.prd_dir}/<slug>/PRD.md"}
   ```

2. **Session token telemetry — producer for the `cost` field (ONLY when `stats_enabled: true` in the state file)** — measure REAL per-role token + wall-clock cost by post-processing the session transcripts (zero model-token cost — runs in Bash). Invoke:

   ```bash
   node .framework/framework/scripts/analyze-session-tokens.js \
     --skill prd --run-id "prd-<slug>" --out-dir "$WORKTREE_PATH/${paths.metrics}"
   ```

   The script reads `$CLAUDE_CODE_SESSION_ID` and derives the transcript paths itself (do NOT pass `--session` / `--project-dir` — test-only overrides). It writes `$WORKTREE_PATH/${paths.metrics}/sessions/prd-<slug>.md` and prints a summary plus a final `TELEMETRY_JSON=<json>` line. Parse that line and **fold its object into the in-memory record under a `"cost"` key** (do NOT touch the `.jsonl` file — it has not been written yet). On `stats: SKIPPED (...)` set `"cost":{"skipped":"<reason>"}`; when `stats_enabled: false`, omit the `cost` key entirely. Echo the summary to the user. The new `sessions/prd-<slug>.md` file is added to the explicit stage list in step 4.

3. **Append the assembled record ONCE** — write a single JSON line (the fully-built object
   from steps 1–2) to `$WORKTREE_PATH/${paths.metrics}/skill-runs.jsonl`, creating the file +
   parent directory if absent. This is a single atomic append — never re-open the line to
   mutate it afterward. (If a future field needs late enrichment, emit a SEPARATE record
   keyed by the same `run_id` rather than rewriting this line.)

4. Add the file(s) (the `.jsonl` plus, when written, `sessions/prd-<slug>.md`) to the explicit stage list in validation-phase.md Step 7 point 6 (the stage list is at point 6; point 5 is the invocation of this very Metrics Log step).

**This step is NON-BLOCKING** — if it fails, do not abort. Log "Metrics Log: SKIPPED" in the progress bar. The PRD merge proceeds regardless. The `-stats` script is itself fail-safe (always exits 0).
