Deep plan

From indigoai-us/hq-core · View interactive version

Deep plan is an AI agent skill from the GitHub repository indigoai-us/hq-core. Deep planning: research subagents plus a 15-question interview for large or strategic PRDs. For light planning use /prd.

How to use this skill

Skill file

Deep Plan — Research-First PRD Generation

Create execution-ready PRDs with full HQ context awareness, parallel research subagents, and a structured three-tier deep interview. Use this skill when the project is large, strategically important, touches unfamiliar code, or warrants the 10-15 minute upfront cost. For small ideas, tweaks, or fast captures, use the lightweight /prd skill instead.

Important: Do NOT implement. Just create the PRD.

Work Mesh Live — trusted bind (do this first)

After Step 0 resolves {co} and before any other tool call that touches project work, bind the session per

.claude/skills/_shared/work-mesh-live-bind.md (US-011):

hq core work-mesh-bind-trusted \
  --company "{co}" --project "{project}" --task "{task}"

Omit --task when unknown. This writes workspace/sessions/<sid>/meta.yaml

and reconciles with observation.trustedContext (no --trusted CLI flag).

Step 0: Company Anchor (from user input)

Resolve the company with the shared resolver — never by hand, and never from the first word alone:

hq core resolve-company --prompt "{the user's full input}"

It returns {"company":"<slug>","source":"prompt|session|device_default|none"}: an explicit whole-token slug in the input wins, then the bound session company, then the enabled device default. A session company always wins over the default; disabled and needsChoice defaults resolve as none. If source is none, use the structured picker before creating project files.

If company is non-empty: Read companies/manifest.yaml for company metadata, then:

  1. Set {co} = resolved slug for the entire flow. Strip it from the description only when it was the leading token
  2. Announce: "Anchored on {co}"
  3. Bind the session — run hq core work-mesh-bind-trusted --company "{co}" now, before any read under companies/{co}/. The scope guard blocks company paths until the session is bound to {co}.
  4. Load policies (frontmatter-only) — Collect eligible files for the resolved company, except example-policy.md, README.md, and _digest.md; preserve their order and split the stable file order into consecutive chunks of at most 40 files. For each chunk, run hq core policy frontmatter {file1} {file2} ... once with each path as a separate argument. Keep each call under 30 KB of output. The first output block belongs to the chunk’s first file argument; each later block belongs to the path named by its preceding # --- policy-file: <path> --- separator. Note enforcement: hard titles. For hard-enforcement policies only, additionally read the ## Rule section with a targeted range. Policy digests remain retired; SessionStart injects matching policies via inject-policy-on-trigger. Apply hard rules as constraints throughout the PRD
  5. Scope qmd searches — If company has qmd_collections in manifest, use -c {collection} for all qmd calls
  6. Pre-load repos — Extract {co}.repos[] from manifest. Present as repo options in the Architecture tier repo question
  7. Scope workers — Filter to company workers (companies/{co}/workers/) + public workers (core/workers/public/)
  8. Scope projects — Only search companies/{co}/projects/ for existing project collision check

If source is none — do not silently assume personal scope. Ask the user which company this belongs to, or whether it is personal/HQ work, before creating any project files. The full input text is the project description either way.

Step 1: Get Project Description

If user provided input, use as starting point.

If empty, ask the user: "Describe what you want to build or accomplish." Wait for response.

Step 2: Scan HQ Context

Before asking questions, explore HQ. Resolve mode from Step 0 + input:

If {co} is anchored, scope all searches to that company.

Companies & Context (only if mode in (company, repo)):

Workers (only if mode in (company, repo) AND the description plausibly needs a worker — otherwise skip):

Existing Projects:

Knowledge (use single qmd hybrid query, not Grep, not vsearch+search pair):

Company Policies (anchored only):

Repo Policies (if repo resolved):

Target Repo (if repo specified or discovered):

Present:

Scanned HQ:
- Mode: {company | repo | personal/HQ}
- Company: {co} (anchored) | TBD | n/a
- Workers: {relevant list or "skipped"}
- Existing projects: {list or "none matching"}
- Relevant knowledge: {if any}
- Policies: {count loaded, or "none"}
- Category: [company-specific | cross-company | personal | HQ infrastructure]

Step 2.5: Infrastructure Pre-Check

