Add agent, command, and conversion specifications; introduce templates for agent and command structures

- Created `agent-design-spec.md` detailing agent identity, knowledge, and structure.
- Established `command-design-spec.md` outlining command orchestration, user interaction, and agent coordination.
- Introduced `conversion-spec.md` for guidelines on converting existing files to GSD conventions without content loss.
- Added `agent-md.md` and `command-md.md` templates to standardize the creation of agent and command files.
This commit is contained in:
catlog22
2026-03-17 10:52:05 +08:00
parent abdc66cee7
commit e6255cf41a
10 changed files with 1562 additions and 565 deletions

View File

@@ -9,26 +9,23 @@ allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glo
When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles. When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles.
# Workflow Analyze Command <purpose>
Interactive collaborative analysis workflow combining codebase exploration (cli-explore-agent) with CLI-assisted analysis (Gemini/Codex). Produces a documented discussion timeline with evolving understanding, decision trails, and actionable conclusions.
**Context Source**: cli-explore-agent + Gemini/Codex analysis Invoked when user needs deep, multi-perspective analysis of a topic or codebase question — e.g., architecture review, implementation analysis, concept exploration, or decision evaluation.
**Output Directory**: `.workflow/.analysis/{session-id}/`
**Core Innovation**: Documented discussion timeline with evolving understanding
## Output Artifacts Produces: `discussion.md` (evolving analysis document with TOC, rounds, narrative synthesis), `explorations.json`/`perspectives.json` (structured findings), `conclusions.json` (final synthesis with recommendations). All artifacts stored in `.workflow/.analysis/{session-id}/`.
</purpose>
| Phase | Artifact | Description | <conventions>
|-------|----------|-------------|
| 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata | ### AskUserQuestion Constraints
| 1 | Session variables | Dimensions, focus areas, analysis depth |
| 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent | All `AskUserQuestion` calls MUST comply:
| 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) | - **questions**: 1-4 questions per call
| 2 | `explorations.json` | Single perspective aggregated findings | - **options**: 2-4 per question (system auto-adds "Other" for free-text input)
| 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis | - **header**: max 12 characters
| 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced | - **label**: 1-5 words per option
| 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
| 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
| 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
### Decision Recording Protocol ### Decision Recording Protocol
@@ -38,7 +35,7 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
|---------|---------------|----------------| |---------|---------------|----------------|
| **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` | | **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` |
| **Key finding** | Content, impact scope, confidence level, hypothesis impact | `#### Key Findings` | | **Key finding** | Content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
| **Assumption change** | Old new understanding, reason, impact | `#### Corrected Assumptions` | | **Assumption change** | Old -> new understanding, reason, impact | `#### Corrected Assumptions` |
| **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` | | **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` |
| **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` | | **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` |
| **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` | | **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` |
@@ -63,23 +60,33 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
**Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason+rejected), Traceability (later phases trace back), Depth (capture reasoning, not just outcomes) **Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason+rejected), Traceability (later phases trace back), Depth (capture reasoning, not just outcomes)
## Implementation ### Output Artifacts
### AskUserQuestion Constraints | Phase | Artifact | Description |
|-------|----------|-------------|
| 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata |
| 1 | Session variables | Dimensions, focus areas, analysis depth |
| 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent |
| 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) |
| 2 | `explorations.json` | Single perspective aggregated findings |
| 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis |
| 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
| 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
| 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
| 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
All `AskUserQuestion` calls MUST comply: </conventions>
- **questions**: 1-4 questions per call
- **options**: 2-4 per question (system auto-adds "Other" for free-text input)
- **header**: max 12 characters
- **label**: 1-5 words per option
### Session Initialization <process>
<step name="session_init" priority="first">
**Initialize session and create progress tracking.**
1. Extract topic/question from `$ARGUMENTS` 1. Extract topic/question from `$ARGUMENTS`
2. Generate session ID: `ANL-{slug}-{date}` (slug: lowercase alphanumeric+Chinese, max 40 chars; date: YYYY-MM-DD UTC+8) 2. Generate session ID: `ANL-{slug}-{date}` (slug: lowercase alphanumeric+Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
3. Define session folder: `.workflow/.analysis/{session-id}` 3. Define session folder: `.workflow/.analysis/{session-id}`
4. Parse options: `-c`/`--continue` for continuation, `-y`/`--yes` for auto-approval 4. Parse options: `-c`/`--continue` for continuation, `-y`/`--yes` for auto-approval
5. Auto-detect: If session folder + discussion.md exist continue mode 5. Auto-detect: If session folder + discussion.md exist -> continue mode
6. Create directory structure 6. Create directory structure
7. **Create Progress Tracking** (TodoWrite — MANDATORY): 7. **Create Progress Tracking** (TodoWrite — MANDATORY):
``` ```
@@ -95,10 +102,12 @@ All `AskUserQuestion` calls MUST comply:
- **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"` - **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"`
**Session Variables**: `sessionId`, `sessionFolder`, `autoMode` (boolean), `mode` (new|continue) **Session Variables**: `sessionId`, `sessionFolder`, `autoMode` (boolean), `mode` (new|continue)
</step>
### Phase 1: Topic Understanding <step name="topic_understanding">
**Phase 1: Parse topic, identify dimensions, and capture user preferences.**
1. **Parse Topic & Identify Dimensions** — Match keywords against Analysis Dimensions table 1. **Parse Topic & Identify Dimensions** — Match keywords against Analysis Dimensions table (see Configuration)
2. **Initial Scoping** (if new session + not auto mode) — use **single AskUserQuestion call with up to 3 questions**: 2. **Initial Scoping** (if new session + not auto mode) — use **single AskUserQuestion call with up to 3 questions**:
- Q1 **Focus** (multiSelect: true, header: "分析方向"): Top 3-4 directions from Dimension-Direction Mapping (options max 4) - Q1 **Focus** (multiSelect: true, header: "分析方向"): Top 3-4 directions from Dimension-Direction Mapping (options max 4)
- Q2 **Perspectives** (multiSelect: true, header: "分析视角"): Up to 4 from Analysis Perspectives table (options max 4), default: single comprehensive - Q2 **Perspectives** (multiSelect: true, header: "分析视角"): Up to 4 from Analysis Perspectives table (options max 4), default: single comprehensive
@@ -109,17 +118,21 @@ All `AskUserQuestion` calls MUST comply:
- Session metadata, user context, initial questions, empty discussion timeline, initial dimension selection rationale - Session metadata, user context, initial questions, empty discussion timeline, initial dimension selection rationale
4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments 4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments
**Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded | Condition | Action |
**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"` |-----------|--------|
| Session folder + discussion.md created | Continue to Phase 2 |
| User provides no input (timeout) | Save state, show resume command `# (see code: E003)` |
### Phase 2: CLI Exploration **TodoWrite**: Update `phase-1` -> `"completed"`, `phase-2` -> `"in_progress"`
</step>
Codebase exploration FIRST, then CLI analysis. <step name="cli_exploration">
**Phase 2: Codebase exploration FIRST, then CLI analysis.**
**Step 1: Codebase Exploration** (cli-explore-agent, parallel up to 6) **Step 1: Codebase Exploration** (cli-explore-agent, parallel up to 6)
- **Single**: General codebase analysis `{sessionFolder}/exploration-codebase.json` - **Single**: General codebase analysis -> `{sessionFolder}/exploration-codebase.json`
- **Multi-perspective**: Parallel per-perspective `{sessionFolder}/explorations/{perspective}.json` - **Multi-perspective**: Parallel per-perspective -> `{sessionFolder}/explorations/{perspective}.json`
- **Common tasks**: `ccw tool exec get_modules_by_depth '{}'`, keyword searches, read `.workflow/project-tech.json` - **Common tasks**: `ccw tool exec get_modules_by_depth '{}'`, keyword searches, read `.workflow/project-tech.json`
```javascript ```javascript
@@ -143,15 +156,15 @@ Session: ${sessionFolder}
### Layer 1 — Module Discovery (Breadth) ### Layer 1 — Module Discovery (Breadth)
- Search by topic keywords, identify ALL relevant files - Search by topic keywords, identify ALL relevant files
- Map module boundaries and entry points relevant_files[] with annotations - Map module boundaries and entry points -> relevant_files[] with annotations
### Layer 2 — Structure Tracing (Depth) ### Layer 2 — Structure Tracing (Depth)
- Top 3-5 key files: trace call chains 2-3 levels deep - Top 3-5 key files: trace call chains 2-3 levels deep
- Identify data flow paths and dependencies call_chains[], data_flows[] - Identify data flow paths and dependencies -> call_chains[], data_flows[]
### Layer 3 — Code Anchor Extraction (Detail) ### Layer 3 — Code Anchor Extraction (Detail)
- Each key finding: extract code snippet (20-50 lines) with file:line - Each key finding: extract code snippet (20-50 lines) with file:line
- Annotate WHY this matters code_anchors[] - Annotate WHY this matters -> code_anchors[]
## Output ## Output
Write to: ${sessionFolder}/exploration-codebase.json Write to: ${sessionFolder}/exploration-codebase.json
@@ -177,7 +190,7 @@ PRIOR EXPLORATION CONTEXT:
- Findings: ${explorationResults.key_findings.slice(0,3).join(', ')} - Findings: ${explorationResults.key_findings.slice(0,3).join(', ')}
- Code anchors: - Code anchors:
${(explorationResults.code_anchors || []).slice(0,5).map(a => ` [${a.file}:${a.lines}] ${a.significance}\n \`\`\`\n ${a.snippet}\n \`\`\``).join('\n')} ${(explorationResults.code_anchors || []).slice(0,5).map(a => ` [${a.file}:${a.lines}] ${a.significance}\n \`\`\`\n ${a.snippet}\n \`\`\``).join('\n')}
- Call chains: ${(explorationResults.call_chains || []).slice(0,3).map(c => `${c.entry} ${c.chain.join(' ')}`).join('; ')}` - Call chains: ${(explorationResults.call_chains || []).slice(0,3).map(c => `${c.entry} -> ${c.chain.join(' -> ')}`).join('; ')}`
// Single perspective (for multi: loop selectedPerspectives with perspective.purpose/tasks/constraints) // Single perspective (for multi: loop selectedPerspectives with perspective.purpose/tasks/constraints)
Bash({ Bash({
@@ -188,10 +201,10 @@ Success: Actionable insights with clear reasoning
${explorationContext} ${explorationContext}
TASK: TASK:
Build on exploration findings — reference specific code anchors - Build on exploration findings — reference specific code anchors
Analyze common patterns and anti-patterns with code evidence - Analyze common patterns and anti-patterns with code evidence
Highlight potential issues/opportunities with file:line references - Highlight potential issues/opportunities with file:line references
Generate discussion points for user clarification - Generate discussion points for user clarification
MODE: analysis MODE: analysis
CONTEXT: @**/* | Topic: ${topic_or_question} CONTEXT: @**/* | Topic: ${topic_or_question}
@@ -230,10 +243,17 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- `synthesis`: {convergent_themes, conflicting_views, unique_contributions} - `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
- code_anchors/call_chains include `perspective` field - code_anchors/call_chains include `perspective` field
**Success**: Exploration + CLI artifacts created, discussion.md Round 1, key findings and exploration decisions recorded | Condition | Action |
**TodoWrite**: Update `phase-2` → `"completed"`, `phase-3` → `"in_progress"` |-----------|--------|
| Exploration + CLI artifacts created | Continue to Phase 3 |
| cli-explore-agent fails | Continue with available context, note limitation `# (see code: E001)` |
| CLI timeout | Retry with shorter prompt, or skip perspective `# (see code: E002)` |
### Phase 3: Interactive Discussion **TodoWrite**: Update `phase-2` -> `"completed"`, `phase-3` -> `"in_progress"`
</step>
<step name="interactive_discussion">
**Phase 3: Interactive discussion loop with evolving understanding.**
**Guideline**: Delegate complex tasks to agents (cli-explore-agent) or CLI calls. Avoid direct analysis in main process. **Guideline**: Delegate complex tasks to agents (cli-explore-agent) or CLI calls. Avoid direct analysis in main process.
@@ -249,26 +269,26 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest) - **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
- **调整方向**: Different focus or specific questions to address - **调整方向**: Different focus or specific questions to address
- **补充信息**: User has additional context, constraints, or corrections to provide - **补充信息**: User has additional context, constraints, or corrections to provide
- **分析完成**: Sufficient exit to Phase 4 - **分析完成**: Sufficient -> exit to Phase 4
4. **Process Response** (always record user choice + impact to discussion.md): 4. **Process Response** (always record user choice + impact to discussion.md):
**继续深入** Sub-question to choose direction (AskUserQuestion, single-select, header: "深入方向"): **继续深入** -> Sub-question to choose direction (AskUserQuestion, single-select, header: "深入方向"):
- Dynamically generate **max 3** context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions, user-highlighted areas - Dynamically generate **max 3** context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions, user-highlighted areas
- Add **1** heuristic option that breaks current frame (e.g., "compare with best practices", "review from security perspective", "explore simpler alternatives") - Add **1** heuristic option that breaks current frame (e.g., "compare with best practices", "review from security perspective", "explore simpler alternatives")
- Total: **max 4 options**. Each specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope - Total: **max 4 options**. Each specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope
- **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option) - **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option)
- Execute selected direction merge new code_anchors/call_chains record confirmed assumptions + deepen angle - Execute selected direction -> merge new code_anchors/call_chains -> record confirmed assumptions + deepen angle
**调整方向** AskUserQuestion (header: "新方向", user selects or provides custom via "Other") new CLI exploration Record Decision (old vs new direction, reason, impact) **调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
**补充信息** Capture user input, integrate into context, answer questions via CLI/analysis if needed Record corrections/additions + updated understanding **补充信息** -> Capture user input, integrate into context, answer questions via CLI/analysis if needed -> Record corrections/additions + updated understanding
**分析完成** Exit loop Record why concluding **分析完成** -> Exit loop -> Record why concluding
5. **Update discussion.md**: 5. **Update discussion.md**:
- **Append** Round N: user input, direction adjustment, Q&A, corrections, new insights - **Append** Round N: user input, direction adjustment, Q&A, corrections, new insights
- **Replace** `## Current Understanding` block with latest consolidated understanding (follow Consolidation Rules: promote confirmed, track corrections, focus on NOW) - **Replace** `## Current Understanding` block with latest consolidated understanding (follow Consolidation Rules)
- **Update** `## Table of Contents` with links to new Round N sections - **Update** `## Table of Contents` with links to new Round N sections
6. **Round Narrative Synthesis** (append to discussion.md after each round update): 6. **Round Narrative Synthesis** (append to discussion.md after each round update):
@@ -291,12 +311,19 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation] - ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation]
- ❌ Intent 4: [not yet discussed] - ❌ Intent 4: [not yet discussed]
``` ```
- If ❌ or ⚠️ items exist **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?" - If ❌ or ⚠️ items exist -> **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
**Success**: All rounds documented with narrative synthesis, assumptions corrected, all decisions recorded with rejection reasoning, direction changes with before/after | Condition | Action |
**TodoWrite**: Update `phase-3` → `"completed"`, `phase-4` → `"in_progress"` |-----------|--------|
| User selects "分析完成" | Exit loop, proceed to Phase 4 |
| Max rounds (5) reached | Force synthesis, offer continuation `# (see code: E004)` |
| User timeout | Save state, show resume command `# (see code: E003)` |
### Phase 4: Synthesis & Conclusion **TodoWrite**: Update `phase-3` -> `"completed"`, `phase-4` -> `"in_progress"`
</step>
<step name="synthesis_conclusion">
**Phase 4: Synthesize findings, verify intent coverage, and determine next steps.**
1. **Intent Coverage Verification** (MANDATORY before synthesis): 1. **Intent Coverage Verification** (MANDATORY before synthesis):
- Check each original intent: ✅ Addressed / 🔀 Transformed / ⚠️ Absorbed / ❌ Missed - Check each original intent: ✅ Addressed / 🔀 Transformed / ⚠️ Absorbed / ❌ Missed
@@ -305,7 +332,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
| # | Original Intent | Status | Where Addressed | Notes | | # | Original Intent | Status | Where Addressed | Notes |
|---|----------------|--------|-----------------|-------| |---|----------------|--------|-----------------|-------|
| 1 | [intent] | ✅ Addressed | Round N, Conclusion #M | | | 1 | [intent] | ✅ Addressed | Round N, Conclusion #M | |
| 2 | [intent] | 🔀 Transformed | Round N M | Original: X Final: Y | | 2 | [intent] | 🔀 Transformed | Round N -> M | Original: X -> Final: Y |
| 3 | [intent] | ❌ Missed | — | Reason | | 3 | [intent] | ❌ Missed | — | Reason |
``` ```
- **Gate**: ❌ Missed items must be either (a) addressed in additional round or (b) confirmed deferred by user - **Gate**: ❌ Missed items must be either (a) addressed in additional round or (b) confirmed deferred by user
@@ -336,11 +363,11 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
``` ```
1. Display all recommendations with numbering (action, rationale, priority, steps[]) 1. Display all recommendations with numbering (action, rationale, priority, steps[])
2. Single AskUserQuestion call — one question per recommendation (max 4, ordered by priority highmediumlow): 2. Single AskUserQuestion call — one question per recommendation (max 4, ordered by priority high->medium->low):
Each question (single-select, header: "建议#N"): Each question (single-select, header: "建议#N"):
- **确认** (label: "确认", desc: "Accept as-is") review_status = "accepted" - **确认** (label: "确认", desc: "Accept as-is") -> review_status = "accepted"
- **修改** (label: "修改", desc: "Adjust scope/steps") review_status = "modified" - **修改** (label: "修改", desc: "Adjust scope/steps") -> review_status = "modified"
- **删除** (label: "删除", desc: "Not needed") review_status = "rejected" - **删除** (label: "删除", desc: "Not needed") -> review_status = "rejected"
3. If >4 recommendations: batch in groups of 4 with additional AskUserQuestion calls 3. If >4 recommendations: batch in groups of 4 with additional AskUserQuestion calls
4. For "修改" selections: follow up to capture modification details 4. For "修改" selections: follow up to capture modification details
5. Record all review decisions to discussion.md Decision Log 5. Record all review decisions to discussion.md Decision Log
@@ -353,7 +380,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
6. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step. 6. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step.
**TodoWrite**: Update `phase-4` `"completed"`, `next-step` `"in_progress"` **TodoWrite**: Update `phase-4` -> `"completed"`, `next-step` -> `"in_progress"`
> **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying conclusions (step 4) and recommendation review (step 5), you MUST immediately proceed here. > **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying conclusions (step 4) and recommendation review (step 5), you MUST immediately proceed here.
@@ -364,7 +391,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
**Handle user selection**: **Handle user selection**:
**"执行任务"** MUST invoke Skill tool (do NOT just display a summary and stop): **"执行任务"** -> MUST invoke Skill tool (do NOT just display a summary and stop):
1. Build `taskDescription` from high/medium priority recommendations (fallback: summary) 1. Build `taskDescription` from high/medium priority recommendations (fallback: summary)
2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json 2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json
3. **Invoke Skill tool immediately**: 3. **Invoke Skill tool immediately**:
@@ -374,15 +401,15 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
If Skill invocation is omitted, the workflow is BROKEN. If Skill invocation is omitted, the workflow is BROKEN.
4. After Skill invocation, analyze-with-file is complete — do not output any additional content 4. After Skill invocation, analyze-with-file is complete — do not output any additional content
**"产出Issue"** Convert recommendations to issues: **"产出Issue"** -> Convert recommendations to issues:
1. For each recommendation in conclusions.recommendations (priority high/medium): 1. For each recommendation in conclusions.recommendations (priority high/medium):
- Build issue JSON: `{title, context: rec.action + rec.rationale, priority: rec.priority == 'high' ? 2 : 3, source: 'discovery', labels: dimensions}` - Build issue JSON: `{title, context: rec.action + rec.rationale, priority: rec.priority == 'high' ? 2 : 3, source: 'discovery', labels: dimensions}`
- Create via pipe: `echo '<issue-json>' | ccw issue create` - Create via pipe: `echo '<issue-json>' | ccw issue create`
2. Display created issue IDs with next step hint: `/issue:plan <id>` 2. Display created issue IDs with next step hint: `/issue:plan <id>`
**"完成"** No further action needed. **"完成"** -> No further action needed.
**TodoWrite**: Update `next-step` `"completed"` after user selection is handled **TodoWrite**: Update `next-step` -> `"completed"` after user selection is handled
**conclusions.json Schema**: **conclusions.json Schema**:
- `session_id`, `topic`, `completed`, `total_rounds`, `summary` - `session_id`, `topic`, `completed`, `total_rounds`, `summary`
@@ -393,10 +420,43 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- `decision_trail[]`: {round, decision, context, options_considered, chosen, rejected_reasons, reason, impact} - `decision_trail[]`: {round, decision, context, options_considered, chosen, rejected_reasons, reason, impact}
- `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions} - `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions}
- `intent_coverage[]`: {intent, status, where_addressed, notes} - `intent_coverage[]`: {intent, status, where_addressed, notes}
</step>
**Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented, `next-step` gate completed </process>
## Configuration <error_codes>
| Code | Severity | Description | Stage |
|------|----------|-------------|-------|
| E001 | error | cli-explore-agent fails — continue with available context, note limitation | cli_exploration |
| E002 | error | CLI timeout — retry with shorter prompt, or skip perspective | cli_exploration |
| E003 | error | User timeout — save state, show resume command | topic_understanding, interactive_discussion |
| E004 | warning | Max discussion rounds (5) reached — force synthesis, offer continuation | interactive_discussion |
| E005 | error | No relevant findings from exploration — broaden search, ask user for clarification | cli_exploration |
| E006 | warning | Session folder conflict — append timestamp suffix | session_init |
| E007 | error | Gemini unavailable — fallback to Codex or manual analysis | cli_exploration |
</error_codes>
<success_criteria>
- [ ] Session folder created with valid session ID
- [ ] Progress tracking (TodoWrite) initialized with all 5 items
- [ ] Dimensions identified and user preferences captured (Phase 1)
- [ ] discussion.md initialized with TOC, Current Understanding, metadata
- [ ] Codebase exploration completed with code_anchors and call_chains (Phase 2)
- [ ] CLI analysis executed and findings aggregated
- [ ] Initial Intent Coverage Check appended to discussion.md
- [ ] Interactive discussion rounds documented with narrative synthesis (Phase 3)
- [ ] Intent Drift Check performed each round >= 2
- [ ] All decisions recorded per Decision Recording Protocol
- [ ] Intent Coverage Matrix verified in Phase 4
- [ ] conclusions.json created with key_conclusions, recommendations, decision_trail
- [ ] discussion.md finalized with conclusions, Decision Trail, session statistics
- [ ] Recommendation review completed (non-auto mode)
- [ ] Next Step terminal gate executed — `next-step` todo is `"completed"`
</success_criteria>
<configuration>
### Analysis Perspectives ### Analysis Perspectives
@@ -440,22 +500,12 @@ Present 2-3 top directions per dimension, allow multi-select + custom.
| Rule | Description | | Rule | Description |
|------|-------------| |------|-------------|
| Promote confirmed insights | Move validated findings to "What We Established" | | Promote confirmed insights | Move validated findings to "What We Established" |
| Track corrections | Keep important wrongright transformations | | Track corrections | Keep important wrong->right transformations |
| Focus on current state | What do we know NOW | | Focus on current state | What do we know NOW |
| Avoid timeline repetition | Don't copy discussion details | | Avoid timeline repetition | Don't copy discussion details |
| Preserve key learnings | Keep insights valuable for future reference | | Preserve key learnings | Keep insights valuable for future reference |
## Error Handling </configuration>
| Error | Resolution |
|-------|------------|
| cli-explore-agent fails | Continue with available context, note limitation |
| CLI timeout | Retry with shorter prompt, or skip perspective |
| User timeout | Save state, show resume command |
| Max rounds reached | Force synthesis, offer continuation |
| No relevant findings | Broaden search, ask user for clarification |
| Session folder conflict | Append timestamp suffix |
| Gemini unavailable | Fallback to Codex or manual analysis |
> **Lite-plan handoff**: Phase 4「执行任务」assembles analysis context as inline `## Prior Analysis` block, allowing lite-plan to skip redundant exploration. > **Lite-plan handoff**: Phase 4「执行任务」assembles analysis context as inline `## Prior Analysis` block, allowing lite-plan to skip redundant exploration.

