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.
# 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
**Output Directory**: `.workflow/.analysis/{session-id}/`
**Core Innovation**: Documented discussion timeline with evolving understanding
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 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 |
|-------|----------|-------------|
| 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 |
<conventions>
### AskUserQuestion Constraints
All `AskUserQuestion` calls MUST comply:
- **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
### 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` |
| **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` |
| **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### 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)
## 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:
- **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
</conventions>
### Session Initialization
<process>
<step name="session_init" priority="first">
**Initialize session and create progress tracking.**
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)
3. Define session folder: `.workflow/.analysis/{session-id}`
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
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"`
**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**:
- 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
@@ -109,17 +118,21 @@ All `AskUserQuestion` calls MUST comply:
- 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
**Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded
**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"`
| Condition | Action |
|-----------|--------|
| 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)
- **Single**: General codebase analysis `{sessionFolder}/exploration-codebase.json`
- **Multi-perspective**: Parallel per-perspective `{sessionFolder}/explorations/{perspective}.json`
- **Single**: General codebase analysis -> `{sessionFolder}/exploration-codebase.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`
```javascript
@@ -143,15 +156,15 @@ Session: ${sessionFolder}
### Layer 1 — Module Discovery (Breadth)
- 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)
- 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)
- 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
Write to: ${sessionFolder}/exploration-codebase.json
@@ -177,7 +190,7 @@ PRIOR EXPLORATION CONTEXT:
- Findings: ${explorationResults.key_findings.slice(0,3).join(', ')}
- Code anchors:
${(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)
Bash({
@@ -188,10 +201,10 @@ Success: Actionable insights with clear reasoning
${explorationContext}
TASK:
Build on exploration findings — reference specific code anchors
Analyze common patterns and anti-patterns with code evidence
Highlight potential issues/opportunities with file:line references
Generate discussion points for user clarification
- Build on exploration findings — reference specific code anchors
- Analyze common patterns and anti-patterns with code evidence
- Highlight potential issues/opportunities with file:line references
- Generate discussion points for user clarification
MODE: analysis
CONTEXT: @**/* | Topic: ${topic_or_question}
@@ -230,10 +243,17 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
- code_anchors/call_chains include `perspective` field
**Success**: Exploration + CLI artifacts created, discussion.md Round 1, key findings and exploration decisions recorded
**TodoWrite**: Update `phase-2` → `"completed"`, `phase-3` → `"in_progress"`
| Condition | Action |
|-----------|--------|
| 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.
@@ -249,26 +269,26 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
- **调整方向**: Different focus or specific questions to address
- **补充信息**: 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):
**继续深入** 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
- 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
- **"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**:
- **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
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 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
**TodoWrite**: Update `phase-3` → `"completed"`, `phase-4` → `"in_progress"`
| Condition | Action |
|-----------|--------|
| 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):
- Check each original intent: ✅ Addressed / 🔀 Transformed / ⚠️ Absorbed / ❌ Missed
@@ -305,7 +332,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
| # | Original Intent | Status | Where Addressed | Notes |
|---|----------------|--------|-----------------|-------|
| 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 |
```
- **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[])
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"):
- **确认** (label: "确认", desc: "Accept as-is") review_status = "accepted"
- **修改** (label: "修改", desc: "Adjust scope/steps") review_status = "modified"
- **删除** (label: "删除", desc: "Not needed") review_status = "rejected"
- **确认** (label: "确认", desc: "Accept as-is") -> review_status = "accepted"
- **修改** (label: "修改", desc: "Adjust scope/steps") -> review_status = "modified"
- **删除** (label: "删除", desc: "Not needed") -> review_status = "rejected"
3. If >4 recommendations: batch in groups of 4 with additional AskUserQuestion calls
4. For "修改" selections: follow up to capture modification details
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.
**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.
@@ -364,7 +391,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
**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)
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**:
@@ -374,15 +401,15 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
If Skill invocation is omitted, the workflow is BROKEN.
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):
- 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`
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**:
- `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}
- `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions}
- `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
@@ -440,22 +500,12 @@ Present 2-3 top directions per dimension, allow multi-select + custom.
| Rule | Description |
|------|-------------|
| 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 |
| Avoid timeline repetition | Don't copy discussion details |
| Preserve key learnings | Keep insights valuable for future reference |
## Error Handling
| 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 |
</configuration>
> **Lite-plan handoff**: Phase 4「执行任务」assembles analysis context as inline `## Prior Analysis` block, allowing lite-plan to skip redundant exploration.