Before generating the PRD, verify infrastructure exists for the target company/repo:

  1. Company: If project targets a company, read companies/manifest.yaml. If company has knowledge: null, flag that it has no knowledge directory. If the user wants one, create companies/{co}/knowledge/ as a plain real directory (never initialize Git or symlink it), add a README if useful, and update the manifest knowledge field with that directory path.
  1. Repo: If repoPath specified and doesn't exist locally, flag: "Repo not found at {path}. Clone it or create new?" Add to manifest.yaml if missing.
  1. qmd collection: If company has qmd_collections: [] in manifest, flag and offer to create collection.

Fix any gaps before proceeding.

Step 3: Get + Validate Project Name

Ask the user for project slug (or infer from description). Then:

  1. If {co} already set by Step 0: use it directly (skip company detection)

If NOT set: determine company from context (infer from description, repo, or ask the user)

  1. Check if companies/{co}/projects/{name}/ exists (also check personal/projects/{name}/ for personal/HQ)
  1. Validate slug format (lowercase, hyphens only)

Step 3.5: Brainstorm Detection

Now that {co} and {slug} are resolved, check if a brainstorm file exists:

companies/{co}/projects/{slug}/brainstorm.md

If found:

  1. Read it. Extract YAML frontmatter (status, source_idea_id)
  2. If status: "promoted" — warn the user: "This brainstorm was already promoted to a PRD. Open existing prd.json instead?"
  3. Extract brainstorm context for use in Step 3.7 (Research) and Step 4 (Interview):
  1. Enrich interview questions (NOT collapse to confirmations). Brainstorm context is added to each question as additional context, but the full question is still asked one-at-a-time:
  1. Mandatory questions from brainstorm unknowns. Items from brainstorm.unknowns ("What We Don't Know") become mandatory interview questions that cannot be smart-skipped, regardless of research findings. These represent gaps the brainstorm session explicitly identified as unresolved. For each unknown:
  1. Higher smart-skip threshold with brainstorm. When brainstorm.md exists, the smart-skip condition for any question requires both brainstorm AND research to clearly answer the question with consistent, unambiguous findings. If brainstorm says one thing and research says another, the question must be asked to resolve the conflict.
  1. Research agents incorporate brainstorm. Step 3.7's Agent 2 (HQ Context Scanner) already includes brainstorm enrichment in its prompt (see {brainstorm_context} variable). When brainstorm.md is detected here, that variable is populated with the brainstorm's recommended approach, rejected approaches, and open questions — so the research brief reflects brainstorm context.

Effect: Interview depth is preserved even with brainstorm. Questions are richer (pre-loaded with brainstorm context as suggested answers) but still asked in full. The brainstorm's explicit unknowns become mandatory deep-dives. This prevents the "brainstorm answered everything → shallow PRD" failure mode.

If not found: proceed normally (no change to existing behavior). All smart-skip thresholds use the default (research-only) conditions.

Step 3.55: Design Detection

Also check for a design artifact produced by /storyboard in design-led mode at companies/{co}/projects/{slug}/design/design.md.

If found:

  1. Read it — surface(s) used, design rationale, and a proposed screen/story list.
  2. Set metadata.designRef to design/design.md (plus any referenced Figma URL). Seed candidate stories from the design's screen list, and add each screen's resolved interaction as enrichment to the Architecture-tier questions (mirrors brainstorm enrichment — informs questions, does not collapse them).
  3. This is the design-led handoff: /storyboard explored visuals first, and /deep-plan now hardens them into a full PRD.

If not found: proceed normally.

Step 3.6: Open Session Journal

Spec: core/knowledge/public/hq-core/journal-spec.md. Open a session journal at the project_dir so research, decisions, and dead ends survive context compaction:

.claude/skills/_shared/journal.sh open deep-plan "{project_dir}"

Where {project_dir} = companies/{co}/projects/{slug}/ or personal/projects/{slug}/ for personal/HQ. The helper:

Subsequent steps (3.7 research synthesis, 4 interview decisions, 8.5 resolved/deferred questions) append curated entries via the same helper. The autocapture PostToolUse hook appends ## Auto-capture lines for any Agent / WebFetch / WebSearch / AskUserQuestion calls.

