{"id":"generate","name":"generate","summary":"prd-taskmasterパイプラインのフェーズ2:スペック生成とタスク解析。","body":"# Phase 2: Generate\n\nDeclarative phase skill. Invoked by the prd-taskmaster orchestrator when\n`current_phase` is `GENERATE`. Never called directly by a user.\n\nThe one rule: **generate the spec, validate it catches placeholders, parse it\ninto tasks, expand every task into subtasks. Quality over speed.**\n\n## Entry gate\n\n1. Call `mcp__plugin_prd_go__check_gate(phase=\"GENERATE\", evidence={})` for diagnostics.\n\n   `check_gate` is an EXIT gate: it checks `task_count > 0`, `subtask_coverage >= 1.0`,\n   and `validation_grade in (EXCELLENT, GOOD)` — all of which are GENERATE's OWN OUTPUTS,\n   i.e. evidence to *advance*, not preconditions to *enter*. On first entry none exist\n   yet, so a `gate_passed: false` here is EXPECTED — the state machine's legal\n   transitions already guarantee only legal entry.\n\n   - **First entry** (no evidence yet): note the result and continue with the Procedure.\n   - **Re-entry**: if the gate reports violations, report them and stop — it protects\n     against re-running a completed phase or skipping ahead from DISCOVER.\n2. Read the DISCOVER output (discovery summary + `CONSTRAINTS CAPTURED` block\n   + scale classification). If any of these are missing, report and stop — the\n   gate should have caught this, but belt-and-braces.\n\n## Generate checklist\n\nCopy into your response before running the procedure:\n\n```\nGENERATE CHECKLIST:\n- [ ] Template loaded (comprehensive|minimal)\n- [ ] Spec written with discovery answers (no bare placeholders remaining)\n- [ ] CONSTRAINT CHECK: every DISCOVER constraint appears in the spec\n- [ ] SCOPE CHECK: task count matches scale (Solo 8-12, Team 12-20, Enterprise 20-30)\n- [ ] Validation score: ___ / ___ (grade: ___)\n- [ ] placeholders_found: ___ (bare placeholders = 0 required)\n- [ ] Warnings addressed or acknowledged\n- [ ] Tasks parsed: ___ tasks created\n- [ ] Complexity analyzed via TaskMaster: Y/N\n- [ ] All tasks expanded into subtasks: Y/N\n```\n\n## Step 1: Choose and load template\n\nDecide based on discovery depth:\n\n- **Comprehensive**: 4+ detailed answers, complex project, Team / Enterprise scale\n- **Minimal**: thin answers, user wants speed, Solo scale\n\n**MCP (preferred)**: `mcp__plugin_prd_go__load_template(type=\"comprehensive\")`\n\n**CLI fallback**: `python3 script.py load-template --type comprehensive`\n\nThe template is the canonical shape — do not invent your own. If the template\nload fails, report and stop. Do not paper over with a home-rolled skeleton.\n\n## Step 2: Generate spec at `.taskmaster/docs/prd.md`\n\nFill the template with discovery answers. AI judgment required:\n\n- Replace ALL placeholders with actual content pulled from DISCOVER.\n- Expand with project-specific details — do not leave template prose verbatim.\n- Add technical depth proportional to what the user provided in discovery.\n- Generate domain-appropriate sections (pentest = threat model, app = user\n  stories, business = success metrics, learning = assessment criteria).\n- Document assumptions where discovery was thin — explicitly, not silently.\n\n### CONSTRAINT CHECK (MANDATORY)\n\nVerify EVERY constraint from the DISCOVER phase `CONSTRAINTS CAPTURED` block\nappears in the spec. If \"must use Python\" was a constraint, the spec MUST\nreference Python. Missing constraints = spec bug.\n\nEmit the check explicitly:\n\n```\nCONSTRAINT CHECK:\n- Tech stack (Python): FOUND in spec section \"Technical Stack\"\n- Timeline (MVP in 2 weeks): FOUND in spec section \"Milestones\"\n- ...\n```\n\nEvery constraint must be marked FOUND. If any are MISSING, loop back and\nfix the spec before proceeding.\n\n### SCOPE CHECK (MANDATORY)\n\nUse the scale classification from DISCOVER to set task count range:\n\n| Scale      | Task Count | Subtask Depth    |\n|------------|-----------|------------------|\n| Solo       | 8–12      | 2–3 subtasks each |\n| Team       | 12–20     | 3–5 subtasks each |\n| Enterprise | 20–30     | 5–8 subtasks each |\n\nIf DISCOVER classified the project as Team but the spec implies 30 tasks,\nthat's a scope bug — narrow the spec or re-classify explicitly.\n\n### Domain-neutral vocabulary\n\nWhen the domain is unclear, default to neutral terms:\n\n| Software term | Neutral equivalent | When to use neutral |\n|---------------|-------------------|---------------------|\n| tests         | verification criteria | pentest, business, learning |\n| code          | deliverable        | business, learning |\n| deploy        | execute / deliver  | business, learning |\n| repo          | workspace          | non-software |\n| PR            | output / submission | non-software |\n\nIf the domain IS software, use software terms. Neutral terms are for\nnon-software goals.\n\n### Deferred decisions — the `reason:` convention\n\nEvery `[placeholder]`, `{{variable}}`, `[TBD]`, `[TODO]` must be either:\n\n(a) Replaced with real content,\n(b) Removed entirely, or\n(c) **Paired with a `reason:` explanation** on the same line or the next line\n    documenting why the decision is deferred.\n\nPer the v4 spec: placeholders with `reason:` attribution are allowed and\nsurfaced in the validation output as `deferred_decisions`. A bare placeholder\nis a validation failure; an attributed one is a known deferred decision with\naccountability.\n\nExamples:\n\n```\n# BAD — bare placeholder, fails validation:\nTarget latency: {{TBD}}\n\n# GOOD — attributed, appears in deferred_decisions:\nTarget latency: {{TBD}} reason: awaiting load-test results scheduled 2026-04-20\n```\n\nWrite the final spec to `.taskmaster/docs/prd.md`. This is the canonical\npath — downstream tools read from here.\n\n## Step 3: Validate spec quality\n\n**MCP (preferred)**: `mcp__plugin_prd_go__validate_prd(input_path=\".taskmaster/docs/prd.md\")`\n\n**CLI fallback**: `python3 script.py validate-prd --input .taskmaster/docs/prd.md`\n\nReturns: `score`, `grade`, `checks`, `warnings`, `placeholders_found`. The\nvalidate call persists its result, so render the GENERATE scorecard and print\nit: MCP `render_status(phase=\"GENERATE\")` → print `rendered`; CLI\n`python3 script.py status --phase GENERATE`.\n\n**Optional AI-augmented review** (opt-in): pass `--ai` (CLI) or `ai=True` (MCP)\nto additionally invoke TaskMaster's configured main model for a holistic\nquality review. The deterministic regex checks always run first — AI review\nis additive, never a replacement.\n\n**Grading thresholds:**\n\n- EXCELLENT: 91%+\n- GOOD: 83–90%\n- ACCEPTABLE: 75–82%\n- NEEDS_WORK: <75%\n\n**Decision rules:**\n\n- If `placeholders_found > 0` (bare placeholders, not `reason:`-attributed):\n  fix before proceeding. No exceptions.\n- If grade is NEEDS_WORK: offer auto-fix or proceed-with-risk — do not silently\n  advance. Surface the decision.\n- If grade is ACCEPTABLE or better AND placeholders_found == 0: proceed to\n  Step 4.\n\n## Step 4: Parse tasks via backend\n\nCalculate task count first:\n\n**MCP**: `mcp__plugin_prd_go__calc_tasks(requirements_count=<count>)`\n\n**CLI**: `python3 script.py calc-tasks --requirements <count>`\n\nThen parse through the normative backend operation:\n\n**backend op parse-prd**: `python3 script.py parse-prd --input .taskmaster/docs/prd.md --num-tasks <recommended>`\n\n**TaskMaster backend direct methods** (only when explicitly operating that backend):\n- **MCP**: `mcp__task-master-ai__parse_prd(input=\".taskmaster/docs/prd.md\", numTasks=<recommended>)`\n- **MCP fallback**: `mcp__plugin_prd_go__tm_parse_prd(input_path=\".taskmaster/docs/prd.md\", num_tasks=<recommended>)`\n- **CLI**: `task-master parse-prd --input .taskmaster/docs/prd.md --num-tasks <recommended>`\n\nThe backend operation writes to `.taskmaster/tasks/tasks.json`. Verify the file exists\nand contains the expected number of tasks before continuing.\n\n## Step 5: Rate complexity via backend\n\nUse the normative backend operation instead of home-rolled classification:\n\n**backend op rate**: `python3 script.py rate`\n\n**TaskMaster backend direct methods** (only when explicitly operating that backend):\n- **MCP**: `mcp__task-master-ai__analyze_complexity` (analyzes all tasks)\n- **MCP fallback**: `mcp__plugin_prd_go__tm_analyze_complexity` (wraps the CLI)\n- **CLI**: `task-master analyze-complexity`\n\n**Important — output location**: the `analyze-complexity` step does NOT emit\nJSON to stdout. It writes structured analysis to\n`.taskmaster/reports/task-complexity-report.json` and prints a human-readable\ntable to stdout. To read the structured result, read the report file:\n\n```bash\ncat .taskmaster/reports/task-complexity-report.json | jq .\n```\n\nDo not try to parse the stdout table — it's colour-coded ASCII and will break\nconsumers. TaskMaster's built-in analysis is more accurate than anything\nhand-rolled because it has full context of the task graph and dependencies.\n\n## Step 6: Expand tasks into subtasks (MANDATORY)\n\nEvery task MUST be expanded into subtasks before HANDOFF. Subtasks are\nverifiable checkpoints — without them, tasks are black boxes that either\npass or fail with no intermediate proof.\n\n### Use backend op expand, NOT bare per-id parallel calls\n\nPer-id parallel calls (e.g. `task-master expand --id=1 & task-master expand\n--id=2 &`) hit a non-atomic read-modify-write race on\n`.taskmaster/tasks/tasks.json`: every parallel writer reads the same starting\nsnapshot, adds its own subtasks, and writes the whole file back. The last\nwriter wins and earlier writes are silently lost — the AI call reports\nsuccess, the subtasks were generated, but they never landed on disk.\nDetected in the v4 Shade dogfood 2026-04-13.\n\n**backend op expand** is the correct path:\n\n```bash\npython3 script.py expand\n```\n\nThe native engine is the sole generator. `script.py expand` (backend op expand)\nexpands pending tasks via the native structured path — a keyless host CLI\n(`claude`/`codex`/`gemini`) or a provider API key — running in parallel and\napplying atomically. When no provider/CLI is available it falls back to\nagent-parallel planning + atomic apply (the native/agent floor).\n\n### Patience under slow providers\n\nUnder `claude-code` (Claude Max rate-limited) or local `ollama`, `--all`\ncan run for 5–15 minutes on a 12-task project. Do NOT time out aggressively.\nUse `.taskmaster/tasks/tasks.json` mtime as the liveness signal:\n\n- **mtime updated within last 60s** → work is landing, keep waiting\n- **mtime stale for 120s+** → investigate (rate limit, provider crash, network)\n- **Never conclude STUCK from a single capture** — always compare two\n  snapshots 30–60s apart\n\n### Verify coverage (read tasks.json DIRECTLY, not `task-master list`)\n\n`task-master list --format json` has been observed to return a different\ntop-level schema from `tasks.json`, causing consumers to report 0/N\ncoverage even when all tasks have subtasks on disk (v4 dogfood LEARNING\n#15). Always read the canonical file directly:\n\n```bash\npython3 -c \"\nimport json\nd = json.load(open('.taskmaster/tasks/tasks.json'))\n# tasks.json is tag-grouped (master, defaults, feature branches) — walk all tags\nall_tasks = []\nif 'master' in d and isinstance(d['master'], dict):\n    all_tasks = d['master'].get('tasks', [])\nelif 'tasks' in d:\n    all_tasks = d['tasks']\nelse:\n    for v in d.values():\n        if isinstance(v, dict) and 'tasks' in v:\n            all_tasks.extend(v['tasks'])\n\ncounts = [len(t.get('subtasks', [])) for t in all_tasks]\ncovered = sum(1 for c in counts if c > 0)\ntotal = len(all_tasks)\nno_subs = [t['id'] for t in all_tasks if not t.get('subtasks')]\n\nif no_subs:\n    print(f'WARNING: {covered}/{total} tasks expanded. Missing: {no_subs}. Re-run backend op expand.')\nelse:\n    print(f'OK: All {total} tasks expanded ({sum(counts)} subtasks total).')\n\"\n```\n\n### Idempotent recovery\n\nIf any task still shows 0 subtasks after `--all` completes (rate-limit hiccup,\nprovider timeout, partial run), re-run the same command:\n\n```bash\npython3 script.py expand\n```\n\nThe backend operation only re-expands tasks that are still in `pending` state\nwith 0 subtasks, so a second invocation is safe and recovers gracefully. Do NOT\nwork around it with parallel per-id calls — that is the exact pattern that\ncauses silent data loss.\n\n## Evidence gate\n\n**Gate: spec validation grade is ACCEPTABLE+ AND placeholders_found == 0 AND\ntasks parsed AND complexity analyzed AND all tasks have subtasks in\n`.taskmaster/tasks/tasks.json`.**\n\nEmit a compact one-block status:\n\n```\nGenerate:\n  spec: .taskmaster/docs/prd.md (grade: <grade>, score: <n>/<total>)\n  placeholders_found: <n> (bare), <m> deferred_decisions\n  tasks parsed: <n>\n  complexity report: .taskmaster/reports/task-complexity-report.json\n  subtask coverage: <n>/<n> tasks expanded (<total> subtasks)\n```\n\n## Exit gate\n\nAfter the evidence gate passes:\n\n1. Call `mcp__plugin_prd_go__advance_phase(expected_current=\"GENERATE\", target=\"HANDOFF\", evidence={\"validation_grade\": \"<EXCELLENT|GOOD|ACCEPTABLE>\", \"task_count\": <int>, \"subtask_coverage\": <float 0-1>, \"placeholders_found\": <int>})`.\n   The call atomically transitions `pipeline.json` from GENERATE to HANDOFF.\n   The `expected_current` field is the compare-and-swap guard;\n   `evidence` is stored under `phase_evidence[HANDOFF]` for audit.\n2. Return control to the orchestrator (`prd-taskmaster` skill). Do NOT invoke\n   HANDOFF directly — the orchestrator re-reads `current_phase` and routes.\n\n## Red flags (stop and report, do not paper over)\n\n- \"The validation says placeholders_found=3 but the content reads fine —\n  I'll advance anyway\" → NO. Bare placeholders are a hard fail. Fix or\n  attribute with `reason:`.\n- \"`task-master expand --all` is slow, let me run `expand_task` in parallel\n  across IDs to speed it up\" → NO. That is the exact race that silently\n  drops subtasks. Serial `--all` or serial per-id only.\n- \"A constraint from DISCOVER isn't in the spec — I'll add it to the\n  handoff note instead\" → NO. Constraints live in the spec. Fix the spec.\n- \"Complexity analyze output looked odd, I'll skip reading the JSON report\"\n  → NO. Read `.taskmaster/reports/task-complexity-report.json` directly;\n  the stdout table is decoration.\n- \"I can call advance_phase without check_gate\" → NO. Gate first, always.\n- \"The template prose is close enough, I'll ship it verbatim\" → NO. The\n  template is a shape, not content. Fill every section with project-specific\n  material.\n\n## Non-exits\n\nThis skill does not use explicit process termination. A hard block reports\nthe reason and returns control to the orchestrator; the orchestrator decides\nwhether to surface to the user.","author":"@anombyte93","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/anombyte93/prd-taskmaster/tree/main/skills/generate","license":"MIT","category":"writing","lang":"en","tokens":3550,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":["plugin_prd_go","task-master-ai"],"tools":["Read","Write","Edit","Bash","Skill","ToolSearch","mcp__atlas-engine","mcp__plugin_prd_go","mcp__plugin_prd-taskmaster_go","mcp__plugin_atlas-go_go"]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":[]}}