# Backlog Cards Phase (Step 5)

**Precondition:** PRD specs confirmed by user.

Mark task 4 as `in_progress`.

## MANDATORY Card Rules (zero tolerance — read first)

These two rules apply to EVERY child card (epics use `owner_agent: ""`). The
`prd-card-writer` agent enforces them; the skill MUST verify post-generation
and HALT if violated.

### Rule A — `owner_agent` is mandatory and enum-validated

Every child card MUST declare `owner_agent` with a value from the **`owner_agent` enum**
defined in `framework/.claude/agents/REGISTRY.md` (the SSOT for all valid values). Do
not re-list the enum here — consult REGISTRY.md directly to avoid drift.

There is no implicit default and `claude` is NOT a valid value. Cards with
missing, empty, placeholder, or non-enum values fail Step 6 (validation-phase)
and BLOCK the commit. The `/new` orchestrator dispatches implementation
agent by this field (see `framework/.claude/skills/new/SKILL.md` § Agent
Routing), so a wrong value silently routes the card to the wrong specialist.

### Rule B — UI cards have UI-only scope (no mixed scope)

A card with `owner_agent: ui-expert` MUST be scoped EXCLUSIVELY to graphical
concerns: components, layout, styling, token usage, motion, accessibility.
It MUST NOT bundle:

- business logic / domain rules
- API integration or data fetching
- state management beyond local UI state
- form validation logic (rendering validation states is UI; the rules are not)
- backend changes (routes, handlers, DB schema)

If a feature step involves BOTH UI and logic, the writer MUST split it into:

- one `owner_agent: ui-expert` card — visual implementation, consumes mocked
  or contract-stable data
- one `owner_agent: coder` card — logic, API call, state, persistence

The two cards are wired via `depends_on:` / `blocks:`. A common ordering is
`coder → ui-expert` (contract ready before UI), but the reverse is acceptable
when the UI card consumes a hand-written mock.

#### Split example — Login feature

**Bad** (single mixed card):

```yaml
id: FEAT-XXXX-01
owner_agent: coder
scope:
  summary: |
    Implement the login page: form layout, validation states, call to
    POST /api/auth/login, token storage, redirect to dashboard.
```

**Good** (split into UI + logic):

```yaml
# UI card — visual only, consumes a mocked auth contract
id: FEAT-XXXX-02
owner_agent: ui-expert
depends_on: [FEAT-XXXX-01]
scope:
  summary: |
    Login form layout (email/password fields, primary CTA, link to recovery),
    visual states (idle / loading / error / success), a11y (focus order,
    aria-live for inline errors), responsive breakpoints. Consumes the
    `useAuth()` mock provided by FEAT-XXXX-01.
```

```yaml
# Logic card — API call + state + redirect
id: FEAT-XXXX-01
owner_agent: coder
blocks: [FEAT-XXXX-02]
scope:
  summary: |
    POST /api/auth/login handler, token storage in httpOnly cookie, redirect
    on success, `useAuth()` hook exposing { status, error, signIn }.
```

## MANDATORY Card Structure (zero tolerance — read first)

Every PRD generates **1 epic card + N children**, regardless of N. The
`prd-card-writer` agent enforces this; the skill MUST verify it post-generation
and HALT if violated.

- **Epic**: `${paths.backlog_dir}/FEAT-XXXX-00-<slug>-epic.yml` — tracker only (no code work);
  contains AC-EPIC, execution_strategy with parallel groups, documentation_impact
  map.
- **Children**: `${paths.backlog_dir}/FEAT-XXXX-NN-<sub-slug>.yml` for N=1..M — atomic
  implementation cards. `group.parent: FEAT-XXXX-00`, `group.sequence: N`.

**Forbidden** (post-write verification: skill MUST `ls ${paths.backlog_dir}/FEAT-XXXX-*.yml`
and confirm a `-00-...-epic.yml` exists, plus at least one `-NN-` child):

- Flat cards `FEAT-XXXX-<slug>.yml` (no `-NN-` segment).
- `group.parent` as placeholder string (e.g. `TIPS-EPIC`) instead of the
  epic's actual `FEAT-XXXX-00` id.