Skip if: journal helper unavailable (fail-soft).

Step 3.7: Research Phase (Phase 1 — Subagents)

Before asking interview questions, gather context via parallel research subagents. Research artifacts persist to disk (not chat) so they survive session handoffs and are available to execution workers.

Output directory: {project_dir}/research/ (alongside brainstorm.md and prd.json). Where {project_dir} = companies/{co}/projects/{slug}/ or personal/projects/{slug}/ for personal/HQ projects.

mkdir -p {project_dir}/research

Brainstorm-Research Reuse Check (before dispatch)

If Step 3.5 detected an existing brainstorm.md, check whether its research is fresh enough to reuse before dispatching Agent 2 (HQ Context Scanner):

  1. Check brainstorm.md YAML frontmatter for research_persisted: true.
  2. Check that {project_dir}/research/hq-context.md exists.
  3. Compute brainstorm.md mtime. If within 2 days (172800s) of now, set {reuse_hq_context} = true. Otherwise {reuse_hq_context} = false.

Bash reference:

if [[ -f "{project_dir}/research/hq-context.md" ]] \
   && grep -q '^research_persisted: true' "{project_dir}/brainstorm.md" 2>/dev/null; then
  mtime=$(stat -f %m "{project_dir}/brainstorm.md" 2>/dev/null || stat -c %Y "{project_dir}/brainstorm.md")
  age=$(( $(date +%s) - mtime ))
  if (( age < 172800 )); then echo "reuse"; else echo "stale"; fi
fi

Behavior:

Agents 1 (Codebase Scanner) and 3 (Repo Deep-Read) always run when {repoPath} exists — brainstorm does not produce those files.

Agent Dispatch

Spawn agents in parallel using the Agent tool. The Explore agents are read-only (no Write or Edit), so each one returns its findings as its final message. The main session waits for all agents to complete, then writes each returned report verbatim to its file in the table below (creating {project_dir}/research/ first if needed). If an agent returns no usable report, do not create that file.

Resolve {repoPath} from Step 2 context (company manifest repos, user input, or brainstorm references). If no repo is identifiable, set {repoPath} = null.

| Agent | Condition | Output |

|-------|-----------|--------|

| Codebase Scanner | {repoPath} exists | research/codebase-scan.md |

| HQ Context Scanner | {reuse_hq_context} is false | research/hq-context.md (overwrites if stale) |

| Repo Deep-Read | {repoPath} exists | research/repo-analysis.md |

If {repoPath} is null (non-code project): only consider Agent 2 (HQ Context). Skip Agents 1 and 3. If {reuse_hq_context} is also true, no agents dispatch at all — proceed directly to Synthesis, which will still pick up the brainstorm's hq-context.md and landscape.md.


Agent 1 — Codebase Scanner
Spawn Agent (subagent_type: Explore) with prompt:

"Scan the repository at {repoPath} to understand its architecture for a new project: '{description}'.

Search for and document:
1. **Project structure**: Read CLAUDE.md (if exists), package.json/Cargo.toml/go.mod, and top-level directory layout
2. **Tech stack**: Framework, language version, ORM/DB client, auth system, CSS approach, test framework
3. **Existing patterns**: How are routes/endpoints structured? How are components organized? What naming conventions are used?
4. **Data models**: Read schema files, migration directories, or type definitions for existing entities
5. **Auth system**: How is authentication handled? What middleware/guards exist? What roles are defined?
6. **Key integrations**: External services already wired up (Stripe, SendGrid, analytics, etc.)

Return a structured markdown report as your final message. You are read-only and cannot write files; the main session saves your report to {project_dir}/research/codebase-scan.md.

Format:
# Codebase Scan: {repo name}

## Tech Stack
- Framework: ...
- Language: ...
- Database: ...
- Auth: ...
- Testing: ...

## Architecture Patterns
(describe routing, component, and data patterns)

## Existing Data Models
(list entities with key fields and relationships)