View File

@@ -1,307 +0,0 @@
---
name: command-generator
description: Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on "create command", "new command", "command generator".
allowed-tools: Read, Write, Edit, Bash, Glob, AskUserQuestion
---
<purpose>
Generate Claude Code command .md files with concrete, domain-specific content in GSD style. Produces command files at project-level (`.claude/commands/`) or user-level (`~/.claude/commands/`) with YAML frontmatter, XML semantic tags (`<purpose>`, `<process>`, `<step>`, `<error_codes>`, `<success_criteria>`), and actionable execution logic — NOT empty placeholders.
Invoked when user requests "create command", "new command", or "command generator".
</purpose>
<required_reading>
- @.claude/skills/command-generator/specs/command-design-spec.md
- @.claude/skills/command-generator/templates/command-md.md
</required_reading>
<process>
<step name="validate_params" priority="first">
**Parse and validate all input parameters.**
Extract from `$ARGUMENTS` or skill args:
| Parameter | Required | Validation | Example |
|-----------|----------|------------|---------|
| `$SKILL_NAME` | Yes | `/^[a-z][a-z0-9-]*$/`, min 1 char | `deploy`, `create` |
| `$DESCRIPTION` | Yes | min 10 chars | `"Deploy application to production"` |
| `$LOCATION` | Yes | `"project"` or `"user"` | `project` |
| `$GROUP` | No | `/^[a-z][a-z0-9-]*$/` or null | `issue`, `workflow` |
| `$ARGUMENT_HINT` | No | any string or empty | `"<url> [--priority 1-5]"` |
**Validation rules:**
- Missing required param → Error with specific message (e.g., `"skillName is required"`)
- Invalid `$SKILL_NAME` pattern → Error: `"skillName must be lowercase alphanumeric with hyphens, starting with a letter"`
- Invalid `$LOCATION` → Error: `"location must be 'project' or 'user'"`
- Invalid `$GROUP` pattern → Warning, continue
**Normalize:** trim + lowercase for `$SKILL_NAME`, `$LOCATION`, `$GROUP`.
</step>
<step name="resolve_target_path">
**Resolve target file path based on location and group.**
Path mapping:
| Location | Base Directory |
|----------|---------------|
| `project` | `.claude/commands` |
| `user` | `~/.claude/commands` (expand `~` to `$HOME`) |
Path construction:
```
If $GROUP:
$TARGET_DIR = {base}/{$GROUP}
$TARGET_PATH = {base}/{$GROUP}/{$SKILL_NAME}.md
Else:
$TARGET_DIR = {base}
$TARGET_PATH = {base}/{$SKILL_NAME}.md
```
Check if `$TARGET_PATH` already exists → store as `$FILE_EXISTS` (true/false).
</step>
<step name="gather_requirements">
**Gather domain-specific requirements to generate concrete content.**
Infer the command's domain from `$SKILL_NAME`, `$DESCRIPTION`, and `$ARGUMENT_HINT`:
| Signal | Extract |
|--------|---------|
| `$SKILL_NAME` | Action verb (deploy, create, analyze, sync) → step naming |
| `$DESCRIPTION` | Domain keywords → execution logic, error scenarios |
| `$ARGUMENT_HINT` | Flags/args → parse_input step details, validation rules |
| `$GROUP` | Command family → related commands, shared patterns |
**Determine command complexity:**
| Complexity | Criteria | Steps to Generate |
|------------|----------|-------------------|
| Simple | Single action, no flags | 2-3 steps |
| Standard | 1-2 flags, clear workflow | 3-4 steps |
| Complex | Multiple flags, multi-phase | 4-6 steps |
**If complexity is unclear**, ask user:
```
AskUserQuestion(
header: "Command Scope",
question: "What are the main execution steps for this command?",
options: [
{ label: "Simple", description: "Single action: validate → execute → report" },
{ label: "Standard", description: "Multi-step: parse → process → verify → report" },
{ label: "Complex", description: "Full workflow: parse → explore → execute → verify → report" },
{ label: "I'll describe", description: "Let me specify the steps" }
]
)
```
Store as `$COMMAND_STEPS`, `$ERROR_SCENARIOS`, `$SUCCESS_CONDITIONS`.
</step>
<step name="draft_content">
**Generate concrete, domain-specific command content in GSD style.**
This is the core generation step. Draft the COMPLETE command file — not a template with placeholders — using the gathered requirements.
**YAML Frontmatter:**
```yaml
---
name: $SKILL_NAME
description: $DESCRIPTION
argument-hint: $ARGUMENT_HINT # only if provided
---
```
**`<purpose>` section:** Write 2-3 sentences describing:
- What the command does (action + target)
- When it's invoked (trigger conditions)
- What it produces (output artifacts or effects)
**`<required_reading>` section:** Infer from domain:
- If command reads config → `@.claude/CLAUDE.md` or relevant config files
- If command modifies code → relevant source directories
- If command is part of a group → other commands in the same group
**`<process>` section with `<step>` blocks:**
For each step in `$COMMAND_STEPS`, generate a `<step name="snake_case">` block containing:
1. **`parse_input`** (always first, `priority="first"`):
- Parse `$ARGUMENTS` for flags and positional args derived from `$ARGUMENT_HINT`
- Include specific flag detection logic (e.g., `if arguments contain "--env"`)
- Include validation with specific error messages
- Include decision routing table if multiple modes exist
2. **Domain-specific execution steps** (2-4 steps):
- Each step has a **bold action description**
- Include concrete shell commands, file operations, or tool calls
- Use `$UPPER_CASE` variables for user input, `${computed}` for derived values
- Include conditional logic with specific conditions (not generic)
- Reference actual file paths and tool names
3. **`report`** (always last):
- Format output with banner and status
- Include file paths, timestamps, next step suggestions
**Shell Correctness Checklist (MANDATORY for every shell block):**
| Rule | Wrong | Correct |
|------|-------|---------|
| Multi-line output | `echo "{ ... }"` (unquoted multi-line) | `cat <<'EOF' > file`...`EOF` (heredoc) |
| Variable init | Use `$VAR` after conditional | `VAR="default"` BEFORE any conditional that sets it |
| Error exit | `echo "Error: ..."` (no exit) | `echo "Error: ..." # (see code: E00X)` + `exit 1` |
| Quoting | `$VAR` in commands | `"$VAR"` (double-quoted in all expansions) |
| Exit on fail | Command chain without checks | `set -e` or explicit `|| { echo "Failed"; exit 1; }` |
| Command from var | `$CMD --flag` (word-split fragile) | `eval "$CMD" --flag` or use array: `cmd=(...); "${cmd[@]}"` |
| Prerequisites | Implicit `git`/`curl` usage | Declare in `<prerequisites>` section |
**Golden Example — a correctly-written execution step:**
```markdown
<step name="run_deployment">
**Execute deployment to target environment.**
$DEPLOY_STATUS="pending" # Initialize before conditional
```bash
# Save current state for rollback
cp .deploy/latest.json .deploy/previous.json 2>/dev/null || true
# Write deployment manifest via heredoc
cat <<EOF > .deploy/latest.json
{
"env": "$ENV",
"tag": "$DEPLOY_TAG",
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"commit": "$(git rev-parse --short HEAD)",
"status": "deploying"
}
EOF
# Execute deployment
if ! deploy_cmd --env "$ENV" --tag "$DEPLOY_TAG" 2>&1 | tee .deploy/latest.log; then
echo "Error: Deployment to $ENV failed" # (see code: E004)
exit 1
fi
$DEPLOY_STATUS="success"
```
| Condition | Action |
|-----------|--------|
| Deploy succeeds | Update status → `"deployed"`, continue to verify |
| Deploy fails | Log error `# (see code: E004)`, exit 1 |
| `$ROLLBACK_MODE` | Load `.deploy/previous.json`, redeploy prior version |
</step>
```
**Optional `<prerequisites>` section** (include when command uses external tools):
```markdown
<prerequisites>
- git (2.20+) — version control operations
- curl — health check endpoints
- jq — JSON processing (optional)
</prerequisites>
```
**`<error_codes>` table:** Generate 3-6 specific error codes:
- Derive from `$ARGUMENT_HINT` validation failures (E001-E003)
- Derive from domain-specific failure modes (E004+)
- Include 1-2 warnings (W001+)
- Each code has: Code, Severity, Description, **Stage** (which step triggers it)
- **Cross-reference rule**: Every `# (see code: E00X)` comment in `<process>` MUST have a matching row in `<error_codes>`, and every error code row MUST be referenced by at least one inline comment
**`<success_criteria>` checkboxes:** Generate 4-8 verifiable conditions:
- Input validation passed
- Each execution step completed its action
- Output artifacts exist / effects applied
- Report displayed
**Quality rules for generated content:**
- NO bracket placeholders (`[Describe...]`, `[List...]`) — all content must be concrete
- Steps must contain actionable logic, not descriptions of what to do
- Error codes must reference specific failure conditions from this command's domain
- Success criteria must be verifiable (not "command works correctly")
- Every shell block must pass the Shell Correctness Checklist above
- Follow patterns from @.claude/skills/command-generator/templates/command-md.md for structural reference only
</step>
<step name="write_file">
**Write generated content to target path.**
**If `$FILE_EXISTS`:** Warn: `"Command file already exists at {path}. Will overwrite."`
```bash
mkdir -p "$TARGET_DIR"
```
Write the drafted content to `$TARGET_PATH` using Write tool.
**Verify:** Read back the file and confirm:
- File exists and is non-empty
- Contains `<purpose>` tag with concrete content (no placeholders)
- Contains at least 2 `<step name=` blocks with shell code or tool calls
- Contains `<error_codes>` with at least 3 rows including Stage column
- Contains `<success_criteria>` with at least 4 checkboxes
- No unresolved `{{...}}` or `[...]` placeholders remain
- Every `# (see code: E0XX)` has a matching `<error_codes>` row (cross-ref check)
- Every shell block uses heredoc for multi-line output (no bare multi-line echo)
- All state variables initialized before conditional use
- All error paths include `exit 1` after error message
**If verification fails:** Fix the content in-place using Edit tool.
**Report completion:**
```
Command generated successfully!
File: {$TARGET_PATH}
Name: {$SKILL_NAME}
Description: {$DESCRIPTION}
Location: {$LOCATION}
Group: {$GROUP or "(none)"}
Steps: {number of <step> blocks generated}
Error codes: {number of error codes}
Next Steps:
1. Review and customize {$TARGET_PATH}
2. Test: /{$GROUP}:{$SKILL_NAME} or /{$SKILL_NAME}
```
</step>
</process>
<error_codes>
| Code | Severity | Description | Stage |
|------|----------|-------------|-------|
| E001 | error | skillName is required | validate_params |
| E002 | error | description is required (min 10 chars) | validate_params |
| E003 | error | location is required ("project" or "user") | validate_params |
| E004 | error | skillName must be lowercase alphanumeric with hyphens | validate_params |
| E005 | error | Failed to infer command domain from description | gather_requirements |
| E006 | error | Failed to write command file | write_file |
| E007 | error | Generated content contains unresolved placeholders | write_file |
| W001 | warning | group must be lowercase alphanumeric with hyphens | validate_params |
| W002 | warning | Command file already exists, will overwrite | write_file |
| W003 | warning | Could not infer required_reading, using defaults | draft_content |
</error_codes>
<success_criteria>
- [ ] All required parameters validated ($SKILL_NAME, $DESCRIPTION, $LOCATION)
- [ ] Target path resolved with correct scope (project vs user) and group
- [ ] Command domain inferred from description and argument hint
- [ ] Concrete `<purpose>` drafted (no placeholders)
- [ ] 2-6 `<step>` blocks generated with domain-specific logic
- [ ] `<error_codes>` table generated with 3+ specific codes
- [ ] `<success_criteria>` generated with 4+ verifiable checkboxes
- [ ] File written to $TARGET_PATH and verified
- [ ] Zero bracket placeholders in final output
- [ ] Completion report displayed
</success_criteria>