- Epic missing when N=1.

If the agent returns flat cards: re-invoke with explicit correction prompt. Do
NOT commit flat cards.

Reference examples: `FEAT-0875-00..08` (Survey Analytics), `FEAT-0876-00..11`
(Menu TIPS).

Templates: `.claude/skills/prd/assets/epic-template.yml` for the epic,
`.claude/skills/prd/assets/card-template.yml` for children.

## Specialist Audits (conditional, before cards)

Invoke mandatory specialist agents when the feature qualifies:

- **`hyper-gamification-designer`** — MUST invoke if the feature touches B2C rewards,
  loyalty, engagement, progression, points, referrals, or retention loops.

  Invoke with:

  ```
  Agent(
    subagent_type: "hyper-gamification-designer",
    prompt: """
      Audit the approved PRD for gamification / retention quality.

      WORKING_DIRECTORY: <$WORKTREE_PATH absolute path>
      PRD path: <$WORKTREE_PATH>/<prd_path>
      Feature slug: <slug>

      Review the PRD's requirements, acceptance criteria, and risks for
      gamification mechanics, reward loop design, progression clarity, and
      retention risks. Return a structured findings list: each finding has
      a section reference, severity (HIGH/MEDIUM/LOW), and a concrete
      recommendation. Do NOT rewrite the PRD — return findings only.
    """,
    mode: "bypassPermissions"
  )
  ```

  After the agent returns: **present its findings to the user** via
  `AskUserQuestion` (list each HIGH finding explicitly) and request
  confirmation before applying any changes to the PRD. Only incorporate
  findings the user approves. Once the PRD is updated, re-confirm the
  final PRD state with the user before proceeding to card generation —
  the Step 4b gate applies to the post-audit PRD, not only the pre-audit version.

- **`api-perf-cost-auditor`** — already executed at Step 4.5 (API Performance Gate)
  if the PRD contained API/data surfaces. Do NOT re-invoke here unless the card
  introduces NEW API patterns not covered in the PRD (e.g., card splits a single
  endpoint into multiple, or adds a caching layer not in the original design).
  If re-invoked, scope the audit to card-specific additions only.

If neither applies, note "Specialist audits: N/A" in the state file.

## Complexity Gate (pre-write)

Before delegating to `prd-card-writer`, check each logical card boundary:

1. Count expected `files_likely_touched` — flag if **> 12**. `[CALIBRATION-NEEDED: pre-write advisory threshold; prd-card-writer Rule C (SSOT) uses > 15 as the DEEP-profile trigger and 8 as the per-card atomicity target — these three thresholds serve distinct purposes and are not interchangeable; empirical grounding is missing for all three]`
2. Count expected `acceptance_criteria` — flag if **> 5**. `[DESIGN-CHOICE: matches Rule C's DEEP trigger for AC count — the advisory here prompts a split before delegation, while Rule C deterministically assigns deep regardless of the user's override choice]`

**If flagged:**

- Warn: `"COMPLEXITY: [scope] has [N] files / [M] ACs — consider splitting by layer (API/UI) or by flow."`
- **Advisory, not blocking.** User can confirm to proceed. Log override in state file.

**If clean:** proceed silently.

## Card Writing — Delegated to `prd-card-writer` Agent

This phase is delegated to the **`prd-card-writer`** agent (`subagent_type: "prd-card-writer"`)
to free main context and ensure high-precision card generation under `effort: high`.

**DO NOT use `EnterPlanMode`/`ExitPlanMode`.** This skill manages its own multi-turn
approval flow. Plan mode risks context loss if the user accidentally accepts
"clear context and accept plan", destroying the entire skill session.

### Invocation

Launch the agent with all necessary context in the prompt:

```
Agent(
  subagent_type: "prd-card-writer",
  prompt: """
    Generate backlog cards from the approved PRD.

    WORKING_DIRECTORY: <$WORKTREE_PATH absolute path>
    (Per HARD RULE 17 of /prd SKILL.md — all file writes must go inside this
    directory, NOT into the consumer's main repo. See your "Working Directory"
    section for the rule and sanity check.)

    PRD path: <$WORKTREE_PATH>/<prd_path>
    State file path: <$WORKTREE_PATH>/<state_file_path>
    Card template: <$WORKTREE_PATH>/.claude/skills/prd/assets/card-template.yml
      (the template is symlinked from .framework/ into the worktree just like
      in the main repo — the symlink works inside the worktree)
    Feature slug: <slug>

    The PRD has been approved by the user. Read it in full, read the state file
    for discovery context, and produce atomic cards following your instructions.

    The card template includes 7 agent-optimization fields (existing_patterns,
    validation_commands, anti_patterns, scope_boundaries, input_output_examples,
    error_handling, reuse_analysis). Populate them per your field-mapping instructions.
    Use Grep/Glob to verify file paths and line numbers for existing_patterns and reuse_analysis.

    Write all card YAML files to <$WORKTREE_PATH>/backlog/ (absolute path).
    Update the state file ## Backlog Cards section with card list and traceability matrices.
    Return the Parallel Execution Map summary.
  """,
  mode: "bypassPermissions"
)
```

**Substitution rule.** In the prompt above, `<$WORKTREE_PATH>` is a textual
placeholder — the `/prd` skill MUST replace it with the absolute path stored
in the state file's `## Worktree` section BEFORE invoking the agent. Do NOT
pass the literal string `$WORKTREE_PATH` — the subagent has no shell context
to expand it.

### What the agent handles

The `prd-card-writer` agent owns the entire card writing pipeline:
- Card atomicity and splitting
- All required fields per card (27+ fields from template, including 7 agent-optimization fields)
- business_rationale field (extracted from PRD Section 1b — 2-3 line summary per card)
- `existing_patterns` with codebase-verified file:line references (requires Grep during card generation)
- `validation_commands` derived from acceptance criteria and definition_of_done
- `anti_patterns` extracted from PRD constraints and cross-card scope boundaries
- `scope_boundaries` with explicit in/out of scope and sibling card references
- `input_output_examples` from PRD API contracts (Section 5)
- `error_handling` from PRD failure modes and edge cases (Sections 5, 11)
- `reuse_analysis` with codebase-verified component references (requires Grep/Glob during generation)
- FR/NFR traceability matrix
- ISA traceability matrix (if PRD has section 15)
- UI Element traceability matrix (if PRD has UI Element Inventory)
- Parallel group computation (dependency graph + file-conflict map)
- `execution_strategy` block on epic parent card
- State file update with card list and matrices
- `env_vars` field: for every card that introduces/modifies/removes env vars (detectable from PRD Section 6 or requirements that mention `process.env`, secrets, API keys, feature flags), populate the field with `action: new|modified|removed`, `scope`, `required`, `note`. If the card does not touch env vars, write `env_vars: []`.
- `review_profile` field: deterministic per-card review depth (`skip|light|balanced|deep`). The decision criteria (how each profile is chosen) live ONLY in `prd-card-writer.md § Rule C` — see that file for the criteria. The `/new` orchestrator reads this value from the card and runs an escalation-only detector; it does NOT re-derive from a duplicate criteria table. Epics always get `review_profile: skip`. Honor any explicit author override already present in the YAML.

### What stays in the main context

- Specialist audit invocations (above) — they may modify the PRD before cards are generated
- Presenting results to the user (the agent returns summary, main context displays it)
- Proceeding to Step 6 (validation phase)

## Present and Proceed

Present the plan to the user (traceability matrix + parallel execution map) for
visibility, then **proceed immediately** — no approval gate needed at this stage.
The PRD specs were already confirmed in Step 4b; card creation is a mechanical
derivation from approved specs, so a second approval would be redundant.

Mark task 4 as `completed`. Update state file `## Backlog Cards` with card list.

**MANDATORY: Immediately proceed to Step 6 in the SAME turn.** Read
[validation-phase.md](validation-phase.md) and execute the quality audit protocol
from [audit-phase.md](audit-phase.md) with the card IDs. Do NOT display the progress
bar and stop. Do NOT wait for user input. Do NOT ask the user if they want to skip
the audit. Just run it.