## Integrations
(list external services with how they're connected)

## Relevant Existing Code
(files/patterns directly relevant to: '{description}')

Keep the report factual and concise — no recommendations, just findings."
Agent 2 — HQ Context Scanner

The scanner reads the company worker list and that company's manifest entry, writes the report, and stops. It does not search core/workers/registry.yaml or workers/registry.yaml line by line.

Spawn Agent (subagent_type: Explore) with prompt:

"Scan HQ context for a new project '{slug}' ({description}) for company '{co}'.

Read only the sources below. Do not open core/workers/registry.yaml or workers/registry.yaml, and do not scan that registry line by line. For workers and repos, read the company worker list and the company's manifest entry only.

1. **Existing projects**: Read companies/{co}/projects/ — list any related or overlapping projects with their status
2. **Company workers**: Read the company worker list at companies/{co}/workers/ (if it exists). Each subdirectory is one worker; read its worker.yaml for the id, description, and skills. List workers relevant to this project's domain. Do not read the full worker registry.
3. **Company knowledge**: Search companies/{co}/knowledge/ for documents related to '{description keywords}'
4. **Company policies**: List companies/{co}/policies/ — note any hard-enforcement policies that constrain this project
5. **Manifest entry**: Read only the '{co}' entry in companies/manifest.yaml (the block under companies: whose key is {co}), including its repos. Do not scan other companies' entries.
{brainstorm_context}

Return a structured markdown report as your final message. You are read-only and cannot write files; the main session saves your report to {project_dir}/research/hq-context.md.

Format:
# HQ Context: {slug}

## Related Projects
(list with status and overlap description, or 'None found')

## Relevant Workers
(list with skills that apply)

## Knowledge Base Findings
(relevant docs with paths)

## Applicable Policies
(hard-enforcement policies with rule summaries)

## Available Repos
(company repos from the manifest entry)

## Brainstorm Findings
(if brainstorm.md exists: recommended approach, rejected approaches, open questions — otherwise 'No brainstorm')

Keep the report factual and concise — no recommendations, just findings.

Stop after the report file is written. Do not run further searches, do not re-read the worker registry, and do not revise the report unless the write failed."

Brainstorm enrichment: If brainstorm.md was detected in Step 3.5, append to the Agent 2 prompt:

{brainstorm_context} = "
6. **Brainstorm context**: Read {project_dir}/brainstorm.md — extract:
   - Recommended approach and its rationale
   - Rejected approaches and why
   - 'What We Don't Know' items (open questions)
   - Any mentioned tech choices, data models, or architecture preferences
"

If no brainstorm: {brainstorm_context} = ""

Agent 3 — Repo Deep-Read
Spawn Agent (subagent_type: Explore) with prompt:

"Deep-read the repository at {repoPath} for recent activity and test patterns relevant to: '{description}'.

Search for:
1. **Recent git history**: Run `git log --oneline -30` — summarize recent development themes and active areas
2. **Test structure**: Find test directories, test file patterns, test commands in package.json/scripts. Note coverage configuration if present
3. **Recent changes**: Run `git diff --stat HEAD~10` — what files are actively being modified?
4. **CI/CD**: Check .github/workflows/, vercel.json, Dockerfile, deploy scripts — document the deployment pipeline
5. **Open issues/branches**: Run `git branch -r --list 'origin/feature/*'` — note active feature work that might conflict

Return a structured markdown report as your final message. You are read-only and cannot write files; the main session saves your report to {project_dir}/research/repo-analysis.md.

Format:
# Repo Analysis: {repo name}

## Recent Development
(themes from last 30 commits)

## Active Areas
(files/directories with most recent changes)

## Test Infrastructure
- Framework: ...
- Test command: ...
- Coverage: ...
- Test directories: ...

## CI/CD Pipeline
(deployment pipeline description)

## Active Branches
(feature branches that might overlap with this project)

Keep the report factual and concise — no recommendations, just findings."

Synthesis — Research Brief

After all agents complete, the main session reads the research files and writes a compact synthesis:

  1. Read all files in {project_dir}/research/ that the main session wrote from the agent reports (plus a reused hq-context.md). If all dispatched scans returned no usable report, say so in research-brief.md instead of synthesising from nothing.
  2. Synthesize into {project_dir}/research/research-brief.md:
# Research Brief: {slug}

## Key Findings
- {3-5 bullet points of most important discoveries across all agents}

## Pre-Answered Questions
(questions from the Question Bank that research already answers — list question ID + finding)

## Open Questions Surfaced
(new questions raised by research that should be asked during interview)

## Constraints Discovered
(hard policies, existing patterns, or technical constraints that limit options)

## Brainstorm Alignment
(if brainstorm exists: how research findings align/conflict with brainstorm's recommendation — otherwise omit)
  1. Display to user: "Research complete. {N} findings across {agent count} scans. Key constraints: {list}."
  1. Append synthesis to journal (curated layer):
.claude/skills/_shared/journal.sh append "{project_dir}" findings "Research synthesis: key findings — {3-5 bullets}; pre-answered — {list of question IDs}; open questions surfaced — {list}; constraints — {list}"

This preserves the research thinking even if research-brief.md is later edited or the session compacts before PRD finalization.

The research brief is the primary input for smart-skip logic in Step 4. When a question's smart-skip condition references "research," it means checking research-brief.md for pre-answered questions.

Step 4: Deep Interview (Phase 2 — One-at-a-Time)

Sequential one-at-a-time questioning using the Question Bank (see bottom of this file). Each question is asked via AskUserQuestion with 2-4 concrete options + a free text override. Questions are asked one at a time — never batched.

Minimum: 10 questions asked (including smart-skip confirmations). Target: 15. Track count throughout.

Interview Rules

  1. One question at a time. Ask a single question via AskUserQuestion. Wait for the response. Process it. Then ask the next question. Never combine multiple questions into one AskUserQuestion call.
  1. Pushback on vague answers. If the user's response matches the question's pushback pattern (vague, category-level, non-specific), push back once with the defined follow-up. After the pushback response, accept whatever the user provides — never push more than once per question.
  1. Anti-sycophancy. Never say "that's interesting," "great idea," "love that," or similar flattery. Instead, take a position on every answer: "That narrows scope well," "I'd challenge that — {reason}," "Strong signal — the pain is quantified." React substantively or move on silently.
  1. Smart-skip logic. Before asking each question, check its smart-skip condition against:

If the smart-skip condition is met, present the question's confirmation format instead of the full question. Confirmations still count toward the question minimum. Use AskUserQuestion with options: ["Confirm", "Modify — {free text}"].

  1. CEO cognitive patterns as evaluation lenses. Do NOT ask these as explicit questions. Instead, apply them silently when evaluating answers and formulating follow-ups:

Context Enrichment

Use context gathered in Step 2 (company policies, repo policies, manifest) and Step 3.7 (research) to enrich each question with specific details. Weave enrichments into the question text naturally — don't dump detected context separately.

Enrichment sources:

If enrichment fully answers a question, present as confirmation (same as smart-skip): "Research found {X}. Confirm or modify?"

Project Type Classification

After the Strategic tier (questions 1-5), classify the project type to determine which Architecture and Quality questions to ask:

Note skips: "(Skipping {question} — {reason})"

Interview Sequence

Tier 1 — Strategic (5 questions)

Ask questions STRATEGIC-1 through STRATEGIC-5 from the Question Bank, in order. Each via AskUserQuestion.

After STRATEGIC-5 (Premise Challenge): This question generates 2-4 premises. Present each premise via AskUserQuestion with options: ["Agree", "Disagree", "Not sure — needs investigation"]. Premises flagged as "not sure" become mandatory investigation items surfaced in metadata.openQuestions.

After Strategic tier completes: Classify project type (see above). Announce: "Strategic tier complete ({N}/10 minimum). Moving to Architecture."

Tier 2 — Architecture (5 questions, conditional)

Ask questions ARCHITECTURE-1 through ARCHITECTURE-5, skipping per project type classification. Each via AskUserQuestion.

After Architecture tier completes: Announce: "Architecture tier complete ({N}/10 minimum). Moving to Quality."

Tier 3 — Quality (5 questions, conditional)

Ask questions QUALITY-1 through QUALITY-5, skipping per project type classification. Each via AskUserQuestion.

Escape Hatch

After question 10 (regardless of which tier you're in), present an escape hatch via AskUserQuestion:

"10 questions answered — minimum met. {remaining} questions remain in the bank."
Options:
A. "Continue to remaining questions" (recommended for code projects)
B. "Generate PRD now — enough context gathered"

If user chooses B, skip remaining questions and proceed to Step 4.5. If A, continue through remaining questions. Present the escape hatch again after question 13 if questions remain.

After interview completes — append decisions to journal:

.claude/skills/_shared/journal.sh append "{project_dir}" decisions "Interview decisions: project type — {classification}; scope — {what's in / what's out}; premises agreed/disagreed — {brief}; smart-skipped — {count}"

Step 4.5: Metadata Extraction + Operational Questions

After the Question Bank interview completes (or user escapes), extract prd.json metadata from the answers and ask remaining operational questions not covered by the Question Bank.

Metadata extraction — Map interview answers to prd.json fields. This is done automatically by the skill (no user interaction needed):

| Interview Source | prd.json Field |

|-----------------|----------------|

| STRATEGIC-1 (Demand Reality) | metadata.goal |

| STRATEGIC-2 (Status Quo Teardown) | metadata.currentSolution |

| STRATEGIC-3 (Desperate Specificity) | metadata.audiences |

| STRATEGIC-4 (Narrowest Wedge) | metadata.nonGoals (from excluded scope) |

| STRATEGIC-5 (Premise Challenge) | metadata.openQuestions (from "not sure" premises) |

| ARCHITECTURE-1 (Data Model) | metadata.dataModel |

| ARCHITECTURE-2 (Auth) | metadata.authModel |

| ARCHITECTURE-3 (Error Handling) | metadata.architectureNotes (append) |

| ARCHITECTURE-4 (Component Boundaries) | metadata.architectureNotes (append) |

| ARCHITECTURE-5 (Performance) | metadata.performanceRequirements |

| QUALITY-1 (Testing) | drives e2eTests per story |

| QUALITY-2 (Quality Gates) | metadata.qualityGates |

| QUALITY-3 (Monitoring) | metadata.monitoringNotes |

| QUALITY-4 (Rollout) | metadata.rolloutStrategy |

| QUALITY-5 (Success Criteria) | metadata.successCriteria |

Operational questions — Ask these via AskUserQuestion only if not already answered by research or interview context. Skip any that research or prior answers already resolve:

  1. Repo path (if not yet resolved): "Which repo does this target?" Options: list from manifest + "None — non-code project" + free text
  2. Branch name: "Branch name?" Default: feature/{slug}. Options: ["feature/{slug}", "Custom — {free text}"]
  3. Base branch: "Base branch?" Default: main. Options from repo's branches if known
  4. Workers: "Research found these relevant workers: {list}. Use them?" Options: ["Yes — use suggested workers", "Modify list — {free text}", "No workers — direct execution"]
  5. Design reference (UI projects only): "Any design reference?" Options: ["Figma file (provide ID)", "Visual reference", "Follow existing design system", "No constraints", "Not a UI project"]
  6. Integrations (if not covered by ARCHITECTURE questions): "External integrations?" Options: ["None", "Existing — {list from research}", "New — {free text}"]
  7. Analytics (deployable UI only): "Analytics tracking needed?" Options: ["No", "Use existing {system}", "New events needed — {free text}"]
  8. E2E tests: "What E2E tests should verify each story?" For each planned story, ask for Given/When/Then assertions. Options: ["Define tests per story", "Skip — non-deployable project"]

Live Path Watch hook — Before generating the PRD, detect whether this project plausibly replaces, hardens, or builds alongside an existing live production surface. Purpose: prevent silent regressions on routes that already serve real users (this hook was added after a {company} signup outage caused by a silent route regression).

Trigger the hook when ANY of the following match:

On match, ask via AskUserQuestion:

If user picks "Yes": also add a canary E2E test to the highest-priority story: "curl -sS <liveUrl> returns 200 and contains none of {forbiddenTokens}".

Policy core/policies/hq-live-path-watch-on-replacement-prds.md (hard enforcement) blocks PRD generation when the hook matches but the user neither declared replacementFor nor explicitly dismissed. The hook MUST run before Step 5.

Display: "Interview complete. {N} questions asked across {tiers answered} tiers. Generating PRD..."

Step 5: Generate PRD

Create companies/{co}/projects/{name}/ folder with two files. Use personal/projects/{name}/ only for personal/HQ projects.

Primary: companies/{co}/projects/{name}/prd.json

This is the source of truth. /run-project and /execute-task consume this file.

{
  "name": "{project-slug}",
  "description": "{1-sentence goal}",
  "branchName": "feature/{name}",
  "userStories": [
    {
      "id": "US-001",
      "title": "{Story title}",
      "description": "{As a [user], I want [feature] so that [benefit]}",
      "acceptanceCriteria": ["{Specific verifiable criterion}"],
      "e2eTests": [],
      "priority": 1,
      "passes": false,
      "files": [],
      "labels": [],
      "dependsOn": [],
      "notes": "",
      "model_hint": "",
      "worker_preference": []
    }
  ],
  "metadata": {
    "createdAt": "{ISO8601}",
    "goal": "{Overall project goal}",
    "successCriteria": "{Measurable outcome}",
    "qualityGates": ["{from QUALITY-2 — gate commands}"],
    "repoPath": "{repos/private/repo-name or empty}",
    "baseBranch": "{main or staging or master}",
    "relatedWorkers": ["{worker-ids from scan}"],
    "knowledge": ["{relevant knowledge paths}"],
    "audiences": ["{from STRATEGIC-3 — user roles + technical level}"],
    "currentSolution": "{from STRATEGIC-2 — what exists today}",
    "designRef": "{from operational questions — Figma ID, reference, or empty}",
    "nonGoals": ["{from STRATEGIC-4 — explicit out-of-scope items}"],
    "dataModel": "{from ARCHITECTURE-1 — key entities/tables or empty}",
    "authModel": "{from ARCHITECTURE-2 — auth approach or empty}",
    "architectureNotes": "{from ARCHITECTURE-3/4 — approach or empty}",
    "performanceRequirements": "{from ARCHITECTURE-5 — targets or empty}",
    "integrations": ["{from operational questions — service name, type, credentialsReady}"],
    "securityNotes": "{from ARCHITECTURE-2/3 — PII/compliance notes or empty}",
    "rolloutStrategy": "{from QUALITY-4 — ship strategy or empty}",
    "analyticsEvents": ["{from operational questions — event names or empty}"],
    "monitoringNotes": "{from QUALITY-3 — prod monitoring plan or empty}",
    "openQuestions": ["{remaining unresolved questions — Step 8.5 resolves these before Step 9}"],
    "decisions": []
  }
}

decisions[] schema: Appended by Step 8.5 as {question, answer, decidedAt, decidedBy}. Optional — absent means empty. Additive and backwards-compatible; existing PRDs without the field are unaffected.

worker_preference[] schema: Optional ordered list of preferred worker IDs (strings) per story. Used by /execute-task Layer 2 worker selection (core/settings/orchestrator.yaml → worker_selection). When non-empty AND any pinned worker can fill a role slot in the resolved sequence, that worker wins and the LLM picker is skipped. Default: empty array — fully auto-select. Example: ["acme-backend", "acme-qa"].

Populating files: For each story, infer file paths from the description + acceptance criteria + target repo structure. If repoPath is set, search the repo (via qmd or Glob) to find existing files the story will modify, and predict new files it will create. Paths are repo-relative (e.g. src/middleware/auth.ts, not absolute). Best-effort — empty is fine for stories with unclear scope.

Derived: companies/{co}/projects/{name}/README.md

Generate FROM the prd.json data. Human-friendly view.

# {name from prd.json}

**Goal:** {metadata.goal}
**Success:** {metadata.successCriteria}
**Repo:** {metadata.repoPath}
**Branch:** {branchName}

## Overview
{description}

## Audiences
{metadata.audiences — who uses this and their technical level. Omit section if empty}

## Quality Gates
- `{metadata.qualityGates[0]}`

## User Stories

### US-001: {title}
**Description:** {description}
**Priority:** {priority}
**Depends on:** {dependsOn or "None"}

**Acceptance Criteria:**
- [ ] {criterion 1}
- [ ] {criterion 2}

**E2E Tests:** (if non-empty)
- [ ] {e2eTest 1}
- [ ] {e2eTest 2}

## Non-Goals
{metadata.nonGoals — from STRATEGIC-4 excluded scope. If empty, state "None defined"}

## Technical Considerations
{Enriched from interview answers:}
- **Data model:** {metadata.dataModel — or omit if empty}
- **Auth:** {metadata.authModel — or omit if empty}
- **Architecture:** {metadata.architectureNotes — or omit if empty}
- **Performance:** {metadata.performanceRequirements — or omit if empty}
- **Integrations:** {metadata.integrations — list services, note if creds ready. Or omit if empty}
- **Security:** {metadata.securityNotes — or omit if empty}
- **Rollout:** {metadata.rolloutStrategy — or omit if empty}
- **Analytics:** {metadata.analyticsEvents — list events. Or omit if empty}
- **Monitoring:** {metadata.monitoringNotes — or omit if empty}
{Omit any sub-bullet where the field is empty. If ALL fields empty, write general constraints/dependencies instead}

## Decisions
{Render as table from metadata.decisions[]. Omit section entirely if empty. Columns: Question | Answer | Decided by. Populated by Step 8.5 decision-mode pass.}

| Question | Answer | Decided by |
|---|---|---|
| {decisions[i].question} | {decisions[i].answer} | {decisions[i].decidedBy} |

## Open Questions
{Remaining unresolved questions from metadata.openQuestions[]. If all were resolved in Step 8.5, write "None — all resolved in decision mode (see Decisions above)." If any were deferred, list each with its deferredReason and link to the generated pre-flight story.}

Step 5.1: Spec Review (delegated to /review-plan)

Adversarial spec review is no longer inline. After PRD generation, recommend the user run /review-plan {slug} in a fresh session for adversarial review. The review skill at .claude/skills/review-plan/SKILL.md handles the 5-dimension scoring + fix loop standalone.

Reasoning: a deep PRD already costs significant context. Bolting a multi-iteration review subagent onto the same session frequently hit autocompact mid-call (see policy plan-large-prd-defer-heavy-steps.md). Standalone /review-plan runs with full context budget on the just-written PRD.

Note in handoff (Step 9): "Recommended next: /review-plan {slug}".

Steps 5.5–8.5: Finalize (shared)

Follow .claude/skills/_shared/prd-finalize.md in order, as caller /deep-plan. One line per step:

Step 9: Confirm & STOP

Tell user:

Project **{name}** created with {N} user stories.
Decisions resolved: {metadata.decisions.length} (Step 8.5)
Open questions remaining: {metadata.openQuestions.length}

Files:
  companies/{co}/projects/{name}/prd.json   (source of truth — tracks all work)
  companies/{co}/projects/{name}/README.md  (human-readable view)

Post-implementation docs needed:
  {list from postImplementation metadata, or "None detected"}

To execute, start a new session and run:
  /run-project {name}        (multi-story orchestrator)
  /execute-task {name}/US-001 (single story)

Then, by default, run /handoff (or the handoff skill) and end the session so stories execute in a fresh session. If the user explicitly asks to run it in this session, you may proceed to execution after warning once that planning context can bleed into execution, and recommending the handoff + fresh-session path.

Story Guidelines

Story Complexity Budget

Score each story: (AC count x 1) + (file count x 2). Threshold: <= 20.

At PRD generation, compute per-story. If score > 20:

  1. Warn: "US-004 complexity=29. Recommend splitting."
  2. Offer auto-split by: tab group, entity boundary, or API/UI separation
  3. If user declines split: add "model_hint": "opus" to the story

Splitting heuristics:

Rules

Question Bank

Structured question definitions organized into three tiers: Strategic (problem validation + scope control), Architecture (technical design decisions), and Quality (testing, monitoring, shipping). Each question includes pushback patterns, smart-skip conditions, and confirmation formats for brainstorm-aware interviews.

Total: 15 questions (5 Strategic + 5 Architecture + 5 Quality).


STRATEGIC-1: Demand Reality

STRATEGIC-2: Status Quo Teardown

STRATEGIC-3: Desperate Specificity

STRATEGIC-4: Narrowest Wedge

STRATEGIC-5: Premise Challenge


ARCHITECTURE-1: Data Model + Shadow Paths

ARCHITECTURE-2: Auth + Permissions Model

ARCHITECTURE-3: Error Handling + Failure Modes

ARCHITECTURE-4: Component Boundaries + Coupling

ARCHITECTURE-5: Performance + Scale Considerations


QUALITY-1: Testing Strategy

QUALITY-2: Quality Gates + CI

QUALITY-3: Monitoring + Observability

QUALITY-4: Rollout + Risk Mitigation

QUALITY-5: Success Criteria + Definition of Done

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.