View File

@@ -1,65 +0,0 @@
# Command Design Specification
Guidelines for Claude Code command files generated by command-generator.
## YAML Frontmatter
```yaml
---
name: command-name # Required: lowercase with hyphens
description: Description # Required: brief purpose
argument-hint: "[args]" # Optional: argument format hint
allowed-tools: Tool1, Tool2 # Optional: restricted tool set
---
```
## Naming Conventions
| Element | Convention | Examples |
|---------|-----------|----------|
| Command name | lowercase, hyphens, 2-3 words max | `deploy`, `create-issue` |
| Group name | singular noun | `issue`, `session`, `workflow` |
| Verbs for actions | imperative | `deploy`, `create`, `analyze` |
## Path Structure
```
.claude/commands/deploy.md # Top-level command
.claude/commands/issue/create.md # Grouped command
~/.claude/commands/global-status.md # User-level command
```
## Content Structure (GSD Style)
Generated commands should use XML semantic tags:
| Tag | Required | Purpose |
|-----|----------|---------|
| `<purpose>` | Yes | What the command does, when invoked, what it produces |
| `<required_reading>` | Yes | Files to read before execution (@ notation) |
| `<process>` | Yes | Container for execution steps |
| `<step name="...">` | Yes | Individual execution steps with snake_case names |
| `<error_codes>` | No | Error code table with severity and description |
| `<success_criteria>` | Yes | Checkbox list of verifiable completion conditions |
## Step Naming
- Use snake_case: `parse_input`, `validate_config`, `write_output`
- Use action verbs: `discover`, `validate`, `spawn`, `collect`, `report`
- First step gets `priority="first"` attribute
## Error Messages
```
Good: Error: GitHub issue URL required
Usage: /issue:create <github-url>
Bad: Error: Invalid input
```
## Scope Guidelines
| Scope | Location | Use For |
|-------|----------|---------|
| Project | `.claude/commands/` | Team workflows, project integrations |
| User | `~/.claude/commands/` | Personal tools, cross-project utilities |

