
Memory Manage
- 65 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Manage and organize accumulated context and memory from development
About
Manages and organizes accumulated context, notes, and decisions from ongoing development. Teams use this to keep institutional knowledge organized and accessible across long projects.
- Memory organization
- Context management
- Knowledge organization
Memory Manage by the numbers
- 65 all-time installs (skills.sh)
- Ranked #1,522 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill memory-manageAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 65 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Manage and organize accumulated context and memory from development
Files
Memory Management Skill
Unified entry point for project memory (CLAUDE.md) updates and documentation (API.md/README.md) generation. Routes to specialized sub-commands via arguments or interactive needs assessment.
Architecture Overview
┌──────────────────────────────────────────────────────┐
│ Memory Manage (Router) │
│ → Parse input → Detect mode → Route to phase │
└───────────────┬──────────────────────────────────────┘
│
┌───────┴───────┐
↓ ↓
┌───────────┐ ┌───────────┐
│ CLAUDE.md │ │ Docs │
│ 管理 │ │ 生成 │
└─────┬─────┘ └─────┬─────┘
│ │
┌────┼────┐ ┌────┴────┐
↓ ↓ ↓ ↓ ↓
Full Related Single Full Related
全量 增量 单模块 全量 增量Execution Flow
Step 1: Parse Input & Route
Detect execution mode from user input:
Auto-Route Rules (priority order):
| Signal | Route | Examples |
|---|---|---|
| Explicit sub-command token | → Direct dispatch | update-full --tool qwen |
| Keyword: full, 全量, all, entire + update/claude | → update-full | "全量更新claude" |
| Keyword: related, changed, 增量, diff + update/claude | → update-related | "更新变更模块" |
| Keyword: single, module, 单模块 + path-like token | → update-single | "更新 src/auth 模块" |
| Keyword: docs, documentation, 文档 + full/all/全量 | → docs-full | "全量生成文档" |
| Keyword: docs, documentation, 文档 + related/changed/增量 | → docs-related | "增量生成文档" |
| Ambiguous or no arguments | → AskUserQuestion | /memory-manage |
Valid sub-command tokens: update-full, update-related, update-single, docs-full, docs-related
Direct dispatch examples:
input = "update-full --tool qwen"
→ subcommand = "update-full", remainingArgs = "--tool qwen"
→ Read phases/01-update-full.md, execute
input = "update-single src/auth --tool gemini"
→ subcommand = "update-single", remainingArgs = "src/auth --tool gemini"
→ Read phases/03-update-single.md, executeWhen ambiguous or no arguments, proceed to Step 2.
Step 2: Interactive Needs Assessment
Q1 — 确定内容类别:
AskUserQuestion({
questions: [{
question: "你要管理哪类内容?",
header: "类别",
multiSelect: false,
options: [
{
label: "CLAUDE.md (项目记忆)",
description: "更新模块指令文件,帮助Claude理解代码库结构和约定"
},
{
label: "项目文档 (API+README)",
description: "生成API.md和README.md到.workflow/docs/目录"
}
]
}]
})Q2a — CLAUDE.md 管理范围 (用户选了 CLAUDE.md):
AskUserQuestion({
questions: [{
question: "CLAUDE.md 更新范围?",
header: "范围",
multiSelect: false,
options: [
{
label: "增量更新 (Recommended)",
description: "仅更新git变更模块及其父级,日常开发首选"
},
{
label: "全量更新",
description: "更新所有模块,3层架构bottom-up,适合重大重构后"
},
{
label: "单模块更新",
description: "指定一个模块,Explore深度分析后生成说明书式文档"
}
]
}]
})Route mapping:
- "增量更新" →
update-related→ Ref: phases/02-update-related.md - "全量更新" →
update-full→ Ref: phases/01-update-full.md - "单模块更新" →
update-single→ continue to Q3
Q2b — 文档生成范围 (用户选了项目文档):
AskUserQuestion({
questions: [{
question: "文档生成范围?",
header: "范围",
multiSelect: false,
options: [
{
label: "增量生成 (Recommended)",
description: "仅为git变更模块生成/更新文档,日常开发首选"
},
{
label: "全量生成",
description: "所有模块+项目级文档(ARCHITECTURE.md等),适合初始化"
}
]
}]
})Route mapping:
- "增量生成" →
docs-related→ Ref: phases/05-docs-related.md - "全量生成" →
docs-full→ Ref: phases/04-docs-full.md
Q3 — 补充路径 (仅 update-single 需要,且无路径参数时):
AskUserQuestion({
questions: [{
question: "请指定要更新的模块路径:",
header: "路径",
multiSelect: false,
options: [
{
label: "src",
description: "src 目录"
},
{
label: ".",
description: "项目根目录"
}
]
}]
})用户可选 "Other" 输入自定义路径。
Step 3: Execute Selected Phase
Based on routing result, read and execute the corresponding phase:
Phase Reference Documents (read on-demand when phase executes):
| Mode | Document | Purpose |
|---|---|---|
| update-full | phases/01-update-full.md | Full CLAUDE.md update, 3-layer architecture, batched agents |
| update-related | phases/02-update-related.md | Git-changed CLAUDE.md update, depth-first |
| update-single | phases/03-update-single.md | Single module CLAUDE.md, Explore + handbook style |
| docs-full | phases/04-docs-full.md | Full API.md + README.md generation |
| docs-related | phases/05-docs-related.md | Git-changed docs generation, incremental |
Shared Configuration
Tool Fallback Hierarchy
All sub-commands share the same fallback:
--tool gemini → [gemini, qwen, codex] // default
--tool qwen → [qwen, gemini, codex]
--tool codex → [codex, gemini, qwen]Common Parameters
| Parameter | Description | Default | Used By |
|---|---|---|---|
| `--tool <gemini\ | qwen\ | codex>` | Primary CLI tool |
--path <dir> | Target directory | . | update-full, docs-full |
<path> (positional) | Module path | _(required)_ | update-single |
Batching Thresholds
| Sub-Command | Direct Execution | Agent Batch | Batch Size |
|---|---|---|---|
| update-full | <20 modules | ≥20 modules | 4/agent |
| update-related | <15 modules | ≥15 modules | 4/agent |
| update-single | always single | N/A | 1 |
| docs-full | <20 modules | ≥20 modules | 4/agent |
| docs-related | <15 modules | ≥15 modules | 4/agent |
Core Rules
1. Route before execute: Determine sub-command before any execution 2. Phase doc is truth: All execution logic lives in phase docs, router only dispatches 3. Read on-demand: Only read the selected phase doc, never load all 4. Pass arguments through: Forward remaining args unchanged to sub-command 5. User confirmation: Each sub-command handles its own plan presentation and y/n confirmation
Error Handling
| Error | Resolution |
|---|---|
| Unknown sub-command | Fall through to interactive flow |
| Phase doc not found | Abort with file path error |
| Missing path for update-single | Prompt via Q3 |
| Sub-command execution fails | Follow phase doc's own error handling |
Phase 1: Full CLAUDE.md Update (update-full)
全项目 CLAUDE.md 更新,使用 3 层架构 (Layer 3→1),批量 agent 执行,自动 tool fallback。
Objective
- 发现所有项目模块并按深度分层
- 按 Layer 3→2→1 顺序 bottom-up 更新所有模块的 CLAUDE.md
- <20 模块直接并行,≥20 模块使用 agent 批处理 (4 modules/agent)
- 自动 tool fallback (gemini→qwen→codex)
Parameters
--tool <gemini|qwen|codex>: Primary tool (default: gemini)--path <directory>: Target specific directory (default: entire project)
Execution
Execution Flow: Discovery → Plan Presentation → Execution → Safety Verification
3-Layer Architecture & Auto-Strategy Selection
Layer Definition & Strategy Assignment
| Layer | Depth | Strategy | Purpose | Context Pattern |
|---|---|---|---|---|
| Layer 3 (Deepest) | ≥3 | multi-layer | Handle unstructured files, generate docs for all subdirectories | @**/* (all files) |
| Layer 2 (Middle) | 1-2 | single-layer | Aggregate from children + current code | @*/CLAUDE.md @*.{ts,tsx,js,...} |
| Layer 1 (Top) | 0 | single-layer | Aggregate from children + current code | @*/CLAUDE.md @*.{ts,tsx,js,...} |
Update Direction: Layer 3 → Layer 2 → Layer 1 (bottom-up dependency flow)
Strategy Auto-Selection: Strategies are automatically determined by directory depth - no user configuration needed.
Multi-Layer Strategy (Layer 3 Only)
- Use Case: Deepest directories with unstructured file layouts
- Behavior: Generates CLAUDE.md for current directory AND each subdirectory containing files
- Context: All files in current directory tree (
@**/*)
Single-Layer Strategy (Layers 1-2)
- Use Case: Upper layers that aggregate from existing documentation
- Behavior: Generates CLAUDE.md only for current directory
- Context: Direct children CLAUDE.md files + current directory code files
Example Flow
src/auth/handlers/ (depth 3) → MULTI-LAYER STRATEGY
CONTEXT: @**/* (all files in handlers/ and subdirs)
GENERATES: ./CLAUDE.md + CLAUDE.md in each subdir with files
↓
src/auth/ (depth 2) → SINGLE-LAYER STRATEGY
CONTEXT: @*/CLAUDE.md @*.ts (handlers/CLAUDE.md + current code)
GENERATES: ./CLAUDE.md only
↓
src/ (depth 1) → SINGLE-LAYER STRATEGY
CONTEXT: @*/CLAUDE.md (auth/CLAUDE.md, utils/CLAUDE.md)
GENERATES: ./CLAUDE.md only
↓
./ (depth 0) → SINGLE-LAYER STRATEGY
CONTEXT: @*/CLAUDE.md (src/CLAUDE.md, tests/CLAUDE.md)
GENERATES: ./CLAUDE.md onlyCore Execution Rules
1. Analyze First: Git cache + module discovery before updates 2. Wait for Approval: Present plan, no execution without user confirmation 3. Execution Strategy:
- <20 modules: Direct parallel execution (max 4 concurrent per layer)
- ≥20 modules: Agent batch processing (4 modules/agent, 73% overhead reduction)
4. Tool Fallback: Auto-retry with fallback tools on failure 5. Layer Sequential: Process layers 3→2→1 (bottom-up), parallel batches within layer 6. Safety Check: Verify only CLAUDE.md files modified 7. Layer-based Grouping: Group modules by LAYER (not depth) for execution
Tool Fallback Hierarchy
--tool gemini → [gemini, qwen, codex] // default
--tool qwen → [qwen, gemini, codex]
--tool codex → [codex, gemini, qwen]Trigger: Non-zero exit code from update script
| Tool | Best For | Fallback To |
|---|---|---|
| gemini | Documentation, patterns | qwen → codex |
| qwen | Architecture, system design | gemini → codex |
| codex | Implementation, code quality | gemini → qwen |
Step 1.1: Discovery & Analysis
// Cache git changes
Bash({command: "git add -A 2>/dev/null || true", run_in_background: false});
// Get module structure
Bash({command: "ccw tool exec get_modules_by_depth '{\"format\":\"list\"}'", run_in_background: false});
// OR with --path
Bash({command: "cd <target-path> && ccw tool exec get_modules_by_depth '{\"format\":\"list\"}'", run_in_background: false});Parse output depth:N|path:<PATH>|... to extract module paths and count.
Smart filter: Auto-detect and skip tests/build/config/docs based on project tech stack.
Step 1.2: Plan Presentation
For <20 modules:
Update Plan:
Tool: gemini (fallback: qwen → codex)
Total: 7 modules
Execution: Direct parallel (< 20 modules threshold)
Will update:
- ./core/interfaces (12 files) - depth 2 [Layer 2] - single-layer strategy
- ./core (22 files) - depth 1 [Layer 2] - single-layer strategy
- ./models (9 files) - depth 1 [Layer 2] - single-layer strategy
- ./utils (12 files) - depth 1 [Layer 2] - single-layer strategy
- . (5 files) - depth 0 [Layer 1] - single-layer strategy
Context Strategy (Auto-Selected):
- Layer 2 (depth 1-2): @*/CLAUDE.md + current code files
- Layer 1 (depth 0): @*/CLAUDE.md + current code files
Auto-skipped: ./tests, __pycache__, setup.py (15 paths)
Execution order: Layer 2 → Layer 1
Estimated time: ~5-10 minutes
Confirm execution? (y/n)For ≥20 modules:
Update Plan:
Tool: gemini (fallback: qwen → codex)
Total: 31 modules
Execution: Agent batch processing (4 modules/agent)
Will update:
- ./src/features/auth (12 files) - depth 3 [Layer 3] - multi-layer strategy
- ./.claude/commands/cli (6 files) - depth 3 [Layer 3] - multi-layer strategy
- ./src/utils (8 files) - depth 2 [Layer 2] - single-layer strategy
...
Context Strategy (Auto-Selected):
- Layer 3 (depth ≥3): @**/* (all files)
- Layer 2 (depth 1-2): @*/CLAUDE.md + current code files
- Layer 1 (depth 0): @*/CLAUDE.md + current code files
Auto-skipped: ./tests, __pycache__, setup.py (15 paths)
Execution order: Layer 2 → Layer 1
Estimated time: ~5-10 minutes
Agent allocation (by LAYER):
- Layer 3 (14 modules, depth ≥3): 4 agents [4, 4, 4, 2]
- Layer 2 (15 modules, depth 1-2): 4 agents [4, 4, 4, 3]
- Layer 1 (2 modules, depth 0): 1 agent [2]
Estimated time: ~15-25 minutes
Confirm execution? (y/n)Step 1.3A: Direct Execution (<20 modules)
Strategy: Parallel execution within layer (max 4 concurrent), no agent overhead.
CRITICAL: All Bash commands use run_in_background: false for synchronous execution.
for (let layer of [3, 2, 1]) {
if (modules_by_layer[layer].length === 0) continue;
let batches = batch_modules(modules_by_layer[layer], 4);
for (let batch of batches) {
let parallel_tasks = batch.map(module => {
return async () => {
let strategy = module.depth >= 3 ? "multi-layer" : "single-layer";
for (let tool of tool_order) {
Bash({
command: `cd ${module.path} && ccw tool exec update_module_claude '{"strategy":"${strategy}","path":".","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ ${module.path} (Layer ${layer}) updated with ${tool}`);
return true;
}
}
report(`❌ FAILED: ${module.path} (Layer ${layer}) failed all tools`);
return false;
};
});
await Promise.all(parallel_tasks.map(task => task()));
}
}Step 1.3B: Agent Batch Execution (≥20 modules)
Strategy: Batch modules into groups of 4, spawn memory-bridge agents per batch.
// Group modules by LAYER and batch within each layer
let modules_by_layer = group_by_layer(module_list);
let tool_order = construct_tool_order(primary_tool);
for (let layer of [3, 2, 1]) {
if (modules_by_layer[layer].length === 0) continue;
let batches = batch_modules(modules_by_layer[layer], 4);
let worker_tasks = [];
for (let batch of batches) {
worker_tasks.push(
Task(
subagent_type="memory-bridge",
description=`Update ${batch.length} modules in Layer ${layer}`,
prompt=generate_batch_worker_prompt(batch, tool_order, layer)
)
);
}
await parallel_execute(worker_tasks);
}Batch Worker Prompt Template:
PURPOSE: Update CLAUDE.md for assigned modules with tool fallback
TASK: Update documentation for assigned modules using specified strategies.
MODULES:
{{module_path_1}} (strategy: {{strategy_1}})
{{module_path_2}} (strategy: {{strategy_2}})
...
TOOLS (try in order): {{tool_1}}, {{tool_2}}, {{tool_3}}
EXECUTION SCRIPT: ccw tool exec update_module_claude
- Accepts strategy parameter: multi-layer | single-layer
- Tool execution via direct CLI commands (gemini/qwen/codex)
EXECUTION FLOW (for each module):
1. Tool fallback loop (exit on first success):
for tool in {{tool_1}} {{tool_2}} {{tool_3}}; do
Bash({
command: `cd "{{module_path}}" && ccw tool exec update_module_claude '{"strategy":"{{strategy}}","path":".","tool":"${tool}"}'`,
run_in_background: false
})
exit_code=$?
if [ $exit_code -eq 0 ]; then
report "✅ {{module_path}} updated with $tool"
break
else
report "⚠️ {{module_path}} failed with $tool, trying next..."
continue
fi
done
2. Handle complete failure (all tools failed):
if [ $exit_code -ne 0 ]; then
report "❌ FAILED: {{module_path}} - all tools exhausted"
# Continue to next module (do not abort batch)
fi
FAILURE HANDLING:
- Module-level isolation: One module's failure does not affect others
- Exit code detection: Non-zero exit code triggers next tool
- Exhaustion reporting: Log modules where all tools failed
- Batch continuation: Always process remaining modules
REPORTING FORMAT:
Per-module status:
✅ path/to/module updated with {tool}
⚠️ path/to/module failed with {tool}, trying next...
❌ FAILED: path/to/module - all tools exhaustedStep 1.4: Safety Verification
// Check only CLAUDE.md files modified
Bash({command: 'git diff --cached --name-only | grep -v "CLAUDE.md" || echo "Only CLAUDE.md files modified"', run_in_background: false});
// Display status
Bash({command: "git status --short", run_in_background: false});Result Summary:
Update Summary:
Total: 31 | Success: 29 | Failed: 2
Tool usage: gemini: 25, qwen: 4, codex: 0
Failed: path1, path2Error Handling
Batch Worker: Tool fallback per module, batch isolation, clear status reporting Coordinator: Invalid path abort, user decline handling, safety check with auto-revert Fallback Triggers: Non-zero exit code, script timeout, unexpected output
Output
- Files: Updated CLAUDE.md files across all project modules
- Report: Summary with success/failure counts and tool usage statistics
Next Phase
Return to manage.md router.
Phase 2: Related CLAUDE.md Update (update-related)
仅更新 git 变更模块的 CLAUDE.md,使用深度优先执行和自动 tool fallback。
Objective
- 检测 git 变更,识别受影响模块
- 按深度 N→0 顺序更新变更模块及其父级上下文
- <15 模块直接并行,≥15 模块使用 agent 批处理
- 自动 tool fallback (gemini→qwen→codex)
Parameters
--tool <gemini|qwen|codex>: Primary tool (default: gemini)
Execution
Execution Flow: Change Detection → Plan Presentation → Batched Execution → Safety Verification
Core Rules
1. Detect Changes First: Use git diff to identify affected modules 2. Wait for Approval: Present plan, no execution without user confirmation 3. Execution Strategy:
- <15 modules: Direct parallel execution (max 4 concurrent per depth, no agent overhead)
- ≥15 modules: Agent batch processing (4 modules/agent, 73% overhead reduction)
4. Tool Fallback: Auto-retry with fallback tools on failure 5. Depth Sequential: Process depths N→0, parallel batches within depth (both modes) 6. Related Mode: Update only changed modules and their parent contexts
Tool Fallback Hierarchy
--tool gemini → [gemini, qwen, codex] // default
--tool qwen → [qwen, gemini, codex]
--tool codex → [codex, gemini, qwen]Trigger: Non-zero exit code from update script
Step 2.1: Change Detection & Analysis
// Detect changed modules
Bash({command: "ccw tool exec detect_changed_modules '{\"format\":\"list\"}'", run_in_background: false});
// Cache git changes
Bash({command: "git add -A 2>/dev/null || true", run_in_background: false});Parse output depth:N|path:<PATH>|change:<TYPE> to extract affected modules.
Smart filter: Auto-detect and skip tests/build/config/docs based on project tech stack (Node.js/Python/Go/Rust/etc).
Fallback: If no changes detected, use recent modules (first 10 by depth).
Step 2.2: Plan Presentation
Present filtered plan:
Related Update Plan:
Tool: gemini (fallback: qwen → codex)
Changed: 4 modules | Batching: 4 modules/agent
Will update:
- ./src/api/auth (5 files) [new module]
- ./src/api (12 files) [parent of changed auth/]
- ./src (8 files) [parent context]
- . (14 files) [root level]
Auto-skipped (12 paths):
- Tests: ./src/api/auth.test.ts (8 paths)
- Config: tsconfig.json (3 paths)
- Other: node_modules (1 path)
Agent allocation:
- Depth 3 (1 module): 1 agent [1]
- Depth 2 (1 module): 1 agent [1]
- Depth 1 (1 module): 1 agent [1]
- Depth 0 (1 module): 1 agent [1]
Confirm execution? (y/n)Decision logic:
- User confirms "y": Proceed with execution
- User declines "n": Abort, no changes
- <15 modules: Direct execution
- ≥15 modules: Agent batch execution
Step 2.3A: Direct Execution (<15 modules)
Strategy: Parallel execution within depth (max 4 concurrent), no agent overhead.
CRITICAL: All Bash commands use run_in_background: false for synchronous execution.
for (let depth of sorted_depths.reverse()) { // N → 0
let batches = batch_modules(modules_by_depth[depth], 4);
for (let batch of batches) {
let parallel_tasks = batch.map(module => {
return async () => {
for (let tool of tool_order) {
Bash({
command: `cd ${module.path} && ccw tool exec update_module_claude '{"strategy":"single-layer","path":".","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ ${module.path} updated with ${tool}`);
return true;
}
}
report(`❌ FAILED: ${module.path} failed all tools`);
return false;
};
});
await Promise.all(parallel_tasks.map(task => task()));
}
}Step 2.3B: Agent Batch Execution (≥15 modules)
Batching Strategy
// Batch modules into groups of 4
function batch_modules(modules, batch_size = 4) {
let batches = [];
for (let i = 0; i < modules.length; i += batch_size) {
batches.push(modules.slice(i, i + batch_size));
}
return batches;
}
// Examples: 10→[4,4,2] | 8→[4,4] | 3→[3]Coordinator Orchestration
let modules_by_depth = group_by_depth(changed_modules);
let tool_order = construct_tool_order(primary_tool);
for (let depth of sorted_depths.reverse()) { // N → 0
let batches = batch_modules(modules_by_depth[depth], 4);
let worker_tasks = [];
for (let batch of batches) {
worker_tasks.push(
Task(
subagent_type="memory-bridge",
description=`Update ${batch.length} modules at depth ${depth}`,
prompt=generate_batch_worker_prompt(batch, tool_order, "related")
)
);
}
await parallel_execute(worker_tasks); // Batches run in parallel
}Batch Worker Prompt Template
PURPOSE: Update CLAUDE.md for assigned modules with tool fallback (related mode)
TASK:
Update documentation for the following modules based on recent changes. For each module, try tools in order until success.
MODULES:
{{module_path_1}}
{{module_path_2}}
{{module_path_3}}
{{module_path_4}}
TOOLS (try in order):
1. {{tool_1}}
2. {{tool_2}}
3. {{tool_3}}
EXECUTION:
For each module above:
1. Try tool 1:
Bash({
command: `cd "{{module_path}}" && ccw tool exec update_module_claude '{"strategy":"single-layer","path":".","tool":"{{tool_1}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} updated with {{tool_1}}", proceed to next module
→ Failure: Try tool 2
2. Try tool 2:
Bash({
command: `cd "{{module_path}}" && ccw tool exec update_module_claude '{"strategy":"single-layer","path":".","tool":"{{tool_2}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} updated with {{tool_2}}", proceed to next module
→ Failure: Try tool 3
3. Try tool 3:
Bash({
command: `cd "{{module_path}}" && ccw tool exec update_module_claude '{"strategy":"single-layer","path":".","tool":"{{tool_3}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} updated with {{tool_3}}", proceed to next module
→ Failure: Report "❌ FAILED: {{module_path}} failed all tools", proceed to next module
REPORTING:
Report final summary with:
- Total processed: X modules
- Successful: Y modules
- Failed: Z modules
- Tool usage: {{tool_1}}:X, {{tool_2}}:Y, {{tool_3}}:ZStep 2.4: Safety Verification
// Check only CLAUDE.md modified
Bash({command: 'git diff --cached --name-only | grep -v "CLAUDE.md" || echo "Only CLAUDE.md files modified"', run_in_background: false});
// Display statistics
Bash({command: "git diff --stat", run_in_background: false});Aggregate results:
Update Summary:
Total: 4 | Success: 4 | Failed: 0
Tool usage:
- gemini: 4 modules
- qwen: 0 modules (fallback)
- codex: 0 modules
Changes:
src/api/auth/CLAUDE.md | 45 +++++++++++++++++++++
src/api/CLAUDE.md | 23 +++++++++--
src/CLAUDE.md | 12 ++++--
CLAUDE.md | 8 ++--
4 files changed, 82 insertions(+), 6 deletions(-)Error Handling
Batch Worker:
- Tool fallback per module (auto-retry)
- Batch isolation (failures don't propagate)
- Clear per-module status reporting
Coordinator:
- No changes: Use fallback (recent 10 modules)
- User decline: No execution
- Safety check fail: Auto-revert staging
- Partial failures: Continue execution, report failed modules
Fallback Triggers:
- Non-zero exit code
- Script timeout
- Unexpected output
Output
- Files: Updated CLAUDE.md files for changed modules and their parents
- Report: Summary with success/failure counts, tool usage, and git diff statistics
Next Phase
Return to manage.md router.
Phase 3: Single Module CLAUDE.md Update (update-single)
使用 Explore agent 深度分析后,为单个目标模块生成手册式 (说明书) CLAUDE.md。
Objective
- 验证目标路径并扫描结构
- 使用 Explore agent 进行 7 维度深度探索
- 交互确认后通过 CLI tool 生成手册式 CLAUDE.md
- Tool fallback (gemini→qwen→codex)
Parameters
<path>: Target directory path (required)--tool <gemini|qwen|codex>: Primary CLI tool (default: gemini)
Execution
Step 3.1: Target Validation & Scan
├─ Parse arguments (path, --tool)
├─ Validate target directory exists
└─ Quick structure scan (file count, types, depth)
Step 3.2: Deep Exploration (Explore Agent)
├─ Launch Explore agent with "very thorough" level
├─ Analyze purpose, structure, patterns, exports, dependencies
└─ Build comprehensive module understanding
Step 3.3: Confirmation
├─ Display exploration summary (key findings)
└─ AskUserQuestion: Generate / Cancel
Step 3.4: Generate CLAUDE.md (CLI Tool)
├─ Construct manual-style prompt from exploration results
├─ Execute ccw cli with --mode write
├─ Tool fallback on failure
└─ Write to <path>/CLAUDE.md
Step 3.5: Verification
└─ Display generated CLAUDE.md preview + statsStep 3.1: Target Validation & Scan
// Parse arguments
const args = $ARGUMENTS.trim()
const parts = args.split(/\s+/)
const toolFlagIdx = parts.indexOf('--tool')
const primaryTool = toolFlagIdx !== -1 ? parts[toolFlagIdx + 1] : 'gemini'
const targetPath = parts.find(p => !p.startsWith('--') && p !== primaryTool)
if (!targetPath) {
console.log('ERROR: <path> is required. Usage: /memory:manage update-single <path> [--tool gemini|qwen|codex]')
return
}
// Validate path exists
Bash({ command: `test -d "${targetPath}" && echo "EXISTS" || echo "NOT_FOUND"`, run_in_background: false })
// → NOT_FOUND: abort with error
// Quick structure scan
Bash({ command: `find "${targetPath}" -maxdepth 3 -type f -not -path "*/node_modules/*" -not -path "*/.git/*" | wc -l`, run_in_background: false })
Bash({ command: `ls "${targetPath}"`, run_in_background: false })
// Check existing CLAUDE.md
const hasExisting = file_exists(`${targetPath}/CLAUDE.md`)
console.log(`
## Target: ${targetPath}
Files: ${fileCount}
Existing CLAUDE.md: ${hasExisting ? 'Yes (will be overwritten)' : 'No (new)'}
Tool: ${primaryTool}
Launching deep exploration...
`)Step 3.2: Deep Exploration (Explore Agent)
CRITICAL: Use run_in_background: false — exploration results are REQUIRED before generation.
const explorationResult = Task(
subagent_type="Explore",
run_in_background=false,
description=`Explore: ${targetPath}`,
prompt=`
Thoroughly explore the module at "${targetPath}" with "very thorough" level. I need comprehensive understanding for generating a manual-style CLAUDE.md (说明书).
## Exploration Focus
Analyze from these 7 dimensions:
1. **Purpose & Responsibility**
- What problem does this module solve?
- What is its core responsibility in the larger system?
- One-sentence summary a developer would use to describe it
2. **Directory Structure & Key Files**
- Map directory layout and file organization
- Identify entry points, core logic files, utilities, types
- Note any naming conventions or organizational patterns
3. **Code Patterns & Conventions**
- Common patterns used (factory, observer, middleware, hooks, etc.)
- Import/export conventions
- Error handling patterns
- State management approach (if applicable)
4. **Public API / Exports**
- What does this module expose to the outside?
- Key functions, classes, components, types exported
- How do consumers typically import from this module?
5. **Dependencies & Integration**
- External packages this module depends on
- Internal modules it imports from
- Modules that depend on this one (reverse dependencies)
- Data flow: how data enters and exits this module
6. **Constraints & Gotchas**
- Non-obvious rules a developer must follow
- Performance considerations
- Security-sensitive areas
- Common pitfalls or mistakes
7. **Development Workflow**
- How to add new functionality to this module
- Testing approach used
- Build/compilation specifics (if any)
## Output Format
Return a structured summary covering all 7 dimensions above. Include specific file:line references where relevant. Focus on **actionable knowledge** — what a developer needs to know to work with this module effectively.
`
)Step 3.3: Confirmation
console.log(`
## Exploration Summary
${explorationResult}
---
**Will generate**: ${targetPath}/CLAUDE.md
**Style**: Manual/handbook (说明书)
**Tool**: ${primaryTool}
`)
AskUserQuestion({
questions: [{
question: `Generate manual-style CLAUDE.md for "${targetPath}"?`,
header: "Confirm",
multiSelect: false,
options: [
{ label: "Generate", description: "Write CLAUDE.md based on exploration" },
{ label: "Cancel", description: "Abort without changes" }
]
}]
})
// Cancel → abortStep 3.4: Generate CLAUDE.md (CLI Tool)
Tool fallback hierarchy:
const toolOrder = {
'gemini': ['gemini', 'qwen', 'codex'],
'qwen': ['qwen', 'gemini', 'codex'],
'codex': ['codex', 'gemini', 'qwen']
}[primaryTool]Generation via ccw cli:
for (let tool of toolOrder) {
Bash({
command: `ccw cli -p "PURPOSE: Generate a manual-style CLAUDE.md (说明书) for the module at current directory.
This CLAUDE.md should read like a developer handbook — practical, actionable, concise.
## Exploration Context (use as primary source)
${explorationResult}
## CLAUDE.md Structure Requirements
Generate CLAUDE.md following this exact structure:
### 1. Title & Summary
\`# <Module Name>\`
> One-line description of purpose
### 2. Responsibilities
- Bullet list of what this module owns
- Keep to 3-7 items, each one sentence
### 3. Structure
\`\`\`
directory-tree/
├── key-files-only
└── with-brief-annotations
\`\`\`
### 4. Key Patterns
- Code conventions specific to THIS module
- Import patterns, naming rules, style decisions
- NOT generic best practices — only module-specific patterns
### 5. Usage
- How other modules use this one
- Common import/usage examples (real code, not pseudo-code)
### 6. Integration Points
- **Depends on**: modules/packages this uses (with purpose)
- **Used by**: modules that import from here
### 7. Constraints & Gotchas
- Non-obvious rules developers MUST follow
- Common mistakes to avoid
- Performance or security notes
## Style Rules
- Be CONCISE: each section 3-10 lines max
- Be PRACTICAL: actionable knowledge only, no boilerplate
- Be SPECIFIC: reference actual files and patterns, not generic advice
- No API reference listings — this is a handbook, not a reference doc
- Total length: 50-150 lines of markdown
- Language: Match the project's primary language (check existing CLAUDE.md files)
MODE: write
CONTEXT: @**/*
EXPECTED: Single CLAUDE.md file at ./CLAUDE.md following the structure above
CONSTRAINTS: Only write CLAUDE.md, no other files" --tool ${tool} --mode write --cd "${targetPath}"`,
run_in_background: false
})
if (exit_code === 0) {
console.log(`✅ ${targetPath}/CLAUDE.md generated with ${tool}`)
break
}
console.log(`⚠️ ${tool} failed, trying next...`)
}Step 3.5: Verification
// Check file was created/updated
Bash({ command: `test -f "${targetPath}/CLAUDE.md" && echo "EXISTS" || echo "MISSING"`, run_in_background: false })
// Show stats
Bash({ command: `wc -l "${targetPath}/CLAUDE.md"`, run_in_background: false })
// Preview first 30 lines
Read(`${targetPath}/CLAUDE.md`, { limit: 30 })
console.log(`
## Result
✅ Generated: ${targetPath}/CLAUDE.md
Lines: ${lineCount}
Style: Manual/handbook format
Tool: ${usedTool}
`)CLAUDE.md Output Style Guide
The generated CLAUDE.md is a 说明书 (handbook), NOT a reference doc:
| Aspect | Handbook Style | Reference Doc Style |
|---|---|---|
| Purpose | "This module handles user auth" | "Authentication module" |
| Content | How to work with it | What every function does |
| Patterns | "Always use createAuthMiddleware()" | "List of all exports" |
| Constraints | "Never store tokens in localStorage" | "Token storage API" |
| Length | 50-150 lines | 300+ lines |
| Audience | Developer joining the team | API consumer |
Error Handling
| Error | Resolution |
|---|---|
| Path not found | Abort with clear error message |
| Explore agent failure | Fallback to basic ls + head file scan, continue |
| All CLI tools fail | Report failure with last error, suggest --tool override |
| Empty directory | Abort — nothing to document |
| Existing CLAUDE.md | Overwrite entirely (full regeneration) |
Output
- File:
<path>/CLAUDE.md— Manual-style module handbook - Preview: First 30 lines displayed after generation
Next Phase
Return to manage.md router.
Phase 4: Full Documentation Generation (docs-full)
全项目 API.md + README.md 文档生成,使用 CLI 执行、3 层架构和自动 tool fallback,输出到 .workflow/docs/。
Objective
- 发现所有项目模块并按深度分层
- 按 Layer 3→2→1 顺序生成 API.md + README.md 文档
- <20 模块直接并行,≥20 模块使用 agent 批处理
- 生成项目级文档 (README.md, ARCHITECTURE.md, EXAMPLES.md)
- 自动 tool fallback (gemini→qwen→codex)
Parameters
path: Target directory (default: current directory)--tool <gemini|qwen|codex>: Primary tool (default: gemini)
Execution
Execution Flow: Discovery → Plan Presentation → Execution → Project-Level Docs → Verification
3-Layer Architecture & Auto-Strategy Selection
Layer Definition & Strategy Assignment
| Layer | Depth | Strategy | Purpose | Context Pattern |
|---|---|---|---|---|
| Layer 3 (Deepest) | ≥3 | full | Generate docs for all subdirectories with code | @**/* (all files) |
| Layer 2 (Middle) | 1-2 | single | Current dir + child docs | @*/API.md @*/README.md @*.{ts,tsx,js,...} |
| Layer 1 (Top) | 0 | single | Current dir + child docs | @*/API.md @*/README.md @*.{ts,tsx,js,...} |
Generation Direction: Layer 3 → Layer 2 → Layer 1 (bottom-up dependency flow)
Full Strategy (Layer 3 Only)
- Use Case: Deepest directories with comprehensive file coverage
- Behavior: Generates API.md + README.md for current directory AND subdirectories containing code
- Context: All files in current directory tree (
@**/*) - Output:
.workflow/docs/{project_name}/{path}/API.md+README.md
Single Strategy (Layers 1-2)
- Use Case: Upper layers that aggregate from existing documentation
- Behavior: Generates API.md + README.md only in current directory
- Context: Direct children docs + current directory code files
- Output:
.workflow/docs/{project_name}/{path}/API.md+README.md
Example Flow
src/auth/handlers/ (depth 3) → FULL STRATEGY
CONTEXT: @**/* (all files in handlers/ and subdirs)
GENERATES: .workflow/docs/project/src/auth/handlers/{API.md,README.md} + subdirs
↓
src/auth/ (depth 2) → SINGLE STRATEGY
CONTEXT: @*/API.md @*/README.md @*.ts (handlers docs + current code)
GENERATES: .workflow/docs/project/src/auth/{API.md,README.md} only
↓
src/ (depth 1) → SINGLE STRATEGY
CONTEXT: @*/API.md @*/README.md (auth docs, utils docs)
GENERATES: .workflow/docs/project/src/{API.md,README.md} only
↓
./ (depth 0) → SINGLE STRATEGY
CONTEXT: @*/API.md @*/README.md (src docs, tests docs)
GENERATES: .workflow/docs/project/{API.md,README.md} onlyCore Execution Rules
1. Analyze First: Module discovery + folder classification before generation 2. Wait for Approval: Present plan, no execution without user confirmation 3. Execution Strategy:
- <20 modules: Direct parallel execution (max 4 concurrent per layer)
- ≥20 modules: Agent batch processing (4 modules/agent, 73% overhead reduction)
4. Tool Fallback: Auto-retry with fallback tools on failure 5. Layer Sequential: Process layers 3→2→1 (bottom-up), parallel batches within layer 6. Safety Check: Verify only docs files modified in .workflow/docs/ 7. Layer-based Grouping: Group modules by LAYER (not depth) for execution
Tool Fallback Hierarchy
--tool gemini → [gemini, qwen, codex] // default
--tool qwen → [qwen, gemini, codex]
--tool codex → [codex, gemini, qwen]Step 4.1: Discovery & Analysis
// Get project metadata
Bash({command: "pwd && basename \"$(pwd)\" && git rev-parse --show-toplevel 2>/dev/null || pwd", run_in_background: false});
// Get module structure with classification
Bash({command: "ccw tool exec get_modules_by_depth '{\"format\":\"list\"}' | ccw tool exec classify_folders '{}'", run_in_background: false});
// OR with path parameter
Bash({command: "cd <target-path> && ccw tool exec get_modules_by_depth '{\"format\":\"list\"}' | ccw tool exec classify_folders '{}'", run_in_background: false});Parse output depth:N|path:<PATH>|type:<code|navigation>|... to extract module paths, types, and count.
Smart filter: Auto-detect and skip tests/build/config/vendor based on project tech stack.
Step 4.2: Plan Presentation
For <20 modules:
Documentation Generation Plan:
Tool: gemini (fallback: qwen → codex)
Total: 7 modules
Execution: Direct parallel (< 20 modules threshold)
Project: myproject
Output: .workflow/docs/myproject/
Will generate docs for:
- ./core/interfaces (12 files, type: code) - depth 2 [Layer 2] - single strategy
- ./core (22 files, type: code) - depth 1 [Layer 2] - single strategy
- ./models (9 files, type: code) - depth 1 [Layer 2] - single strategy
- ./utils (12 files, type: navigation) - depth 1 [Layer 2] - single strategy
- . (5 files, type: code) - depth 0 [Layer 1] - single strategy
Documentation Strategy (Auto-Selected):
- Layer 2 (depth 1-2): API.md + README.md (current dir only, reference child docs)
- Layer 1 (depth 0): API.md + README.md (current dir only, reference child docs)
Output Structure:
- Code folders: API.md + README.md
- Navigation folders: README.md only
Auto-skipped: ./tests, __pycache__, node_modules (15 paths)
Execution order: Layer 2 → Layer 1
Confirm execution? (y/n)For ≥20 modules:
Documentation Generation Plan:
Tool: gemini (fallback: qwen → codex)
Total: 31 modules
Execution: Agent batch processing (4 modules/agent)
Project: myproject
Output: .workflow/docs/myproject/
Will generate docs for:
- ./src/features/auth (12 files, type: code) - depth 3 [Layer 3] - full strategy
- ./.claude/commands/cli (6 files, type: code) - depth 3 [Layer 3] - full strategy
- ./src/utils (8 files, type: code) - depth 2 [Layer 2] - single strategy
...
Documentation Strategy (Auto-Selected):
- Layer 3 (depth ≥3): API.md + README.md (all subdirs with code)
- Layer 2 (depth 1-2): API.md + README.md (current dir only)
- Layer 1 (depth 0): API.md + README.md (current dir only)
Output Structure:
- Code folders: API.md + README.md
- Navigation folders: README.md only
Auto-skipped: ./tests, __pycache__, node_modules (15 paths)
Execution order: Layer 3 → Layer 2 → Layer 1
Agent allocation (by LAYER):
- Layer 3 (14 modules, depth ≥3): 4 agents [4, 4, 4, 2]
- Layer 2 (15 modules, depth 1-2): 4 agents [4, 4, 4, 3]
- Layer 1 (2 modules, depth 0): 1 agent [2]
Confirm execution? (y/n)Step 4.3A: Direct Execution (<20 modules)
Strategy: Parallel execution within layer (max 4 concurrent), no agent overhead.
CRITICAL: All Bash commands use run_in_background: false for synchronous execution.
let project_name = detect_project_name();
for (let layer of [3, 2, 1]) {
if (modules_by_layer[layer].length === 0) continue;
let batches = batch_modules(modules_by_layer[layer], 4);
for (let batch of batches) {
let parallel_tasks = batch.map(module => {
return async () => {
let strategy = module.depth >= 3 ? "full" : "single";
for (let tool of tool_order) {
Bash({
command: `cd ${module.path} && ccw tool exec generate_module_docs '{"strategy":"${strategy}","sourcePath":".","projectName":"${project_name}","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ ${module.path} (Layer ${layer}) docs generated with ${tool}`);
return true;
}
}
report(`❌ FAILED: ${module.path} (Layer ${layer}) failed all tools`);
return false;
};
});
await Promise.all(parallel_tasks.map(task => task()));
}
}Step 4.3B: Agent Batch Execution (≥20 modules)
Strategy: Batch modules into groups of 4, spawn memory-bridge agents per batch.
// Group modules by LAYER and batch within each layer
let modules_by_layer = group_by_layer(module_list);
let tool_order = construct_tool_order(primary_tool);
let project_name = detect_project_name();
for (let layer of [3, 2, 1]) {
if (modules_by_layer[layer].length === 0) continue;
let batches = batch_modules(modules_by_layer[layer], 4);
let worker_tasks = [];
for (let batch of batches) {
worker_tasks.push(
Task(
subagent_type="memory-bridge",
description=`Generate docs for ${batch.length} modules in Layer ${layer}`,
prompt=generate_batch_worker_prompt(batch, tool_order, layer, project_name)
)
);
}
await parallel_execute(worker_tasks);
}Batch Worker Prompt Template:
PURPOSE: Generate documentation for assigned modules with tool fallback
TASK: Generate API.md + README.md for assigned modules using specified strategies.
PROJECT: {{project_name}}
OUTPUT: .workflow/docs/{{project_name}}/
MODULES:
{{module_path_1}} (strategy: {{strategy_1}}, type: {{folder_type_1}})
{{module_path_2}} (strategy: {{strategy_2}}, type: {{folder_type_2}})
...
TOOLS (try in order): {{tool_1}}, {{tool_2}}, {{tool_3}}
EXECUTION SCRIPT: ccw tool exec generate_module_docs
- Accepts strategy parameter: full | single
- Accepts folder type detection: code | navigation
- Tool execution via direct CLI commands (gemini/qwen/codex)
- Output path: .workflow/docs/{{project_name}}/{module_path}/
EXECUTION FLOW (for each module):
1. Tool fallback loop (exit on first success):
for tool in {{tool_1}} {{tool_2}} {{tool_3}}; do
Bash({
command: `cd "{{module_path}}" && ccw tool exec generate_module_docs '{"strategy":"{{strategy}}","sourcePath":".","projectName":"{{project_name}}","tool":"${tool}"}'`,
run_in_background: false
})
exit_code=$?
if [ $exit_code -eq 0 ]; then
report "✅ {{module_path}} docs generated with $tool"
break
else
report "⚠️ {{module_path}} failed with $tool, trying next..."
continue
fi
done
2. Handle complete failure (all tools failed):
if [ $exit_code -ne 0 ]; then
report "❌ FAILED: {{module_path}} - all tools exhausted"
fi
FOLDER TYPE HANDLING:
- code: Generate API.md + README.md
- navigation: Generate README.md only
FAILURE HANDLING:
- Module-level isolation: One module's failure does not affect others
- Exit code detection: Non-zero exit code triggers next tool
- Exhaustion reporting: Log modules where all tools failed
- Batch continuation: Always process remaining modules
REPORTING FORMAT:
Per-module status:
✅ path/to/module docs generated with {tool}
⚠️ path/to/module failed with {tool}, trying next...
❌ FAILED: path/to/module - all tools exhaustedStep 4.4: Project-Level Documentation
After all module documentation is generated, create project-level documentation files.
let project_name = detect_project_name();
let project_root = get_project_root();
// Step 1: Generate Project README
report("Generating project README.md...");
for (let tool of tool_order) {
Bash({
command: `cd ${project_root} && ccw tool exec generate_module_docs '{"strategy":"project-readme","sourcePath":".","projectName":"${project_name}","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ Project README generated with ${tool}`);
break;
}
}
// Step 2: Generate Architecture & Examples
report("Generating ARCHITECTURE.md and EXAMPLES.md...");
for (let tool of tool_order) {
Bash({
command: `cd ${project_root} && ccw tool exec generate_module_docs '{"strategy":"project-architecture","sourcePath":".","projectName":"${project_name}","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ Architecture docs generated with ${tool}`);
break;
}
}
// Step 3: Generate HTTP API documentation (if API routes detected)
Bash({command: 'rg "router\\.|@Get|@Post" -g "*.{ts,js,py}" 2>/dev/null && echo "API_FOUND" || echo "NO_API"', run_in_background: false});
if (bash_result.stdout.includes("API_FOUND")) {
report("Generating HTTP API documentation...");
for (let tool of tool_order) {
Bash({
command: `cd ${project_root} && ccw tool exec generate_module_docs '{"strategy":"http-api","sourcePath":".","projectName":"${project_name}","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ HTTP API docs generated with ${tool}`);
break;
}
}
}Expected Output:
Project-Level Documentation:
✅ README.md (project root overview)
✅ ARCHITECTURE.md (system design)
✅ EXAMPLES.md (usage examples)
✅ api/README.md (HTTP API reference) [optional]Step 4.5: Verification
// Check documentation files created
Bash({command: 'find .workflow/docs -type f -name "*.md" 2>/dev/null | wc -l', run_in_background: false});
// Display structure
Bash({command: 'tree -L 3 .workflow/docs/', run_in_background: false});Result Summary:
Documentation Generation Summary:
Total: 31 | Success: 29 | Failed: 2
Tool usage: gemini: 25, qwen: 4, codex: 0
Failed: path1, path2
Generated documentation:
.workflow/docs/myproject/
├── src/
│ ├── auth/
│ │ ├── API.md
│ │ └── README.md
│ └── utils/
│ └── README.md
└── README.mdOutput Structure
.workflow/docs/{project_name}/
├── src/ # Mirrors source structure
│ ├── modules/
│ │ ├── README.md # Navigation
│ │ ├── auth/
│ │ │ ├── API.md # API signatures
│ │ │ ├── README.md # Module docs
│ │ │ └── middleware/
│ │ │ ├── API.md
│ │ │ └── README.md
│ │ └── api/
│ │ ├── API.md
│ │ └── README.md
│ └── utils/
│ └── README.md
├── lib/
│ └── core/
│ ├── API.md
│ └── README.md
├── README.md # Project root overview (auto-generated)
├── ARCHITECTURE.md # System design (auto-generated)
├── EXAMPLES.md # Usage examples (auto-generated)
└── api/ # Optional (auto-generated if HTTP API detected)
└── README.md # HTTP API referenceError Handling
Batch Worker: Tool fallback per module, batch isolation, clear status reporting Coordinator: Invalid path abort, user decline handling, verification with cleanup Fallback Triggers: Non-zero exit code, script timeout, unexpected output
Template Reference
Templates used from ~/.ccw/workflows/cli-templates/prompts/documentation/:
api.txt: Code API documentation (Part A: Code API, Part B: HTTP API)module-readme.txt: Module purpose, usage, dependenciesfolder-navigation.txt: Navigation README for folders with subdirectories
Output
- Directory:
.workflow/docs/{project_name}/— Complete documentation tree - Project-Level: README.md, ARCHITECTURE.md, EXAMPLES.md, api/README.md (optional)
- Report: Summary with success/failure counts and tool usage statistics
Next Phase
Return to manage.md router.
Phase 5: Related Documentation Generation (docs-related)
仅为 git 变更模块生成/更新 API.md + README.md 文档,使用增量策略和自动 tool fallback。
Objective
- 检测 git 变更,识别受影响模块
- 按深度 N→0 顺序为变更模块生成/更新文档
- <15 模块直接并行,≥15 模块使用 agent 批处理
- 使用 single 策略进行增量更新
- 自动 tool fallback (gemini→qwen→codex)
Parameters
--tool <gemini|qwen|codex>: Primary tool (default: gemini)
Execution
Execution Flow: Change Detection → Plan Presentation → Batched Execution → Verification
Core Rules
1. Detect Changes First: Use git diff to identify affected modules 2. Wait for Approval: Present plan, no execution without user confirmation 3. Execution Strategy:
- <15 modules: Direct parallel execution (max 4 concurrent per depth, no agent overhead)
- ≥15 modules: Agent batch processing (4 modules/agent, 73% overhead reduction)
4. Tool Fallback: Auto-retry with fallback tools on failure 5. Depth Sequential: Process depths N→0, parallel batches within depth (both modes) 6. Related Mode: Generate/update only changed modules and their parent contexts 7. Single Strategy: Always use single strategy (incremental update)
Tool Fallback Hierarchy
--tool gemini → [gemini, qwen, codex] // default
--tool qwen → [qwen, gemini, codex]
--tool codex → [codex, gemini, qwen]Step 5.1: Change Detection & Analysis
// Get project metadata
Bash({command: "pwd && basename \"$(pwd)\" && git rev-parse --show-toplevel 2>/dev/null || pwd", run_in_background: false});
// Detect changed modules
Bash({command: "ccw tool exec detect_changed_modules '{\"format\":\"list\"}'", run_in_background: false});
// Cache git changes
Bash({command: "git add -A 2>/dev/null || true", run_in_background: false});Parse output depth:N|path:<PATH>|change:<TYPE>|type:<code|navigation> to extract affected modules.
Smart filter: Auto-detect and skip tests/build/config/vendor based on project tech stack (Node.js/Python/Go/Rust/etc).
Fallback: If no changes detected, use recent modules (first 10 by depth).
Step 5.2: Plan Presentation
Present filtered plan:
Related Documentation Generation Plan:
Tool: gemini (fallback: qwen → codex)
Changed: 4 modules | Batching: 4 modules/agent
Project: myproject
Output: .workflow/docs/myproject/
Will generate/update docs for:
- ./src/api/auth (5 files, type: code) [new module]
- ./src/api (12 files, type: code) [parent of changed auth/]
- ./src (8 files, type: code) [parent context]
- . (14 files, type: code) [root level]
Documentation Strategy:
- Strategy: single (all modules - incremental update)
- Output: API.md + README.md (code folders), README.md only (navigation folders)
- Context: Current dir code + child docs
Auto-skipped (12 paths):
- Tests: ./src/api/auth.test.ts (8 paths)
- Config: tsconfig.json (3 paths)
- Other: node_modules (1 path)
Agent allocation:
- Depth 3 (1 module): 1 agent [1]
- Depth 2 (1 module): 1 agent [1]
- Depth 1 (1 module): 1 agent [1]
- Depth 0 (1 module): 1 agent [1]
Confirm execution? (y/n)Decision logic:
- User confirms "y": Proceed with execution
- User declines "n": Abort, no changes
- <15 modules: Direct execution
- ≥15 modules: Agent batch execution
Step 5.3A: Direct Execution (<15 modules)
Strategy: Parallel execution within depth (max 4 concurrent), no agent overhead.
CRITICAL: All Bash commands use run_in_background: false for synchronous execution.
let project_name = detect_project_name();
for (let depth of sorted_depths.reverse()) { // N → 0
let batches = batch_modules(modules_by_depth[depth], 4);
for (let batch of batches) {
let parallel_tasks = batch.map(module => {
return async () => {
for (let tool of tool_order) {
Bash({
command: `cd ${module.path} && ccw tool exec generate_module_docs '{"strategy":"single","sourcePath":".","projectName":"${project_name}","tool":"${tool}"}'`,
run_in_background: false
});
if (bash_result.exit_code === 0) {
report(`✅ ${module.path} docs generated with ${tool}`);
return true;
}
}
report(`❌ FAILED: ${module.path} failed all tools`);
return false;
};
});
await Promise.all(parallel_tasks.map(task => task()));
}
}Step 5.3B: Agent Batch Execution (≥15 modules)
Batching Strategy
// Batch modules into groups of 4
function batch_modules(modules, batch_size = 4) {
let batches = [];
for (let i = 0; i < modules.length; i += batch_size) {
batches.push(modules.slice(i, i + batch_size));
}
return batches;
}
// Examples: 10→[4,4,2] | 8→[4,4] | 3→[3]Coordinator Orchestration
let modules_by_depth = group_by_depth(changed_modules);
let tool_order = construct_tool_order(primary_tool);
let project_name = detect_project_name();
for (let depth of sorted_depths.reverse()) { // N → 0
let batches = batch_modules(modules_by_depth[depth], 4);
let worker_tasks = [];
for (let batch of batches) {
worker_tasks.push(
Task(
subagent_type="memory-bridge",
description=`Generate docs for ${batch.length} modules at depth ${depth}`,
prompt=generate_batch_worker_prompt(batch, tool_order, depth, project_name, "related")
)
);
}
await parallel_execute(worker_tasks); // Batches run in parallel
}Batch Worker Prompt Template
PURPOSE: Generate/update documentation for assigned modules with tool fallback (related mode)
TASK:
Generate documentation for the following modules based on recent changes. For each module, try tools in order until success.
PROJECT: {{project_name}}
OUTPUT: .workflow/docs/{{project_name}}/
MODULES:
{{module_path_1}} (type: {{folder_type_1}})
{{module_path_2}} (type: {{folder_type_2}})
{{module_path_3}} (type: {{folder_type_3}})
{{module_path_4}} (type: {{folder_type_4}})
TOOLS (try in order):
1. {{tool_1}}
2. {{tool_2}}
3. {{tool_3}}
EXECUTION:
For each module above:
1. Try tool 1:
Bash({
command: `cd "{{module_path}}" && ccw tool exec generate_module_docs '{"strategy":"single","sourcePath":".","projectName":"{{project_name}}","tool":"{{tool_1}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} docs generated with {{tool_1}}", proceed to next module
→ Failure: Try tool 2
2. Try tool 2:
Bash({
command: `cd "{{module_path}}" && ccw tool exec generate_module_docs '{"strategy":"single","sourcePath":".","projectName":"{{project_name}}","tool":"{{tool_2}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} docs generated with {{tool_2}}", proceed to next module
→ Failure: Try tool 3
3. Try tool 3:
Bash({
command: `cd "{{module_path}}" && ccw tool exec generate_module_docs '{"strategy":"single","sourcePath":".","projectName":"{{project_name}}","tool":"{{tool_3}}"}'`,
run_in_background: false
})
→ Success: Report "✅ {{module_path}} docs generated with {{tool_3}}", proceed to next module
→ Failure: Report "❌ FAILED: {{module_path}} failed all tools", proceed to next module
FOLDER TYPE HANDLING:
- code: Generate API.md + README.md
- navigation: Generate README.md only
REPORTING:
Report final summary with:
- Total processed: X modules
- Successful: Y modules
- Failed: Z modules
- Tool usage: {{tool_1}}:X, {{tool_2}}:Y, {{tool_3}}:ZStep 5.4: Verification
// Check documentation files created/updated
Bash({command: 'find .workflow/docs -type f -name "*.md" 2>/dev/null | wc -l', run_in_background: false});
// Display recent changes
Bash({command: 'find .workflow/docs -type f -name "*.md" -mmin -60 2>/dev/null', run_in_background: false});Aggregate results:
Documentation Generation Summary:
Total: 4 | Success: 4 | Failed: 0
Tool usage:
- gemini: 4 modules
- qwen: 0 modules (fallback)
- codex: 0 modules
Changes:
.workflow/docs/myproject/src/api/auth/API.md (new)
.workflow/docs/myproject/src/api/auth/README.md (new)
.workflow/docs/myproject/src/api/API.md (updated)
.workflow/docs/myproject/src/api/README.md (updated)
.workflow/docs/myproject/src/API.md (updated)
.workflow/docs/myproject/src/README.md (updated)
.workflow/docs/myproject/API.md (updated)
.workflow/docs/myproject/README.md (updated)Output Structure
.workflow/docs/{project_name}/
├── src/ # Mirrors source structure
│ ├── modules/
│ │ ├── README.md
│ │ ├── auth/
│ │ │ ├── API.md # Updated based on code changes
│ │ │ └── README.md # Updated based on code changes
│ │ └── api/
│ │ ├── API.md
│ │ └── README.md
│ └── utils/
│ └── README.md
└── README.mdError Handling
Batch Worker:
- Tool fallback per module (auto-retry)
- Batch isolation (failures don't propagate)
- Clear per-module status reporting
Coordinator:
- No changes: Use fallback (recent 10 modules)
- User decline: No execution
- Verification fail: Report incomplete modules
- Partial failures: Continue execution, report failed modules
Fallback Triggers:
- Non-zero exit code
- Script timeout
- Unexpected output
Template Reference
Templates used from ~/.ccw/workflows/cli-templates/prompts/documentation/:
api.txt: Code API documentationmodule-readme.txt: Module purpose, usage, dependenciesfolder-navigation.txt: Navigation README for folders
Output
- Directory:
.workflow/docs/{project_name}/— Updated documentation for changed modules - Report: Summary with success/failure counts, tool usage, and file change list
Next Phase
Return to manage.md router.