View File

@@ -1,112 +0,0 @@
# Command Template — Structural Reference
This template defines the **structural pattern** for generated commands. The `draft_content` step uses this as a guide to generate concrete, domain-specific content — NOT as a literal copy target.
## Required Structure
```markdown
---
name: {$SKILL_NAME}
description: {$DESCRIPTION}
argument-hint: {$ARGUMENT_HINT} # omit line if empty
---
<purpose>
{2-3 concrete sentences: what it does + when invoked + what it produces}
</purpose>
<required_reading>
{@ references to files this command needs before execution}
</required_reading>
<prerequisites> <!-- include when command uses external CLI tools -->
- {tool} ({version}+) — {what it's used for}
</prerequisites>
<process>
<step name="parse_input" priority="first">
**Parse arguments and validate input.**
Parse `$ARGUMENTS` for:
- {specific flags from $ARGUMENT_HINT}
- {positional args}
{Decision routing table if multiple modes:}
| Condition | Action |
|-----------|--------|
| flag present | set variable |
| missing required | Error: "message" `# (see code: E001)` + `exit 1` |
</step>
<step name="{domain_action_1}">
**{Concrete action description.}**
$STATE_VAR="default" <!-- Initialize BEFORE conditional -->
```bash
# Use heredoc for multi-line output
cat <<EOF > output-file
{structured content with $VARIABLES}
EOF
# Every error path: message + code ref + exit
if [ ! -f "$REQUIRED_FILE" ]; then
echo "Error: Required file missing" # (see code: E003)
exit 1
fi
```
| Condition | Action |
|-----------|--------|
| success | Continue to next step |
| failure | Error `# (see code: E0XX)`, exit 1 |
</step>
<step name="report">
**Format and display results.**
{Banner with status, file paths, next steps}
</step>
</process>
<error_codes>
| Code | Severity | Description | Stage |
|------|----------|-------------|-------|
| E001 | error | {specific to parse_input validation} | parse_input |
| E002 | error | {specific to domain action failure} | {step_name} |
| W001 | warning | {specific recoverable condition} | {step_name} |
<!-- Every code MUST be referenced by `# (see code: EXXX)` in <process> -->
</error_codes>
<success_criteria>
- [ ] {Input validated}
- [ ] {Domain action 1 completed}
- [ ] {Domain action 2 completed}
- [ ] {Output produced / effect applied}
</success_criteria>
```
## Content Quality Rules
| Rule | Bad Example | Good Example |
|------|-------------|--------------|
| No bracket placeholders | `[Describe purpose]` | `Deploy to target environment with rollback on failure.` |
| Concrete step names | `execute` | `run_deployment`, `validate_config` |
| Specific error codes | `E001: Invalid input` | `E001: --env must be "prod" or "staging"` |
| Verifiable criteria | `Command works` | `Deployment log written to .deploy/latest.log` |
| Real shell commands | `# TODO: implement` | `kubectl apply -f $MANIFEST_PATH` |
## Step Naming Conventions
| Domain | Typical Steps |
|--------|--------------|
| Deploy/Release | `validate_config`, `run_deployment`, `verify_health`, `report` |
| CRUD operations | `parse_input`, `validate_entity`, `persist_changes`, `report` |
| Analysis/Review | `parse_input`, `gather_context`, `run_analysis`, `present_findings` |
| Sync/Migration | `parse_input`, `detect_changes`, `apply_sync`, `verify_state` |
| Build/Generate | `parse_input`, `resolve_dependencies`, `run_build`, `write_output` |

View File

@@ -0,0 +1,401 @@
---
name: prompt-generator
description: Generate or convert Claude Code prompt files — command orchestrators, agent role definitions, or style conversion of existing files. Follows GSD-style content separation with built-in quality gates. Triggers on "create command", "new command", "create agent", "new agent", "convert command", "convert agent", "prompt generator".
allowed-tools: Read, Write, Edit, Bash, Glob, AskUserQuestion
---
<purpose>
Generate or convert Claude Code prompt files with concrete, domain-specific content. Three modes:
- **Create command** — new orchestration workflow at `.claude/commands/` or `~/.claude/commands/`
- **Create agent** — new role + expertise file at `.claude/agents/`
- **Convert** — restyle existing command/agent to GSD conventions with zero content loss
Content separation principle (from GSD): commands own orchestration flow; agents own domain knowledge.
Invoked when user requests "create command", "new command", "create agent", "new agent", "convert command", "convert agent", or "prompt generator".
</purpose>
<required_reading>
- @.claude/skills/prompt-generator/specs/command-design-spec.md
- @.claude/skills/prompt-generator/specs/agent-design-spec.md
- @.claude/skills/prompt-generator/specs/conversion-spec.md
- @.claude/skills/prompt-generator/templates/command-md.md
- @.claude/skills/prompt-generator/templates/agent-md.md
</required_reading>
<process>
## 1. Determine Artifact Type
Parse `$ARGUMENTS` to determine what to generate.
| Signal | Type |
|--------|------|
| "command", "workflow", "orchestrator" in args | `command` |
| "agent", "role", "worker" in args | `agent` |
| "convert", "restyle", "refactor" + file path in args | `convert` |
| Ambiguous or missing | Ask user |
**Convert mode detection:** If args contain a file path (`.md` extension) + conversion keywords, enter convert mode. Extract `$SOURCE_PATH` from args.
If ambiguous:
```
AskUserQuestion(
header: "Artifact Type",
question: "What type of prompt file do you want to generate?",
options: [
{ label: "Command", description: "New orchestration workflow — process steps, user interaction, agent spawning" },
{ label: "Agent", description: "New role definition — identity, domain expertise, behavioral rules" },
{ label: "Convert", description: "Restyle existing command/agent to GSD conventions (zero content loss)" }
]
)
```
Store as `$ARTIFACT_TYPE` (`command` | `agent` | `convert`).
## 2. Validate Parameters
**If `$ARTIFACT_TYPE` is `convert`:** Skip to Step 2c.
Extract from `$ARGUMENTS` or ask interactively:
**Common parameters (create mode):**
| Parameter | Required | Validation | Example |
|-----------|----------|------------|---------|
| `$NAME` | Yes | `/^[a-z][a-z0-9-]*$/` | `deploy`, `gsd-planner` |
| `$DESCRIPTION` | Yes | min 10 chars | `"Deploy to production with rollback"` |
**Command-specific parameters:**
| Parameter | Required | Validation | Example |
|-----------|----------|------------|---------|
| `$LOCATION` | Yes | `"project"` or `"user"` | `project` |
| `$GROUP` | No | `/^[a-z][a-z0-9-]*$/` | `issue`, `workflow` |
| `$ARGUMENT_HINT` | No | any string | `"<phase> [--skip-verify]"` |
**Agent-specific parameters:**
| Parameter | Required | Validation | Example |
|-----------|----------|------------|---------|
| `$TOOLS` | No | comma-separated tool names | `Read, Write, Bash, Glob` |
| `$SPAWNED_BY` | No | which command spawns this agent | `/plan-phase orchestrator` |
Normalize: trim + lowercase for `$NAME`, `$LOCATION`, `$GROUP`.
## 3. Resolve Target Path
**Command:**
| Location | Base |
|----------|------|
| `project` | `.claude/commands` |
| `user` | `~/.claude/commands` |
```
If $GROUP:
$TARGET_PATH = {base}/{$GROUP}/{$NAME}.md
Else:
$TARGET_PATH = {base}/{$NAME}.md
```
**Agent:**
```
$TARGET_PATH = .claude/agents/{$NAME}.md
```
Check if `$TARGET_PATH` exists → `$FILE_EXISTS`.
## 4. Gather Requirements
**4a. Pattern discovery** — Find 3+ similar files in the project for style reference:
```bash
# For commands: scan existing commands
ls .claude/commands/**/*.md 2>/dev/null | head -5
# For agents: scan existing agents
ls .claude/agents/*.md 2>/dev/null | head -5
```
Read 1-2 similar files to extract patterns: section structure, naming conventions, XML tag usage, prompt style.
**4b. Domain inference** from `$NAME`, `$DESCRIPTION`, and context:
| Signal | Extract |
|--------|---------|
| `$NAME` | Action verb → step/section naming |
| `$DESCRIPTION` | Domain keywords → content structure |
| `$ARGUMENT_HINT` | Flags → parse_input logic (command only) |
| `$SPAWNED_BY` | Upstream contract → role boundary (agent only) |
**For commands — determine complexity:**
| Complexity | Criteria | Steps |
|------------|----------|-------|
| Simple | Single action, no flags | 3-5 numbered steps |
| Standard | 1-2 flags, clear workflow | 5-8 numbered steps |
| Complex | Multiple flags, agent spawning | 8-14 numbered steps |
**For agents — determine expertise scope:**
| Scope | Criteria | Sections |
|-------|----------|----------|
| Focused | Single responsibility | `<role>` + 1-2 domain sections |
| Standard | Multi-aspect domain | `<role>` + 2-4 domain sections |
| Expert | Deep domain with rules | `<role>` + 4-6 domain sections |
If unclear, ask user with AskUserQuestion.
## 5. Generate Content
Route to the appropriate generation logic based on `$ARTIFACT_TYPE`.
### 5a. Command Generation
Follow `@specs/command-design-spec.md` and `@templates/command-md.md`.
Generate a complete command file with:
1. **`<purpose>`** — 2-3 sentences: what + when + what it produces
2. **`<required_reading>`** — @ references to context files
3. **`<process>`** — numbered steps (GSD workflow style):
- Step 1: Initialize / parse arguments
- Steps 2-N: Domain-specific orchestration logic
- Each step: banner display, validation, agent spawning via `Task()`, error handling
- Final step: status display + `<offer_next>` with next actions
4. **`<success_criteria>`** — checkbox list of verifiable conditions
**Command writing rules:**
- Steps are **numbered** (`## 1.`, `## 2.`) — follow `plan-phase.md` and `new-project.md` style
- Use banners for phase transitions: `━━━ SKILL ► ACTION ━━━`
- Agent spawning uses `Task(prompt, subagent_type, description)` pattern
- Prompt to agents uses `<objective>`, `<files_to_read>`, `<output>` blocks
- Include `<offer_next>` block with formatted completion status
- Handle agent return markers: `## TASK COMPLETE`, `## TASK BLOCKED`, `## CHECKPOINT REACHED`
- Shell blocks use heredoc for multi-line, quote all variables
- Include `<auto_mode>` section if command supports `--auto` flag
### 5b. Agent Generation
Follow `@specs/agent-design-spec.md` and `@templates/agent-md.md`.
Generate a complete agent definition with:
1. **YAML frontmatter** — name, description, tools, color (optional)
2. **`<role>`** — identity + spawned-by + core responsibilities + mandatory initial read
3. **Domain sections** (2-6 based on scope):
- `<philosophy>` — guiding principles, anti-patterns
- `<context_fidelity>` — how to honor upstream decisions
- `<task_breakdown>` / `<output_format>` — concrete output rules with examples
- `<quality_gate>` — self-check criteria before returning
- Custom domain sections as needed
4. **Output contract** — structured return markers to orchestrator
**Agent writing rules:**
- `<role>` is ALWAYS first after frontmatter — defines identity
- Each section owns ONE concern — no cross-cutting
- Include concrete examples (good vs bad comparison tables) in every domain section
- Include decision/routing tables for conditional logic
- Quality gate uses checkbox format for self-verification
- Agent does NOT contain orchestration logic, user interaction, or argument parsing
### 5c. Convert Mode (Restyle Existing File)
**CRITICAL: Zero content loss.** Follow `@specs/conversion-spec.md`.
**Step 5c.1: Read and inventory source file.**
Read `$SOURCE_PATH` completely. Build content inventory:
```
$INVENTORY = {
frontmatter: { fields extracted },
sections: [ { name, tag, line_range, line_count, has_code_blocks, has_tables } ],
code_blocks: count,
tables: count,
total_lines: count
}
```
**Step 5c.2: Classify source type.**
| Signal | Type |
|--------|------|
| Contains `<process>`, `<step>`, numbered `## N.` steps | command |
| Contains `<role>`, `tools:` in frontmatter, domain sections | agent |
| Flat markdown with `## Implementation`, `## Phase N` | command (unstructured) |
| Flat prose with role description, no process steps | agent (unstructured) |
**Step 5c.3: Build conversion map.**
Map every source section to its target location. Follow `@specs/conversion-spec.md` transformation rules.
**MANDATORY**: Every line of source content must appear in the conversion map. If a source section has no clear target, keep it as a custom section.
**Step 5c.4: Generate converted content.**
Apply structural transformations while preserving ALL content verbatim:
- Rewrap into GSD XML tags
- Restructure sections to match target template ordering
- Add missing required sections (empty `<quality_gate>`, `<output_contract>`) with `TODO` markers
- Preserve all code blocks, tables, examples, shell commands exactly as-is
**Step 5c.5: Content loss verification (MANDATORY).**
Compare source and output:
| Metric | Source | Output | Pass? |
|--------|--------|--------|-------|
| Total lines | `$SRC_LINES` | `$OUT_LINES` | output >= source × 0.95 |
| Code blocks | `$SRC_BLOCKS` | `$OUT_BLOCKS` | output >= source |
| Tables | `$SRC_TABLES` | `$OUT_TABLES` | output >= source |
| Sections | `$SRC_SECTIONS` | `$OUT_SECTIONS` | output >= source |
If ANY metric fails → STOP, display diff, ask user before proceeding.
Set `$TARGET_PATH = $SOURCE_PATH` (in-place conversion) unless user specifies output path.
### Content quality rules (both types):
- NO bracket placeholders (`[Describe...]`) — all content concrete
- NO generic instructions ("handle errors appropriately") — be specific
- Include domain-specific examples derived from `$DESCRIPTION`
- Every shell block: heredoc for multi-line, quoted variables, error exits
## 6. Quality Gate
**MANDATORY before writing.** Read back the generated content and validate against type-specific checks.
### 6a. Structural Validation (both types)
| Check | Pass Condition |
|-------|---------------|
| YAML frontmatter | Has `name` + `description` |
| No placeholders | Zero `[...]` or `{...}` bracket placeholders in prose |
| Concrete content | Every section has actionable content, not descriptions of what to write |
| Section count | Command: 3+ sections; Agent: 4+ sections |
### 6b. Command-Specific Checks
| Check | Pass Condition |
|-------|---------------|
| `<purpose>` | 2-3 sentences, no placeholders |
| `<process>` with numbered steps | At least 3 `## N.` headers |
| Step 1 is initialization | Parses args or loads context |
| Last step is status/report | Displays results or routes to `<offer_next>` |
| Agent spawning (if complex) | `Task(` call with `subagent_type` |
| Agent prompt structure | `<files_to_read>` + `<objective>` or `<output>` blocks |
| Return handling | Routes on `## TASK COMPLETE` / `## TASK BLOCKED` markers |
| `<offer_next>` | Banner + summary + next command suggestion |
| `<success_criteria>` | 4+ checkbox items, all verifiable |
| Content separation | No domain expertise embedded — only orchestration |
### 6c. Agent-Specific Checks
| Check | Pass Condition |
|-------|---------------|
| YAML `tools` field | Lists tools agent needs |
| `<role>` is first section | Appears before any domain section |
| `<role>` has spawned-by | States which command spawns it |
| `<role>` has mandatory read | `<files_to_read>` instruction present |
| `<role>` has responsibilities | 3+ bullet points with verb phrases |
| Domain sections named | After domain concepts, not generic (`<rules>`, `<guidelines>`) |
| Examples present | Each domain section has 1+ comparison table or decision table |
| `<output_contract>` | Defines return markers (COMPLETE/BLOCKED/CHECKPOINT) |
| `<quality_gate>` | 3+ checkbox self-check items |
| Content separation | No `AskUserQuestion`, no banner display, no argument parsing |
### 6d. Quality Gate Result
Count errors and warnings:
| Gate | Condition | Action |
|------|-----------|--------|
| **PASS** | 0 errors, 0-2 warnings | Proceed to write |
| **REVIEW** | 1-2 errors or 3+ warnings | Fix errors, display warnings |
| **FAIL** | 3+ errors | Re-generate from step 5 |
If FAIL and second attempt also fails:
```
AskUserQuestion(
header: "Quality Gate Failed",
question: "Generated content failed quality checks twice. How to proceed?",
options: [
{ label: "Show issues and proceed", description: "Write as-is, fix manually" },
{ label: "Provide more context", description: "I'll give additional details" },
{ label: "Abort", description: "Cancel generation" }
]
)
```
## 7. Write and Verify
**If `$FILE_EXISTS`:** Warn user before overwriting.
```bash
mkdir -p "$(dirname "$TARGET_PATH")"
```
Write content to `$TARGET_PATH` using Write tool.
**Post-write verification** — Read back and confirm file integrity:
- File exists and is non-empty
- Content matches what was generated (no corruption)
- File size is reasonable (command: 50-500 lines; agent: 80-600 lines)
**If verification fails:** Fix in-place with Edit tool.
## 8. Present Status
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PROMPT-GEN ► {COMMAND|AGENT} GENERATED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Type: {command | agent}
File: {$TARGET_PATH}
Name: {$NAME}
| Section | Status |
|---------|--------|
| {section 1} | concrete |
| {section 2} | concrete |
| ... | ... |
Quality Gate: {PASS | REVIEW (N warnings)}
───────────────────────────────────────────────────────
## Next Up
1. Review: cat {$TARGET_PATH}
2. Test: /{invocation}
**If command + needs an agent:**
/prompt-generator agent {agent-name} "{agent description}"
**If agent + needs a command:**
/prompt-generator command {command-name} "{command description}"
───────────────────────────────────────────────────────
```
</process>
<success_criteria>
- [ ] Artifact type determined (command or agent)
- [ ] All required parameters validated
- [ ] Target path resolved correctly
- [ ] 1-2 similar existing files read for pattern reference
- [ ] Domain requirements gathered from description
- [ ] Content generated with concrete, domain-specific logic
- [ ] GSD content separation respected (commands = orchestration, agents = expertise)
- [ ] Quality gate passed (structural + type-specific checks)
- [ ] No bracket placeholders in final output
- [ ] File written and post-write verified
- [ ] Status banner displayed with quality gate result
</success_criteria>

View File

@@ -0,0 +1,299 @@
# Agent Design Specification
Guidelines for Claude Code **agent definition files** (role + domain expertise). Agents own identity, knowledge, and quality standards — NOT orchestration flow.
## Content Separation Principle
Agents are spawned by commands via `Task()`. The agent file defines WHO the agent is and WHAT it knows. It does NOT define WHEN or HOW it gets invoked.
| Concern | Belongs in Agent | Belongs in Command |
|---------|-----------------|-------------------|
| Role identity (`<role>`) | Yes | No |
| Domain expertise | Yes | No |
| Output format/structure | Yes | No |
| Quality heuristics | Yes | No |
| Self-check criteria | Yes | No |
| Philosophy/principles | Yes | No |
| Discovery protocol | Yes | No |
| Specificity examples | Yes | No |
| Argument parsing | No | Yes |
| User interaction | No | Yes |
| Flow control | No | Yes |
| Agent spawning | No | Yes |
| Status banners | No | Yes |
| Revision loop logic | No | Yes |
## YAML Frontmatter
```yaml
---
name: agent-name
description: One-line purpose. Spawned by /command-name orchestrator.
tools: Read, Write, Bash, Glob, Grep # Tools this agent needs
color: green # Optional: terminal color
---
```
**Naming convention:** `{domain}-{role}` or `{project}-{role}` — e.g., `gsd-planner`, `gsd-plan-checker`, `code-reviewer`.
## Content Structure
Agent files use XML semantic tags. `<role>` is ALWAYS first after frontmatter.
### Section Catalog
Derived from GSD agent patterns (`gsd-planner`, `gsd-plan-checker`, `gsd-phase-researcher`):
| Section | Purpose | When to Include |
|---------|---------|-----------------|
| `<role>` | Identity, spawner, responsibilities | **Always** |
| `<project_context>` | How to discover project conventions | Agent reads project files |
| `<philosophy>` | Guiding principles, anti-patterns | Agent has opinionated approach |
| `<context_fidelity>` | Honor upstream decisions (locked/deferred/discretion) | Agent receives user decisions |
| `<upstream_input>` | What the agent receives and how to use it | Agent has structured input |
| `<discovery_levels>` | Research depth protocol (L0-L3) | Agent does research |
| `<task_breakdown>` | Task anatomy, sizing, ordering | Agent produces tasks |
| `<dependency_graph>` | How to build dependency graphs | Agent manages dependencies |
| `<output_format>` | Exact output structure with templates | Agent produces structured output |
| `<core_principle>` | Central verification or design principle | Agent has one key insight |
| `<output_contract>` | Return markers to orchestrator | **Always** |
| `<quality_gate>` | Self-check before returning | **Always** |
### Section Ordering Convention
```
<role> ← Identity (always first)
<project_context> ← How to orient in the project
<philosophy> ← Guiding beliefs
<upstream_input> ← What agent receives
<context_fidelity> ← How to honor decisions
<core_principle> ← Key insight
... domain sections ← Expertise (2-6 sections)
<output_contract> ← Return protocol
<quality_gate> ← Self-check (always last content section)
```
## Section Writing Rules
### `<role>` — Identity (ALWAYS FIRST)
Pattern from `gsd-planner.md` and `gsd-plan-checker.md`:
```markdown
<role>
You are a {role name}. You {primary action verb} {what you produce}.
Spawned by:
- `/{command}` orchestrator (standard mode)
- `/{command} --flag` orchestrator (variant mode)
- `/{command}` in revision mode (updating based on checker feedback)
Your job: {One sentence — what downstream consumers get from you.}
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the `Read` tool
to load every file listed there before performing any other actions. This is your
primary context.
**Core responsibilities:**
- **FIRST: {Most important action}** ({why it's first})
- {Responsibility 2 — verb phrase}
- {Responsibility 3 — verb phrase}
- {Responsibility 4 — verb phrase}
- Return structured results to orchestrator
</role>
```
### `<project_context>` — Project Discovery
Pattern from `gsd-planner.md`:
```markdown
<project_context>
Before {acting}, discover project context:
**Project instructions:** Read `./CLAUDE.md` if it exists. Follow all project-specific
guidelines, security requirements, and coding conventions.
**Project skills:** Check `.claude/skills/` directory if exists:
1. List available skills (subdirectories)
2. Read `SKILL.md` for each skill
3. Load specific files as needed during {action}
4. Ensure {output} accounts for project patterns
</project_context>
```
### `<philosophy>` — Guiding Principles
Pattern from `gsd-planner.md`:
```markdown
<philosophy>
## {Principle Name}
{Core belief about how this agent approaches work.}
| Context Usage | Quality | Agent's State |
|---------------|---------|---------------|
| 0-30% | PEAK | Thorough |
| 50-70% | DEGRADING | Efficiency mode |
| 70%+ | POOR | Rushed |
**Anti-patterns (delete if seen):**
- {Anti-pattern 1 with specific indicator}
- {Anti-pattern 2 with specific indicator}
</philosophy>
```
### `<upstream_input>` — Structured Input Handling
Pattern from `gsd-plan-checker.md`:
```markdown
<upstream_input>
**{Input name}** (if exists) — {Source description}
| Section | How You Use It |
|---------|----------------|
| `## Section A` | LOCKED — {must implement exactly}. Flag if contradicted. |
| `## Section B` | Freedom areas — {can choose approach}, don't flag. |
| `## Section C` | Out of scope — {must NOT include}. Flag if present. |
</upstream_input>
```
### `<context_fidelity>` — Decision Honoring
Pattern from `gsd-planner.md`:
```markdown
<context_fidelity>
## CRITICAL: User Decision Fidelity
**Before creating ANY {output}, verify:**
1. **Locked Decisions** — MUST be implemented exactly as specified
- If user said "use library X" → {output} MUST use X, not alternative
- If user said "card layout" → {output} MUST implement cards
2. **Deferred Ideas** — MUST NOT appear in {output}
- If user deferred "search" → NO search tasks allowed
3. **Discretion Areas** — Use your judgment
- Make reasonable choices and document in {output}
**Self-check before returning:**
- [ ] Every locked decision has coverage
- [ ] No deferred idea appears
- [ ] Discretion areas handled reasonably
**If conflict exists** (research vs user decision):
- Honor the user's locked decision
- Note: "Using X per user decision (research suggested Y)"
</context_fidelity>
```
### Domain Sections — One Concern Each
Name sections after the domain concept. Include concrete examples in EVERY section.
**Required elements per domain section:**
| Element | Minimum |
|---------|---------|
| Good vs bad comparison table | 1 per section |
| Decision/routing table | 1 per section (if conditional logic exists) |
| Format template | 1 per section (if structured output) |
| Concrete example | 2+ per section |
**Example from gsd-planner.md `<task_breakdown>`:**
```markdown
<task_breakdown>
## Task Anatomy
Every task has four required fields:
**<files>:** Exact paths.
- Good: `src/app/api/auth/login/route.ts`
- Bad: "the auth files"
**<action>:** Specific instructions.
- Good: "Create POST endpoint accepting {email, password}, validates using bcrypt,
returns JWT in httpOnly cookie with 15-min expiry. Use jose library."
- Bad: "Add authentication"
## Specificity Examples
| TOO VAGUE | JUST RIGHT |
|-----------|------------|
| "Add auth" | "Add JWT auth with refresh rotation, jose library, httpOnly cookie" |
| "Style the dashboard" | "Tailwind: 3-col grid on lg, 1 on mobile, card shadows, hover states" |
**Test:** Could a different agent execute without clarifying questions?
</task_breakdown>
```
### `<output_contract>` — Return Protocol
```markdown
<output_contract>
## Return Protocol
Return ONE of these markers as the LAST section of output:
### Success
```
## TASK COMPLETE
{Summary of what was produced}
{Artifact locations: file paths}
{Key metrics: counts, coverage}
```
### Blocked
```
## TASK BLOCKED
**Blocker:** {What's missing or preventing progress}
**Need:** {Specific action/info that would unblock}
**Attempted:** {What was tried before declaring blocked}
```
### Checkpoint (needs user decision)
```
## CHECKPOINT REACHED
**Question:** {Decision needed from user}
**Context:** {Why this matters}
**Options:**
1. {Option A} — {effect on output}
2. {Option B} — {effect on output}
```
</output_contract>
```
### `<quality_gate>` — Self-Check (ALWAYS LAST)
```markdown
<quality_gate>
Before returning, verify:
- [ ] {Check 1 — concrete, grep-verifiable}
- [ ] {Check 2 — concrete, counts/exists}
- [ ] {Check 3 — concrete, structural}
- [ ] {Check 4 — no prohibited content}
</quality_gate>
```
## Anti-Patterns
| Anti-Pattern | Why It's Wrong | Correct Approach |
|-------------|----------------|------------------|
| Agent contains `AskUserQuestion` | Agents don't interact with users | Return `## CHECKPOINT REACHED` |
| Agent parses `$ARGUMENTS` | Arguments belong to the command | Receive pre-parsed values in prompt |
| Agent displays banners | UI is the command's job | Return structured data |
| `<role>` is not first section | Identity must be established first | Always lead with `<role>` |
| Generic section names | Hard to scan, unclear scope | Name after domain concept |
| No examples in domain sections | Rules without examples are ambiguous | Include comparison tables |
| Agent spawns other agents | Spawning belongs to commands | Request via `## CHECKPOINT REACHED` |
| Agent defines its own invocation syntax | That's the command's responsibility | Document in `Spawned by:` only |
| Domain section covers multiple concerns | Violates single-concern rule | Split into separate sections |

View File

@@ -0,0 +1,318 @@
# Command Design Specification
Guidelines for Claude Code **command files** (orchestration workflows). Commands own process flow, user interaction, and agent coordination — NOT domain expertise.
## Content Separation Principle
| Concern | Belongs in Command | Belongs in Agent |
|---------|-------------------|-----------------|
| Argument parsing | Yes | No |
| Path resolution | Yes | No |
| User prompts (AskUserQuestion) | Yes | No |
| Status banners | Yes | No |
| Agent spawning (Task) | Yes | No |
| Flow control (if/else routing) | Yes | No |
| Init/context loading (CLI tools) | Yes | No |
| Revision loops | Yes | No |
| Domain knowledge | No | Yes |
| Quality heuristics | No | Yes |
| Output format rules | No | Yes |
| Role identity | No | Yes |
## YAML Frontmatter
```yaml
---
name: command-name # Required: lowercase with hyphens
description: Description # Required: brief purpose
argument-hint: "[args]" # Optional: argument format hint
allowed-tools: Tool1, Tool2 # Optional: restricted tool set
---
```
## Path Structure
```
.claude/commands/deploy.md # Top-level command
.claude/commands/issue/create.md # Grouped command
~/.claude/commands/global-status.md # User-level command
```
## Content Structure
Commands use XML semantic tags with process steps inside `<process>`:
| Tag | Required | Purpose |
|-----|----------|---------|
| `<purpose>` | Yes | What + when + what it produces (2-3 sentences) |
| `<required_reading>` | Yes | @ file references loaded before execution |
| `<process>` | Yes | Steps — numbered or named (see Step Styles below) |
| `<auto_mode>` | Optional | Behavior when `--auto` flag present |
| `<offer_next>` | Recommended | Formatted completion status + next actions |
| `<success_criteria>` | Yes | Checkbox list of verifiable conditions |
## Step Styles
GSD uses two step styles. Choose based on command nature:
### Style A: Numbered Steps (for complex orchestrators)
Used by: `plan-phase.md`, `new-project.md`, `research-phase.md`
Best for: Multi-agent orchestration, long workflows with branching, revision loops.
```markdown
<process>
## 1. Initialize
Load context, parse arguments.
## 2. Validate Phase
Check preconditions.
## 3. Spawn Agent
Display banner, construct prompt, spawn.
## 4. Handle Result
Route on return markers.
## 5. Present Status
Display offer_next.
</process>
```
### Style B: Named `<step>` Blocks (for focused commands)
Used by: `execute-phase.md`, `discuss-phase.md`, `verify-work.md`
Best for: Sequential steps, clear atomic actions, step-level priority.
```markdown
<process>
<step name="initialize" priority="first">
Load context, parse arguments.
</step>
<step name="validate_phase">
Check preconditions.
</step>
<step name="spawn_agent">
Construct prompt, spawn agent.
</step>
<step name="report">
Display results.
</step>
</process>
```
### Which style to use?
| Criteria | Numbered | Named `<step>` |
|----------|----------|----------------|
| Agent spawning with revision loops | Yes | No |
| Multiple conditional branches | Yes | No |
| Sequential with clear boundaries | No | Yes |
| Steps reference each other by number | Yes | No |
| First step needs `priority="first"` | No | Yes |
## Init Pattern
Most GSD commands start by loading context via CLI tools:
```bash
INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init {command} "${ARG}")
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
```
For non-GSD commands, the equivalent is reading config/state files:
```bash
# Read project state
CONFIG=$(cat .claude/config.json 2>/dev/null || echo '{}')
```
## Banner Style
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SKILL ► ACTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
Display banners before major phase transitions (agent spawning, user decisions, completion).
## Agent Spawning Pattern
Commands spawn agents via `Task()` with structured prompts:
```markdown
Task(
prompt=filled_prompt,
subagent_type="agent-name",
model="{model}",
description="Verb Phase {X}"
)
```
### Prompt Structure for Agents
The prompt passed to agents uses XML blocks:
```markdown
<objective>
What to accomplish — specific and measurable.
</objective>
<files_to_read>
- {path1} (description — what this file provides)
- {path2} (description)
</files_to_read>
<additional_context>
**Phase:** {number}
**Mode:** {standard | revision | gap_closure}
Extra info the agent needs.
</additional_context>
<output>
Write to: {output_path}
</output>
```
### Return Handling
Commands route on agent return markers:
```markdown
## Handle Agent Return
- **`## TASK COMPLETE`:** Display confirmation, continue to next step.
- **`## TASK BLOCKED`:** Display blocker, offer user options:
1) Provide context 2) Skip 3) Abort
- **`## CHECKPOINT REACHED`:** Present question to user, relay response.
```
## Revision Loop Pattern
For commands that iterate between generation and verification:
```markdown
## N. Revision Loop (Max 3 Iterations)
Track `iteration_count` (starts at 1).
**If iteration_count < 3:**
- Display: "Sending back for revision... (iteration {N}/3)"
- Spawn agent with revision prompt + checker issues
- After agent returns → spawn checker again, increment count
**If iteration_count >= 3:**
- Display remaining issues
- Offer: 1) Force proceed 2) Provide guidance 3) Abandon
```
## Auto Mode Pattern
Commands supporting `--auto` flag define behavior in `<auto_mode>`:
```markdown
<auto_mode>
## Auto Mode Detection
Check if `--auto` flag is present in $ARGUMENTS.
**If auto mode:**
- Skip confirmation prompts
- Use smart defaults for optional choices
- Auto-approve intermediate results
- Chain to next command on success
**Document requirement (if applicable):**
- What --auto requires as input
- Error message if requirements not met
</auto_mode>
```
## offer_next Pattern
```markdown
<offer_next>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SKILL ► TASK COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**{Summary line}**
| Key | Value |
|-----|-------|
| ... | ... |
Status: {metric 1} | {metric 2}
───────────────────────────────────────────────────────
## Next Up
**{Primary next action}**
/{next-command} {args}
<sub>/clear first — fresh context window</sub>
───────────────────────────────────────────────────────
**Also available:**
- /{alt-1} — description
- /{alt-2} — description
───────────────────────────────────────────────────────
</offer_next>
```
## AskUserQuestion Pattern
For user decisions within commands:
```markdown
AskUserQuestion(
header: "Context",
question: "Descriptive question?",
options: [
{ label: "Option A", description: "Effect of choosing A" },
{ label: "Option B", description: "Effect of choosing B" }
]
)
If "Option A": {action}
If "Option B": {action}
```
## Shell Correctness Rules
| Rule | Wrong | Correct |
|------|-------|---------|
| Multi-line output | `echo "{ ... }"` | `cat <<'EOF' > file`...`EOF` |
| Variable init | Use `$VAR` after conditional | Initialize BEFORE conditional |
| Error exit | `echo "Error"` (no exit) | `echo "Error" && exit 1` |
| Quoting | `$VAR` bare | `"$VAR"` quoted |
| Prerequisites | Implicit tool usage | Declare in `<prerequisites>` |
| File existence | Assume file exists | `test -f "$FILE" && ...` |
## Step Naming Conventions
| Domain | Typical Steps |
|--------|--------------|
| Multi-Agent Pipeline | Initialize, Validate, Spawn Agent A, Handle A Result, Spawn Agent B, Revision Loop, Present Status |
| Deploy/Release | Initialize, Validate Config, Run Deployment, Verify Health, Present Status |
| CRUD | Initialize, Validate Entity, Persist Changes, Present Status |
| Analysis | Initialize, Gather Context, Spawn Analyzer, Present Findings |

View File

@@ -0,0 +1,151 @@
# Conversion Specification
Rules for restyling existing command/agent files to GSD conventions. **Zero content loss is mandatory.**
## Core Principle
Conversion = structural transformation, NOT content rewriting. Every line of source content must appear in the output. Only the container (XML tags, section ordering, frontmatter format) changes.
## Content Loss Prevention Protocol
### Pre-conversion Inventory
Before converting, count:
- `$SRC_LINES` — total non-empty lines
- `$SRC_BLOCKS` — code block count (``` pairs)
- `$SRC_TABLES` — table count (lines starting with `|`)
- `$SRC_SECTIONS` — section count (## headers)
### Post-conversion Verification
| Metric | Rule | Action on Fail |
|--------|------|----------------|
| Lines | output >= source × 0.95 | STOP — find missing content |
| Code blocks | output >= source | STOP — find missing blocks |
| Tables | output >= source | STOP — find missing tables |
| Sections | output >= source | WARN — sections may have merged |
### Diff Display
After conversion, show summary:
```
Conversion Summary:
Source: {path} ({src_lines} lines, {src_blocks} code blocks)
Output: {path} ({out_lines} lines, {out_blocks} code blocks)
Delta: {+/-} lines, {+/-} code blocks
New sections added: {list of TODO sections}
```
## Command Conversion Rules
### Source Pattern → Target Pattern
| Source Style | Target Style |
|-------------|-------------|
| `# Title` + `## Phase N:` flat markdown | `<purpose>` + `<process>` with numbered `## N.` steps |
| `## Implementation` + `### Phase N` | `<process>` with numbered steps, content preserved |
| `## Overview` / `## Core Principle` | `<purpose>` (merge into 2-3 sentences) + keep details in steps |
| `## Usage` with examples | Keep as-is inside `<process>` step 1 or before `<process>` |
| `## Auto Mode` / `## Auto Mode Defaults` | `<auto_mode>` section |
| `## Quick Reference` | Preserve as-is within appropriate section |
| Inline `AskUserQuestion` calls | Preserve verbatim — these belong in commands |
| `Task()` / agent spawning calls | Preserve verbatim within process steps |
| Banner displays (`━━━`) | Preserve verbatim |
| Code blocks (```bash, ```javascript, etc.) | **Preserve exactly** — never modify code content |
| Tables | **Preserve exactly** — never reformat table content |
### Frontmatter Conversion
| Source Field | Target Field | Transformation |
|-------------|-------------|----------------|
| `name` | `name` | Keep as-is |
| `description` | `description` | Keep as-is |
| `argument-hint` | `argument-hint` | Keep as-is |
| `allowed-tools` | `allowed-tools` | Keep as-is |
| Missing `allowed-tools` | `allowed-tools` | Infer from content (Read, Write, etc.) |
### Section Wrapping
Content that was under plain `##` headers gets wrapped in XML tags:
```
## Overview / ## Core Principle → content moves to <purpose>
## Process / ## Implementation → content moves to <process>
## Success Criteria → content moves to <success_criteria>
## Error Codes → preserve as-is (optional section)
```
**Everything else**: Wrap in appropriate GSD tag or keep as custom section inside `<process>`.
### What to ADD (with TODO markers)
| Missing Element | Add |
|----------------|-----|
| `<purpose>` | Extract from overview/description, mark `<!-- TODO: refine -->` if uncertain |
| `<success_criteria>` | Generate from existing content, mark `<!-- TODO: verify -->` |
| `<offer_next>` | Add skeleton with `<!-- TODO: fill next commands -->` |
| Banners | Add before major transitions if missing |
## Agent Conversion Rules
### Source Pattern → Target Pattern
| Source Style | Target Style |
|-------------|-------------|
| Plain prose role description | `<role>` with structured format |
| `## Core Philosophy` / `## Principles` | `<philosophy>` |
| `## Execution Process` / `## How to` | Domain section with descriptive name |
| `## Quality Gates` / `## Standards` | `<quality_gate>` with checkbox format |
| Flat numbered list of responsibilities | `<role>` core responsibilities bullet list |
| `## Examples` section | Move examples INTO relevant domain sections |
### Frontmatter Conversion
| Source Field | Target Field | Transformation |
|-------------|-------------|----------------|
| `name` | `name` | Keep as-is |
| `description` | `description` | Append "Spawned by /command orchestrator." if missing |
| `color` | `color` | Keep as-is |
| Missing `tools` | `tools` | Infer from content (Read, Write, Bash, etc.) |
### Section Restructuring
1. **`<role>` MUST be first** — gather identity content from wherever it appears
2. **Add "Spawned by:"** if missing — infer from description or mark `<!-- TODO: specify spawner -->`
3. **Add "Mandatory Initial Read"** block if missing
4. **Rename generic sections**: `<rules>` → descriptive name based on content
5. **Add `<output_contract>`** if missing — with TODO marker
6. **Add `<quality_gate>`** if missing — with TODO marker
### What NOT to Change
- Code blocks inside sections — preserve exactly
- Tables — preserve exactly
- Concrete examples (good/bad comparisons) — preserve exactly
- Shell commands — preserve exactly
- Agent prompts — preserve exactly
- Domain-specific terminology — preserve exactly
## Batch Conversion
For converting multiple files:
```bash
# List candidates
ls .claude/commands/**/*.md .claude/agents/*.md
# Convert one at a time, verify each
/prompt-generator convert .claude/commands/issue/new.md
/prompt-generator convert .claude/agents/universal-executor.md
```
## Anti-Patterns
| Anti-Pattern | Why It's Wrong |
|-------------|----------------|
| Rewriting code blocks | Content loss — code is sacred |
| Summarizing verbose sections | Content loss — preserve verbatim |
| Removing "redundant" content | User may depend on it |
| Merging sections without inventory | May lose content silently |
| Adding content beyond structural tags | Conversion adds structure, not content |
| Skipping post-conversion line count | Cannot verify zero content loss |

View File

@@ -0,0 +1,145 @@
# Agent Template — Structural Reference
Defines the structural pattern for generated **agent definition files**. The generator uses this as a guide to produce concrete, domain-specific content — NOT as a literal copy target.
## Required Structure
```markdown
---
name: {$NAME}
description: {One-line purpose. Spawned by /command-name orchestrator.}
tools: {Read, Write, Bash, Glob, Grep}
color: {green|blue|yellow|red} # optional
---
<role>
You are a {role name}. You {primary action} {what you produce}.
Spawned by:
- `/{command}` orchestrator (standard mode)
- `/{command} --flag` orchestrator (variant mode)
Your job: {One sentence — what downstream consumers get from you.}
**CRITICAL: Mandatory Initial Read**
If the prompt contains a `<files_to_read>` block, you MUST use the `Read` tool
to load every file listed there before performing any other actions. This is your
primary context.
**Core responsibilities:**
- {Verb phrase — primary task}
- {Verb phrase — secondary task}
- {Verb phrase — quality assurance}
- Return structured results to orchestrator
</role>
<philosophy>
## {Guiding Principle Name}
{Core beliefs — 3-5 bullet points}
**Anti-patterns (delete if seen):**
- {Anti-pattern 1}
- {Anti-pattern 2}
</philosophy>
<{domain_section_1}>
## {Domain Concept Name}
{Rules, heuristics, decision tables for this aspect.}
| {Condition} | {Action} |
|-------------|----------|
| ... | ... |
{Concrete examples — good vs bad:}
| TOO VAGUE | JUST RIGHT |
|-----------|------------|
| "..." | "..." |
</{domain_section_1}>
<{domain_section_2}>
## {Another Domain Concept}
{Format templates, structural rules, required fields.}
Every {output unit} has {N} required fields:
- **<field_1>:** {What it contains, why it matters}
- **<field_2>:** {What it contains, why it matters}
</{domain_section_2}>
<output_contract>
## Return Protocol
Agent returns one of these markers to the orchestrator:
### Success
```
## TASK COMPLETE
{Structured output summary}
{Artifact locations}
```
### Blocked
```
## TASK BLOCKED
**Blocker:** {What's missing}
**Need:** {What would unblock}
```
### Checkpoint
```
## CHECKPOINT REACHED
**Question:** {Decision needed from user}
**Options:**
1. {Option A} — {effect}
2. {Option B} — {effect}
```
</output_contract>
<quality_gate>
Before returning, verify:
- [ ] {Check 1 — concrete, verifiable}
- [ ] {Check 2 — concrete, verifiable}
- [ ] {Check 3 — concrete, verifiable}
- [ ] {Check 4 — concrete, verifiable}
</quality_gate>
```
## Section Design Guidelines
### Section Naming
Name sections after the domain concept they cover:
| Good | Bad |
|------|-----|
| `<task_breakdown>` | `<rules>` |
| `<dependency_graph>` | `<guidelines>` |
| `<code_style>` | `<misc>` |
| `<review_dimensions>` | `<other>` |
### Section Independence
Each section owns ONE concern. Test: can you explain the section's scope in one sentence?
| One Concern | Multiple Concerns (split it) |
|-------------|------------------------------|
| How to size tasks | How to size tasks AND how to order them |
| Review criteria | Review criteria AND how to present results |
| Error handling rules | Error handling AND logging AND monitoring |
### Example Density
Domain sections MUST include concrete examples. Minimum per section:
| Section Type | Minimum Examples |
|-------------|-----------------|
| Rules/heuristics | 1 good-vs-bad table |
| Format definitions | 1 complete template |
| Decision logic | 1 routing table |
| Quality criteria | 3+ checkbox items |

View File

@@ -0,0 +1,117 @@
# Command Template — Structural Reference
Defines the structural pattern for generated **command files**. The generator uses this as a guide to produce concrete, domain-specific content — NOT as a literal copy target.
## Required Structure
```markdown
---
name: {$NAME}
description: {$DESCRIPTION}
argument-hint: {$ARGUMENT_HINT} # omit if empty
allowed-tools: {tools} # omit if unrestricted
---
<purpose>
{2-3 sentences: what it does + when invoked + what it produces}
</purpose>
<required_reading>
{@ references to files needed before execution}
</required_reading>
<process>
## 1. Initialize
{Load context, parse $ARGUMENTS, validate preconditions.}
{Argument table:}
| Flag/Arg | Required | Description |
|----------|----------|-------------|
| `$ARG1` | Yes | ... |
| `--flag` | No | ... |
{Validation: missing required → error, invalid → error with usage hint.}
## 2. {Domain Action}
{Display banner:}
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SKILL ► ACTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
{Core orchestration logic — file checks, state validation, conditional routing.}
## 3. Spawn Agent (if applicable)
{Construct prompt with <files_to_read>, <objective>, <output> blocks.}
```
Task(
prompt=filled_prompt,
subagent_type="{agent-name}",
description="{Verb} {target}"
)
```
## 4. Handle Result
{Route on agent return markers:}
- `## TASK COMPLETE` → continue to next step
- `## TASK BLOCKED` → display blocker, offer options
- `## CHECKPOINT REACHED` → present to user, relay response
## N. Present Status
{Route to <offer_next>.}
</process>
<offer_next>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SKILL ► TASK COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**{Summary line}**
{Status table or key-value pairs}
## Next Up
/{next-command} {args}
**Also available:**
- /{alt-command-1} — description
- /{alt-command-2} — description
</offer_next>
<success_criteria>
- [ ] {Precondition validated}
- [ ] {Core action completed}
- [ ] {Agent spawned and returned (if applicable)}
- [ ] {Output artifact produced / effect applied}
- [ ] {Status displayed to user}
</success_criteria>
```
## Step Naming Conventions
| Domain | Typical Steps |
|--------|--------------|
| Deploy/Release | Initialize, Validate Config, Run Deployment, Verify Health, Present Status |
| CRUD | Initialize, Validate Entity, Persist Changes, Present Status |
| Analysis | Initialize, Gather Context, Spawn Analyzer, Present Findings |
| Multi-Agent | Initialize, Spawn Agent A, Handle A Result, Spawn Agent B, Revision Loop, Present Status |
| Pipeline | Initialize, Stage 1, Handle Stage 1, Stage 2, Handle Stage 2, Present Status |
## Content Quality Rules
| Rule | Bad | Good |
|------|-----|------|
| No placeholders | `[Describe purpose]` | `Deploy to target environment with rollback on failure.` |
| Concrete steps | `Handle the deployment` | `Run kubectl apply, wait for rollout, check health endpoint` |
| Specific errors | `Error: invalid` | `Error: --env must be "prod" or "staging"` |
| Verifiable criteria | `Works correctly` | `Health endpoint returns 200 within 30s` |