diff --git a/.claude/commands/clean.md b/.claude/commands/workflow/clean.md similarity index 97% rename from .claude/commands/clean.md rename to .claude/commands/workflow/clean.md index 99b079f5..60533ace 100644 --- a/.claude/commands/clean.md +++ b/.claude/commands/workflow/clean.md @@ -5,7 +5,7 @@ argument-hint: "[--dry-run] [\"focus area\"]" allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*) --- -# Clean Command (/clean) +# Clean Command (/workflow:clean) ## Overview @@ -20,9 +20,9 @@ Intelligent cleanup command that explores the codebase to identify the developme ## Usage ```bash -/clean # Full intelligent cleanup (explore → analyze → confirm → execute) -/clean --dry-run # Explore and analyze only, no execution -/clean "auth module" # Focus cleanup on specific area +/workflow:clean # Full intelligent cleanup (explore → analyze → confirm → execute) +/workflow:clean --dry-run # Explore and analyze only, no execution +/workflow:clean "auth module" # Focus cleanup on specific area ``` ## Execution Process @@ -321,7 +321,7 @@ if (flags.includes('--dry-run')) { **Dry-run mode**: No changes made. Manifest saved to: ${sessionFolder}/cleanup-manifest.json -To execute cleanup: /clean +To execute cleanup: /workflow:clean `) return } diff --git a/.claude/commands/workflow/docs/analyze.md b/.claude/commands/workflow/docs/analyze.md new file mode 100644 index 00000000..6a43f623 --- /dev/null +++ b/.claude/commands/workflow/docs/analyze.md @@ -0,0 +1,1467 @@ +--- +name: analyze +description: Multi-phase iterative project analysis with user-guided focus, produces architecture/design/method reports through incremental updates +argument-hint: "[scope|path] [--type=architecture|design|methods|comprehensive]" +allowed-tools: Task(*), AskUserQuestion(*), Read(*), Bash(*), Glob(*), Grep(*), TodoWrite(*), Write(*) +--- + +# Workflow Docs Analyze Command (/workflow:docs:analyze) + +## Overview + +**Iterative project analysis command** that guides users through multi-phase analysis to produce tailored project reports. Uses multi-agent collaboration with incremental report updates based on user feedback. + +**Core Differentiator**: Unlike static analysis tools, this command engages in multi-round dialogue to understand user's specific focus areas and iteratively refines reports until user satisfaction. + +## Report Types + +| Type | Focus | Output | +|------|-------|--------| +| `architecture` | System structure, module relationships, dependencies | ARCHITECTURE-REPORT.md | +| `design` | Design patterns, class diagrams, component interactions | DESIGN-REPORT.md | +| `methods` | Key algorithms, critical paths, core functions explained | METHODS-REPORT.md | +| `comprehensive` | All above combined | COMPREHENSIVE-REPORT.md | + +## Execution Philosophy + +**User-Centric Iteration Model**: +1. **Discover** user's actual analysis needs (not assume) +2. **Explore** codebase from multiple angles +3. **Generate** initial report with clear structure +4. **Iterate** based on user feedback until satisfied +5. **Finalize** polished report + +## Execution Process + +``` +Input Parsing: + ├─ Parse: scope/path (optional, defaults to project root) + └─ Parse: --type flag (optional, determines initial focus) + +Phase 1: Requirements Discovery (AskUserQuestion) + ├─ Ask: Report type preference (if not specified) + ├─ Ask: Focus areas within chosen type + ├─ Ask: Depth level (overview/detailed/deep-dive) + └─ Output: analysis_config object + +Phase 2: Project Exploration (cli-explore-agent) + ├─ Execute: Parallel exploration by focus areas + ├─ Generate: exploration-{angle}.json files + └─ Output: explorations-manifest.json + +Phase 3: Deep Analysis (Gemini CLI) + ├─ Execute: Multi-dimensional analysis + ├─ Generate: analysis-{dimension}.json files + └─ Output: analysis-manifest.json + +Phase 4: Initial Report Generation + ├─ Synthesize: Merge all analysis results + ├─ Generate: {TYPE}-REPORT.md (draft) + └─ Output: Present report to user + +Phase 5: Iterative Refinement (Loop) + ├─ Ask: User feedback on current report + ├─ Decision: + │ ├─ "satisfied" → Finalize and exit + │ ├─ "expand section X" → Deep-dive specific area + │ ├─ "add details on Y" → Augment with new analysis + │ └─ "change focus" → Re-run Phase 3 with new config + └─ Update: Incremental report modification + +Finalize: + └─ Output: Final {TYPE}-REPORT.md +``` + +## 5-Phase Execution + +### Phase 1: Requirements Discovery + +**Purpose**: Understand user's actual analysis needs through interactive questioning + +**Step 1.1: Initialize TodoWrite** + +```javascript +TodoWrite([ + {content: "Phase 1: Requirements Discovery", status: "in_progress", activeForm: "Discovering analysis requirements"}, + {content: "Phase 2: Project Exploration", status: "pending", activeForm: "Exploring project structure"}, + {content: "Phase 3: Deep Analysis", status: "pending", activeForm: "Performing deep analysis"}, + {content: "Phase 4: Initial Report Generation", status: "pending", activeForm: "Generating initial report"}, + {content: "Phase 5: Iterative Refinement", status: "pending", activeForm: "Refining report based on feedback"} +]) +``` + +**Step 1.2: Report Type Selection (if not specified)** + +```javascript +if (!type_specified) { + AskUserQuestion({ + questions: [{ + question: "What type of project analysis report would you like?", + header: "Report Type", + multiSelect: false, + options: [ + {label: "Architecture (Recommended)", description: "System structure, module relationships, layer analysis, dependency graph"}, + {label: "Design", description: "Design patterns, class relationships, component interactions, abstraction analysis"}, + {label: "Methods", description: "Key algorithms, critical code paths, core function explanations with examples"}, + {label: "Comprehensive", description: "All above combined into a complete project analysis"} + ] + }] + }) +} +``` + +**Step 1.3: Focus Area Discovery** + +```javascript +// Based on report type, ask focused questions +const focusQuestions = { + architecture: { + question: "Which architectural aspects are you most interested in?", + header: "Focus Areas", + multiSelect: true, + options: [ + {label: "Layer Structure", description: "How the system is divided into layers (presentation, business, data)"}, + {label: "Module Dependencies", description: "How modules depend on and communicate with each other"}, + {label: "Entry Points", description: "How requests flow through the system from entry to response"}, + {label: "Data Flow", description: "How data moves and transforms across the system"} + ] + }, + design: { + question: "Which design aspects do you want to understand?", + header: "Design Focus", + multiSelect: true, + options: [ + {label: "Design Patterns", description: "Identify and explain patterns used in the codebase"}, + {label: "Class Relationships", description: "Inheritance, composition, and associations between classes"}, + {label: "Interface Contracts", description: "How components communicate through interfaces/protocols"}, + {label: "State Management", description: "How application state is managed and mutated"} + ] + }, + methods: { + question: "What kind of method analysis do you need?", + header: "Method Focus", + multiSelect: true, + options: [ + {label: "Core Algorithms", description: "Key algorithms that define the system's behavior"}, + {label: "Critical Paths", description: "Most important execution flows in the application"}, + {label: "Public APIs", description: "External-facing methods and their contracts"}, + {label: "Complex Logic", description: "Methods with high cyclomatic complexity explained"} + ] + } +}; + +AskUserQuestion({questions: [focusQuestions[selected_type]]}) +``` + +**Step 1.4: Depth Level Selection** + +```javascript +AskUserQuestion({ + questions: [{ + question: "How detailed should the analysis be?", + header: "Depth", + multiSelect: false, + options: [ + {label: "Overview (Recommended)", description: "High-level understanding, suitable for onboarding or quick review"}, + {label: "Detailed", description: "In-depth analysis with code examples and explanations"}, + {label: "Deep-Dive", description: "Exhaustive analysis with implementation details and edge cases"} + ] + }] +}) +``` + +**Step 1.5: Store Analysis Config** + +```javascript +const analysis_config = { + type: selected_type, + focus_areas: selected_focus_areas, + depth: selected_depth, + scope: scope_path || ".", + timestamp: new Date().toISOString() +}; + +// Create output directory +const outputDir = `.workflow/.scratchpad/analyze-${Date.now()}`; +bash(`mkdir -p ${outputDir}`); +Write(`${outputDir}/analysis-config.json`, JSON.stringify(analysis_config, null, 2)); +``` + +**TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress + +--- + +### Phase 2: Project Exploration + +**Purpose**: Multi-angle exploration based on user's focus areas + +**Step 2.1: Launch Parallel Explore Agents** + +```javascript +const explorationAngles = mapFocusToAngles(analysis_config.focus_areas); +// Examples: +// - "Layer Structure" → ["architecture", "dependencies"] +// - "Design Patterns" → ["patterns", "abstractions"] +// - "Core Algorithms" → ["algorithms", "complexity"] + +const explorationTasks = explorationAngles.map((angle, index) => + Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: `Explore: ${angle}`, + prompt: ` +## Exploration Objective +Execute **${angle}** exploration for project analysis report. + +## Context +- **Angle**: ${angle} +- **Report Type**: ${analysis_config.type} +- **Depth**: ${analysis_config.depth} +- **Scope**: ${analysis_config.scope} +- **Output**: ${outputDir}/exploration-${angle}.json + +## Exploration Protocol + +**Step 1: Structural Discovery** +- Execute: ccw tool exec get_modules_by_depth '{}' +- Find files relevant to ${angle} using rg/glob +- Map directory structure and module boundaries + +**Step 2: Pattern Recognition** +- Identify ${angle}-related patterns and conventions +- Note file naming, organization patterns +- Extract key abstractions + +**Step 3: Relationship Mapping** +- Map dependencies and relationships +- Identify integration points +- Note coupling and cohesion patterns + +## Output Format +{ + "angle": "${angle}", + "findings": { + "structure": [...], + "patterns": [...], + "relationships": [...], + "key_files": [{path, relevance, rationale}] + }, + "insights": [...], + "depth_notes": "${analysis_config.depth}-specific observations" +} + +Write output to: ${outputDir}/exploration-${angle}.json +` + }) +); +``` + +**Step 2.2: Generate Exploration Manifest** + +```javascript +const manifest = { + config: analysis_config, + explorations: explorationAngles.map(angle => ({ + angle, + file: `exploration-${angle}.json` + })), + timestamp: new Date().toISOString() +}; +Write(`${outputDir}/explorations-manifest.json`, JSON.stringify(manifest, null, 2)); +``` + +**TodoWrite**: Mark Phase 2 completed, Phase 3 in_progress + +--- + +### Phase 3: Deep Analysis + +**Purpose**: Use Gemini CLI for in-depth analysis based on exploration results + +**Step 3.1: Synthesize Exploration Results** + +```javascript +// Read all exploration files +const explorations = explorationAngles.map(angle => + JSON.parse(Read(`${outputDir}/exploration-${angle}.json`)) +); + +// Extract key files to analyze +const keyFiles = explorations.flatMap(e => e.findings.key_files) + .sort((a, b) => b.relevance - a.relevance) + .slice(0, 20); // Top 20 most relevant files +``` + +**Step 3.2: Execute Deep Analysis via Gemini CLI** + +```javascript +const analysisPrompt = buildAnalysisPrompt(analysis_config, keyFiles); + +Bash({ + command: `ccw cli -p " +PURPOSE: Generate ${analysis_config.type} analysis report for project +TASK: + • Analyze project structure and patterns from ${analysis_config.type} perspective + • Focus on: ${analysis_config.focus_areas.join(', ')} + • Depth level: ${analysis_config.depth} + • Key files to analyze: ${keyFiles.map(f => f.path).join(', ')} +MODE: analysis +CONTEXT: @**/* | Exploration results from ${outputDir}/ +EXPECTED: + - Structured ${analysis_config.type} analysis + - Clear explanations with code references + - Mermaid diagrams where applicable + - Actionable insights +RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) | + Focus on ${analysis_config.focus_areas.join(', ')} | + Depth: ${analysis_config.depth} +" --tool gemini --mode analysis`, + run_in_background: true, + timeout: 600000 +}); +``` + +**Step 3.3: Store Analysis Results** + +```javascript +// After CLI completes, store structured results +Write(`${outputDir}/deep-analysis.json`, JSON.stringify({ + type: analysis_config.type, + focus_areas: analysis_config.focus_areas, + analysis_result: cli_output, + diagrams: extracted_diagrams, + code_references: extracted_references +}, null, 2)); +``` + +**TodoWrite**: Mark Phase 3 completed, Phase 3.5 in_progress + +--- + +### Phase 3.5: Diagram Generation + +**Purpose**: Generate Mermaid diagrams based on analysis results, tailored to report type + +**Step 3.5.1: Determine Required Diagrams** + +```javascript +// Map report types to required diagram types +const diagramRequirements = { + architecture: [ + {type: 'architecture', format: 'graph TD', name: 'System Architecture'}, + {type: 'layers', format: 'graph TD', name: 'Layer Structure'}, + {type: 'dependencies', format: 'graph LR', name: 'Module Dependencies'}, + {type: 'dataflow', format: 'flowchart LR', name: 'Data Flow'} + ], + design: [ + {type: 'class', format: 'classDiagram', name: 'Class Diagram'}, + {type: 'components', format: 'graph TD', name: 'Component Diagram'}, + {type: 'patterns', format: 'graph TD', name: 'Design Patterns'}, + {type: 'state', format: 'stateDiagram-v2', name: 'State Management'} + ], + methods: [ + {type: 'algorithm', format: 'flowchart TD', name: 'Algorithm Flowchart'}, + {type: 'sequence', format: 'sequenceDiagram', name: 'Call Sequence'}, + {type: 'critical_path', format: 'flowchart LR', name: 'Critical Path'}, + {type: 'api', format: 'graph LR', name: 'API Structure'} + ], + comprehensive: [ + {type: 'architecture', format: 'graph TD', name: 'System Architecture'}, + {type: 'class', format: 'classDiagram', name: 'Class Diagram'}, + {type: 'sequence', format: 'sequenceDiagram', name: 'Key Sequences'}, + {type: 'dataflow', format: 'flowchart LR', name: 'Data Flow'} + ] +}; + +const requiredDiagrams = diagramRequirements[config.type]; +bash(`mkdir -p ${outputDir}/diagrams`); +``` + +**Step 3.5.2: Generate Architecture Diagrams (graph TD)** + +```javascript +function generateArchitectureDiagram(analysis) { + let mermaid = 'graph TD\n'; + + // Subgraphs for layers/modules + const layers = analysis.structure?.layers || extractLayers(analysis); + for (const layer of layers) { + mermaid += ` subgraph ${sanitizeId(layer.name)}["${escapeLabel(layer.name)}"]\n`; + for (const component of layer.components || []) { + mermaid += ` ${sanitizeId(component.id)}["${escapeLabel(component.name)}"]\n`; + } + mermaid += ' end\n'; + } + + // Connections + const connections = analysis.relationships || []; + for (const conn of connections) { + const label = conn.label ? `|"${escapeLabel(conn.label)}"|` : ''; + mermaid += ` ${sanitizeId(conn.from)} -->${label} ${sanitizeId(conn.to)}\n`; + } + + // Styling + mermaid += '\n %% Styling\n'; + mermaid += ' classDef core fill:#e1f5fe,stroke:#01579b\n'; + mermaid += ' classDef external fill:#fff3e0,stroke:#e65100\n'; + + return mermaid; +} + +if (requiredDiagrams.some(d => d.type === 'architecture')) { + const archDiagram = generateArchitectureDiagram(deepAnalysis); + Write(`${outputDir}/diagrams/architecture.mmd`, archDiagram); +} +``` + +**Step 3.5.3: Generate Layer/Dependency Diagrams** + +```javascript +function generateLayerDiagram(analysis) { + let mermaid = 'graph TD\n'; + + const layers = ['Presentation', 'Application', 'Domain', 'Infrastructure']; + const detectedLayers = analysis.layers || inferLayers(analysis); + + for (let i = 0; i < detectedLayers.length; i++) { + const layer = detectedLayers[i]; + mermaid += ` subgraph L${i}["${escapeLabel(layer.name)}"]\n`; + mermaid += ` direction LR\n`; + for (const mod of layer.modules || []) { + mermaid += ` ${sanitizeId(mod)}["${escapeLabel(mod)}"]\n`; + } + mermaid += ' end\n'; + + if (i < detectedLayers.length - 1) { + mermaid += ` L${i} --> L${i + 1}\n`; + } + } + + return mermaid; +} + +function generateDependencyDiagram(analysis) { + let mermaid = 'graph LR\n'; + + const modules = analysis.modules || []; + const deps = analysis.dependencies || []; + + // Nodes + for (const mod of modules) { + const shape = mod.type === 'core' ? '([' : '['; + const shapeEnd = mod.type === 'core' ? '])' : ']'; + mermaid += ` ${sanitizeId(mod.name)}${shape}"${escapeLabel(mod.name)}"${shapeEnd}\n`; + } + + // Edges with labels + for (const dep of deps) { + const style = dep.type === 'weak' ? '-.->' : '-->'; + const label = dep.count ? `|"${dep.count} refs"|` : ''; + mermaid += ` ${sanitizeId(dep.from)} ${style}${label} ${sanitizeId(dep.to)}\n`; + } + + return mermaid; +} + +if (requiredDiagrams.some(d => d.type === 'layers')) { + Write(`${outputDir}/diagrams/layers.mmd`, generateLayerDiagram(deepAnalysis)); +} +if (requiredDiagrams.some(d => d.type === 'dependencies')) { + Write(`${outputDir}/diagrams/dependencies.mmd`, generateDependencyDiagram(deepAnalysis)); +} +``` + +**Step 3.5.4: Generate Class Diagrams (classDiagram)** + +```javascript +function generateClassDiagram(analysis) { + let mermaid = 'classDiagram\n'; + + const entities = analysis.entities || analysis.classes || []; + + // Classes with properties and methods + for (const entity of entities.slice(0, 15)) { // Limit for readability + mermaid += ` class ${sanitizeId(entity.name)} {\n`; + + // Properties + for (const prop of (entity.properties || []).slice(0, 8)) { + const vis = {public: '+', private: '-', protected: '#'}[prop.visibility] || '+'; + mermaid += ` ${vis}${sanitizeType(prop.type)} ${prop.name}\n`; + } + + // Methods + for (const method of (entity.methods || []).slice(0, 6)) { + const vis = {public: '+', private: '-', protected: '#'}[method.visibility] || '+'; + const params = (method.params || []).map(p => `${p.name}`).join(', '); + mermaid += ` ${vis}${method.name}(${params}) ${sanitizeType(method.returnType || 'void')}\n`; + } + + mermaid += ' }\n'; + } + + // Relationships + const relationships = analysis.relationships || []; + const arrows = { + inheritance: '--|>', + implementation: '..|>', + composition: '*--', + aggregation: 'o--', + association: '-->', + dependency: '..>' + }; + + for (const rel of relationships) { + const arrow = arrows[rel.type] || '-->'; + const label = rel.label ? ` : ${escapeLabel(rel.label)}` : ''; + mermaid += ` ${sanitizeId(rel.from)} ${arrow} ${sanitizeId(rel.to)}${label}\n`; + } + + return mermaid; +} + +if (requiredDiagrams.some(d => d.type === 'class')) { + Write(`${outputDir}/diagrams/class-diagram.mmd`, generateClassDiagram(deepAnalysis)); +} +``` + +**Step 3.5.5: Generate Flowcharts (flowchart TD)** + +```javascript +function generateAlgorithmFlowchart(algorithm) { + let mermaid = 'flowchart TD\n'; + + // Start + mermaid += ` START(["Start: ${escapeLabel(algorithm.name)}"])\n`; + + // Input processing + if (algorithm.inputs?.length > 0) { + mermaid += ` INPUT[/"Input: ${algorithm.inputs.map(i => i.name).join(', ')}"/]\n`; + mermaid += ' START --> INPUT\n'; + } + + // Process steps + let prevNode = algorithm.inputs?.length > 0 ? 'INPUT' : 'START'; + for (let i = 0; i < (algorithm.steps || []).length; i++) { + const step = algorithm.steps[i]; + const nodeId = `STEP${i}`; + + if (step.type === 'decision') { + mermaid += ` ${nodeId}{"${escapeLabel(step.description)}"}\n`; + mermaid += ` ${prevNode} --> ${nodeId}\n`; + if (step.yes_branch) { + mermaid += ` ${nodeId} -->|"Yes"| ${sanitizeId(step.yes_branch)}\n`; + } + if (step.no_branch) { + mermaid += ` ${nodeId} -->|"No"| ${sanitizeId(step.no_branch)}\n`; + } + } else { + mermaid += ` ${nodeId}["${escapeLabel(step.description)}"]\n`; + mermaid += ` ${prevNode} --> ${nodeId}\n`; + } + prevNode = nodeId; + } + + // Output and end + mermaid += ` OUTPUT[/"Output: ${escapeLabel(algorithm.output || 'Result')}"/]\n`; + mermaid += ` ${prevNode} --> OUTPUT\n`; + mermaid += ' END_([End])\n'; + mermaid += ' OUTPUT --> END_\n'; + + return mermaid; +} + +function generateDataFlowDiagram(analysis) { + let mermaid = 'flowchart LR\n'; + + const flows = analysis.dataFlows || []; + + // Data stores + mermaid += ' subgraph DataStores["Data Stores"]\n'; + for (const store of analysis.dataStores || []) { + mermaid += ` ${sanitizeId(store.id)}[("${escapeLabel(store.name)}")]\n`; + } + mermaid += ' end\n'; + + // Processes + mermaid += ' subgraph Processes["Processes"]\n'; + for (const proc of analysis.processes || []) { + mermaid += ` ${sanitizeId(proc.id)}["${escapeLabel(proc.name)}"]\n`; + } + mermaid += ' end\n'; + + // Flows + for (const flow of flows) { + mermaid += ` ${sanitizeId(flow.from)} -->|"${escapeLabel(flow.data)}"| ${sanitizeId(flow.to)}\n`; + } + + return mermaid; +} + +// Generate algorithm flowcharts +const algorithms = deepAnalysis.algorithms || []; +for (const algo of algorithms.slice(0, 3)) { // Top 3 algorithms + const flowchart = generateAlgorithmFlowchart(algo); + Write(`${outputDir}/diagrams/algorithm-${sanitizeId(algo.name)}.mmd`, flowchart); +} + +if (requiredDiagrams.some(d => d.type === 'dataflow')) { + Write(`${outputDir}/diagrams/dataflow.mmd`, generateDataFlowDiagram(deepAnalysis)); +} +``` + +**Step 3.5.6: Generate Sequence Diagrams (sequenceDiagram)** + +```javascript +function generateSequenceDiagram(scenario) { + let mermaid = 'sequenceDiagram\n'; + + // Title + mermaid += ` title ${escapeLabel(scenario.name)}\n`; + + // Participants + for (const actor of scenario.actors || []) { + const type = actor.type === 'external' ? 'actor' : 'participant'; + mermaid += ` ${type} ${sanitizeId(actor.id)} as ${escapeLabel(actor.name)}\n`; + } + + mermaid += '\n'; + + // Messages + for (const msg of scenario.messages || []) { + let arrow; + switch (msg.type) { + case 'async': arrow = '->>'; break; + case 'response': arrow = '-->>'; break; + case 'create': arrow = '->>+'; break; + case 'destroy': arrow = '->>-'; break; + default: arrow = '->>'; + } + + mermaid += ` ${sanitizeId(msg.from)}${arrow}${sanitizeId(msg.to)}: ${escapeLabel(msg.description)}\n`; + + // Activations + if (msg.activate) { + mermaid += ` activate ${sanitizeId(msg.to)}\n`; + } + if (msg.deactivate) { + mermaid += ` deactivate ${sanitizeId(msg.from)}\n`; + } + + // Notes + if (msg.note) { + mermaid += ` Note over ${sanitizeId(msg.to)}: ${escapeLabel(msg.note)}\n`; + } + } + + // Loops and conditions + for (const block of scenario.blocks || []) { + if (block.type === 'loop') { + mermaid += ` loop ${escapeLabel(block.condition)}\n`; + for (const m of block.messages) { + mermaid += ` ${sanitizeId(m.from)}->>${sanitizeId(m.to)}: ${escapeLabel(m.description)}\n`; + } + mermaid += ' end\n'; + } + } + + return mermaid; +} + +// Generate sequence diagrams for key scenarios +const scenarios = deepAnalysis.sequences || deepAnalysis.scenarios || []; +for (const scenario of scenarios.slice(0, 3)) { + const seqDiagram = generateSequenceDiagram(scenario); + Write(`${outputDir}/diagrams/sequence-${sanitizeId(scenario.name)}.mmd`, seqDiagram); +} +``` + +**Step 3.5.7: Generate State Diagrams (stateDiagram-v2)** + +```javascript +function generateStateDiagram(stateAnalysis) { + let mermaid = 'stateDiagram-v2\n'; + + const states = stateAnalysis.states || []; + const transitions = stateAnalysis.transitions || []; + + // States + for (const state of states) { + if (state.type === 'initial') { + mermaid += ` [*] --> ${sanitizeId(state.name)}\n`; + } else if (state.type === 'final') { + mermaid += ` ${sanitizeId(state.name)} --> [*]\n`; + } else if (state.substates) { + mermaid += ` state ${sanitizeId(state.name)} {\n`; + for (const sub of state.substates) { + mermaid += ` ${sanitizeId(sub.name)}\n`; + } + mermaid += ' }\n'; + } else { + mermaid += ` ${sanitizeId(state.name)} : ${escapeLabel(state.description || state.name)}\n`; + } + } + + // Transitions + for (const trans of transitions) { + const label = trans.event ? ` : ${escapeLabel(trans.event)}` : ''; + mermaid += ` ${sanitizeId(trans.from)} --> ${sanitizeId(trans.to)}${label}\n`; + } + + return mermaid; +} + +if (requiredDiagrams.some(d => d.type === 'state')) { + const stateAnalysis = deepAnalysis.stateManagement || {}; + if (stateAnalysis.states?.length > 0) { + Write(`${outputDir}/diagrams/state.mmd`, generateStateDiagram(stateAnalysis)); + } +} +``` + +**Step 3.5.8: Helper Functions & Validation** + +```javascript +// Sanitize ID for Mermaid (only alphanumeric and underscore) +function sanitizeId(text) { + return text.replace(/[^a-zA-Z0-9_]/g, '_').replace(/^[0-9]/, '_$&'); +} + +// Escape special characters in labels +function escapeLabel(text) { + if (!text) return ''; + return text + .replace(/"/g, "'") + .replace(/[(){}[\]<>]/g, char => `#${char.charCodeAt(0)};`) + .substring(0, 50); // Limit length +} + +// Sanitize type names +function sanitizeType(type) { + if (!type) return 'any'; + return type.replace(/[<>]/g, '').replace(/\|/g, ' or '); +} + +// Validate all generated diagrams +function validateMermaidDiagrams(diagramDir) { + const files = Glob(`${diagramDir}/*.mmd`); + const results = []; + + for (const file of files) { + const content = Read(file); + const issues = []; + + // Check for common syntax errors + if (content.includes('undefined')) issues.push('Contains undefined'); + if (content.match(/-->.*-->/)) issues.push('Double arrow syntax'); + if (!content.match(/^(graph|flowchart|classDiagram|sequenceDiagram|stateDiagram)/m)) { + issues.push('Missing diagram type declaration'); + } + + // Check for unescaped special chars in labels + const labelMatches = content.match(/\["[^"]*[(){}[\]<>][^"]*"\]/g); + if (labelMatches?.some(m => !m.includes('#'))) { + issues.push('Unescaped special characters in labels'); + } + + results.push({ + file: file.split('/').pop(), + valid: issues.length === 0, + issues + }); + } + + return results; +} + +const validationResults = validateMermaidDiagrams(`${outputDir}/diagrams`); +Write(`${outputDir}/diagrams/validation.json`, JSON.stringify(validationResults, null, 2)); + +// Log validation summary +const validCount = validationResults.filter(r => r.valid).length; +console.log(`Diagram Validation: ${validCount}/${validationResults.length} passed`); +``` + +**Step 3.5.9: Generate Diagram Manifest** + +```javascript +const diagramManifest = { + report_type: config.type, + generated_at: new Date().toISOString(), + diagrams: requiredDiagrams.map(req => { + const filename = `${req.type}.mmd`; + const exists = file_exists(`${outputDir}/diagrams/${filename}`); + return { + type: req.type, + format: req.format, + name: req.name, + filename: exists ? filename : null, + status: exists ? 'generated' : 'skipped' + }; + }), + validation: validationResults +}; + +Write(`${outputDir}/diagrams/manifest.json`, JSON.stringify(diagramManifest, null, 2)); +``` + +**TodoWrite**: Mark Phase 3.5 completed, Phase 4 in_progress + +--- + +### Phase 4: Initial Report Generation + +**Purpose**: Synthesize all analysis into structured report + +**Step 4.1: Load All Analysis Data and Diagrams** + +```javascript +const config = JSON.parse(Read(`${outputDir}/analysis-config.json`)); +const explorations = JSON.parse(Read(`${outputDir}/explorations-manifest.json`)); +const deepAnalysis = JSON.parse(Read(`${outputDir}/deep-analysis.json`)); +const diagramManifest = JSON.parse(Read(`${outputDir}/diagrams/manifest.json`)); + +// Load all generated diagrams +const diagrams = {}; +for (const diag of diagramManifest.diagrams.filter(d => d.status === 'generated')) { + diagrams[diag.type] = Read(`${outputDir}/diagrams/${diag.filename}`); +} +``` + +**Step 4.2: Generate Report Structure** + +```javascript +const reportTemplate = getReportTemplate(config.type); +// Templates define section structure for each report type + +const reportSections = { + architecture: [ + "# Architecture Report", + "## Executive Summary", + "## System Overview", + "## Layer Analysis", + "## Module Dependencies", + "## Data Flow", + "## Entry Points & Critical Paths", + "## Dependency Graph (Mermaid)", + "## Recommendations" + ], + design: [ + "# Design Report", + "## Executive Summary", + "## Design Patterns Used", + "## Class Relationships", + "## Interface Contracts", + "## State Management", + "## Component Diagrams (Mermaid)", + "## Design Recommendations" + ], + methods: [ + "# Key Methods Report", + "## Executive Summary", + "## Core Algorithms", + "## Critical Code Paths", + "## Public API Reference", + "## Complex Logic Breakdown", + "## Sequence Diagrams (Mermaid)", + "## Optimization Suggestions" + ], + comprehensive: [ + "# Comprehensive Project Analysis", + "## Executive Summary", + "## Architecture Overview", + "## Design Patterns & Principles", + "## Key Methods & Algorithms", + "## System Diagrams", + "## Recommendations & Next Steps" + ] +}; +``` + +**Step 4.3: Generate Initial Report** + +```javascript +const reportPath = `${outputDir}/${config.type.toUpperCase()}-REPORT.md`; +const report = generateReport(reportSections[config.type], explorations, deepAnalysis); +Write(reportPath, report); +``` + +**Step 4.4: Present to User** + +```markdown +## Initial Report Generated + +**Report Type**: ${config.type} +**Focus Areas**: ${config.focus_areas.join(', ')} +**Depth**: ${config.depth} + +**Output**: ${reportPath} + +### Report Preview +[First 50 lines of report...] + +--- +**Ready for your feedback.** The report can be refined based on your input. +``` + +**TodoWrite**: Mark Phase 4 completed, Phase 5 in_progress + +--- + +### Phase 5: Iterative Refinement (Discovery-Driven) + +**Purpose**: Generate targeted questions based on agent analysis findings, then refine report based on user responses + +**Core Philosophy**: Questions are NOT predetermined. They emerge from what the agent discovered during analysis. + +**Step 5.1: Extract Discoveries from Analysis** + +```javascript +// Parse deep analysis results for actionable discoveries +function extractDiscoveries(deepAnalysis) { + return { + // Ambiguities: Areas where analysis found multiple interpretations + ambiguities: deepAnalysis.findings.filter(f => f.confidence < 0.7), + + // Complexity hotspots: Areas that may need deeper explanation + complexityHotspots: deepAnalysis.findings.filter(f => f.complexity === 'high'), + + // Pattern variations: Where code deviates from expected patterns + patternDeviations: deepAnalysis.patterns.filter(p => p.consistency < 0.8), + + // Unclear dependencies: Relationships that couldn't be fully traced + unclearDependencies: deepAnalysis.dependencies.filter(d => d.type === 'implicit'), + + // Potential issues: Areas flagged for attention + potentialIssues: deepAnalysis.recommendations.filter(r => r.priority === 'investigate'), + + // Depth opportunities: Sections that could benefit from expansion + depthOpportunities: deepAnalysis.sections.filter(s => s.has_more_detail) + }; +} + +const discoveries = extractDiscoveries(deepAnalysis); +``` + +**Step 5.2: Generate Dynamic Questions Based on Discoveries** + +```javascript +function buildDynamicQuestions(discoveries, config) { + const questions = []; + + // Question 1: Address ambiguities found + if (discoveries.ambiguities.length > 0) { + const topAmbiguity = discoveries.ambiguities[0]; + questions.push({ + question: `Analysis found ambiguity in "${topAmbiguity.area}": ${topAmbiguity.description}. Which interpretation is correct?`, + header: "Clarify", + multiSelect: false, + options: topAmbiguity.interpretations.map((interp, i) => ({ + label: interp.summary, + description: interp.detail + })) + }); + } + + // Question 2: Complexity deep-dive selection + if (discoveries.complexityHotspots.length > 0) { + questions.push({ + question: `These areas have high complexity. Which would you like explained in more detail?`, + header: "Deep-Dive", + multiSelect: true, + options: discoveries.complexityHotspots.slice(0, 4).map(h => ({ + label: h.name, + description: `${h.file}:${h.line} - ${h.brief}` + })) + }); + } + + // Question 3: Pattern deviation confirmation + if (discoveries.patternDeviations.length > 0) { + const deviation = discoveries.patternDeviations[0]; + questions.push({ + question: `Found pattern inconsistency: "${deviation.pattern}" is used differently in ${deviation.locations.length} places. Should I analyze this deviation?`, + header: "Patterns", + multiSelect: false, + options: [ + {label: "Yes, analyze differences", description: "Add detailed comparison to report"}, + {label: "Skip, it's intentional", description: "Note as intentional variation"}, + {label: "Flag as tech debt", description: "Add to recommendations section"} + ] + }); + } + + // Question 4: Dependency clarification + if (discoveries.unclearDependencies.length > 0) { + questions.push({ + question: `Found ${discoveries.unclearDependencies.length} implicit dependencies. Should I trace them fully?`, + header: "Dependencies", + multiSelect: false, + options: [ + {label: "Yes, trace all (Recommended)", description: "Complete dependency graph, may take longer"}, + {label: "Only critical paths", description: "Focus on main execution flows"}, + {label: "Skip for now", description: "Keep current analysis level"} + ] + }); + } + + // Always include satisfaction check as final question + questions.push({ + question: "How would you like to proceed with the current report?", + header: "Action", + multiSelect: false, + options: [ + {label: "Continue refining", description: "Apply above selections and show next discoveries"}, + {label: "Finalize report", description: "Report meets my needs, generate final version"}, + {label: "Change scope", description: "Adjust focus areas or analysis depth"} + ] + }); + + return questions.slice(0, 4); // Max 4 questions per iteration +} + +const dynamicQuestions = buildDynamicQuestions(discoveries, config); +AskUserQuestion({questions: dynamicQuestions}); +``` + +**Step 5.3: Process User Responses and Update Analysis** + +```javascript +function processResponses(responses, discoveries, deepAnalysis) { + const updates = []; + + // Handle ambiguity resolution + if (responses.clarify) { + const resolution = { + area: discoveries.ambiguities[0].area, + resolved_to: responses.clarify, + confidence: 1.0 // User confirmed + }; + updates.push({type: 'resolve_ambiguity', data: resolution}); + } + + // Handle deep-dive requests + if (responses.deepDive && responses.deepDive.length > 0) { + const deepDiveTargets = responses.deepDive; + updates.push({type: 'expand_sections', data: deepDiveTargets}); + } + + // Handle pattern deviation response + if (responses.patterns) { + updates.push({type: 'pattern_handling', data: responses.patterns}); + } + + // Handle dependency tracing + if (responses.dependencies) { + updates.push({type: 'dependency_depth', data: responses.dependencies}); + } + + return updates; +} + +const updates = processResponses(user_responses, discoveries, deepAnalysis); +``` + +**Step 5.4: Incremental Analysis & Report Update** + +```javascript +// Execute targeted re-analysis based on user responses +async function applyUpdates(updates, outputDir, config) { + for (const update of updates) { + switch (update.type) { + case 'expand_sections': + // Re-run Gemini CLI for specific sections only + for (const target of update.data) { + Bash({ + command: `ccw cli -p " +PURPOSE: Deep-dive analysis of ${target.name} +TASK: Provide detailed explanation of ${target.file}:${target.line} + • Trace execution flow step by step + • Explain complex logic with examples + • Show relationships to other components +MODE: analysis +CONTEXT: @${target.file} | Previous analysis from ${outputDir}/ +EXPECTED: Detailed section content for report insertion +RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) +" --tool gemini --mode analysis`, + run_in_background: true + }); + } + break; + + case 'resolve_ambiguity': + // Update analysis with confirmed interpretation + deepAnalysis.findings = deepAnalysis.findings.map(f => + f.area === update.data.area + ? {...f, interpretation: update.data.resolved_to, confidence: 1.0} + : f + ); + break; + + case 'dependency_depth': + if (update.data === 'Yes, trace all (Recommended)') { + // Launch dependency tracing agent + Task({ + subagent_type: "cli-explore-agent", + description: "Trace full dependencies", + prompt: `Trace all implicit dependencies found in ${outputDir}/deep-analysis.json` + }); + } + break; + } + } +} + +await applyUpdates(updates, outputDir, config); + +// Regenerate report sections affected by updates +const currentReport = Read(reportPath); +const updatedSections = regenerateAffectedSections(currentReport, updates); +Write(reportPath, updatedSections); +Write(`${outputDir}/iterations/v${iteration_count}.md`, currentReport); // Archive previous version +``` + +**Step 5.5: Check Termination or Continue Loop** + +```javascript +iteration_count++; + +if (user_responses.action === 'Finalize report') { + // Exit refinement loop + finalized = true; +} else if (user_responses.action === 'Change scope') { + // Return to Phase 1 for scope adjustment + goto Phase1_Step1_3; // Focus area selection +} else { + // Extract new discoveries from updated analysis + const newDiscoveries = extractDiscoveries(deepAnalysis); + + if (newDiscoveries.total_count === 0) { + // No more discoveries to clarify + console.log("All ambiguities resolved. Report is comprehensive."); + AskUserQuestion({ + questions: [{ + question: "No further clarifications needed. Finalize the report?", + header: "Complete", + multiSelect: false, + options: [ + {label: "Yes, finalize", description: "Generate final polished report"}, + {label: "Add custom section", description: "I want to add something specific"} + ] + }] + }); + } else { + // Continue with next round of discovery-driven questions + goto Step5.2; + } +} + +// Safety limit +if (iteration_count > 7) { + console.log("Maximum refinement iterations reached. Finalizing report."); + finalized = true; +} +``` + +**Step 5.6: Discovery Summary Between Iterations** + +```javascript +// Show user what was learned in this iteration +function summarizeIteration(iteration_count, updates, discoveries) { + return ` +### Iteration ${iteration_count} Summary + +**Clarifications Applied**: ${updates.filter(u => u.type === 'resolve_ambiguity').length} +**Sections Expanded**: ${updates.filter(u => u.type === 'expand_sections').length} +**Patterns Addressed**: ${updates.filter(u => u.type === 'pattern_handling').length} + +**Remaining Discoveries**: +- Ambiguities: ${discoveries.ambiguities.length} +- Complexity hotspots: ${discoveries.complexityHotspots.length} +- Pattern deviations: ${discoveries.patternDeviations.length} + +**Report Sections Updated**: [list affected sections] +`; +} + +console.log(summarizeIteration(iteration_count, updates, discoveries)); +``` + +--- + +### Finalization + +**Step 6.1: Polish Final Report** + +```javascript +// Add metadata and finalize formatting +const finalReport = ` + + + + +${report_content} + +--- +*Report generated through ${iteration_count} refinement iterations.* +`; + +Write(reportPath, finalReport); +``` + +**Step 6.2: Summary Output** + +```markdown +## Analysis Complete + +**Final Report**: ${reportPath} +**Report Type**: ${config.type} +**Focus Areas**: ${config.focus_areas.join(', ')} +**Refinement Iterations**: ${iteration_count} + +### Report Contents +- ${section_count} sections +- ${diagram_count} Mermaid diagrams +- ${code_reference_count} code references + +### Recommended Next Steps +1. Share report with team members +2. Use findings to guide development decisions +3. Run `/workflow:plan` to create implementation tasks based on recommendations +``` + +**TodoWrite**: Mark Phase 5 completed + +--- + +## TodoWrite Pattern + +**Dynamic Task Tracking** with phase-level visibility: + +```javascript +// Initial state +[ + {content: "Phase 1: Requirements Discovery", status: "pending", activeForm: "Discovering analysis requirements"}, + {content: "Phase 2: Project Exploration", status: "pending", activeForm: "Exploring project structure"}, + {content: "Phase 3: Deep Analysis", status: "pending", activeForm: "Performing deep analysis"}, + {content: "Phase 3.5: Diagram Generation", status: "pending", activeForm: "Generating Mermaid diagrams"}, + {content: "Phase 4: Initial Report Generation", status: "pending", activeForm: "Generating initial report"}, + {content: "Phase 5: Iterative Refinement", status: "pending", activeForm: "Refining report based on feedback"} +] + +// During Phase 3.5, show diagram generation progress +[ + {content: "Phase 1: Requirements Discovery", status: "completed", activeForm: "Discovering analysis requirements"}, + {content: "Phase 2: Project Exploration", status: "completed", activeForm: "Exploring project structure"}, + {content: "Phase 3: Deep Analysis", status: "completed", activeForm: "Performing deep analysis"}, + {content: "Phase 3.5: Diagram Generation", status: "in_progress", activeForm: "Generating Mermaid diagrams"}, + {content: " → Architecture diagram", status: "completed", activeForm: "Generating architecture diagram"}, + {content: " → Class diagram", status: "in_progress", activeForm: "Generating class diagram"}, + {content: " → Sequence diagrams", status: "pending", activeForm: "Generating sequence diagrams"}, + {content: "Phase 4: Initial Report Generation", status: "pending", activeForm: "Generating initial report"}, + {content: "Phase 5: Iterative Refinement", status: "pending", activeForm: "Refining report based on feedback"} +] + +// During Phase 5 iterations, expand to show current refinement +[ + {content: "Phase 1: Requirements Discovery", status: "completed", activeForm: "Discovering analysis requirements"}, + {content: "Phase 2: Project Exploration", status: "completed", activeForm: "Exploring project structure"}, + {content: "Phase 3: Deep Analysis", status: "completed", activeForm: "Performing deep analysis"}, + {content: "Phase 3.5: Diagram Generation", status: "completed", activeForm: "Generating Mermaid diagrams"}, + {content: "Phase 4: Initial Report Generation", status: "completed", activeForm: "Generating initial report"}, + {content: "Phase 5: Iterative Refinement", status: "in_progress", activeForm: "Refining report based on feedback"}, + {content: " → Iteration 2: Expanding Architecture section", status: "in_progress", activeForm: "Expanding section"} +] +``` + +## Usage Examples + +```bash +# Interactive analysis (prompts for all preferences) +/workflow:docs:analyze + +# Architecture report for specific directory +/workflow:docs:analyze src/core --type=architecture + +# Design patterns analysis +/workflow:docs:analyze --type=design + +# Comprehensive analysis of entire project +/workflow:docs:analyze --type=comprehensive + +# Key methods analysis for API module +/workflow:docs:analyze src/api --type=methods +``` + +## Output Structure + +``` +.workflow/.scratchpad/analyze-{timestamp}/ +├── analysis-config.json # User's analysis preferences +├── exploration-{angle}.json # Per-angle exploration results +├── explorations-manifest.json # Exploration summary +├── deep-analysis.json # Gemini CLI analysis output +├── diagrams/ # Generated Mermaid diagrams +│ ├── manifest.json # Diagram generation manifest +│ ├── validation.json # Syntax validation results +│ ├── architecture.mmd # System architecture (graph TD) +│ ├── layers.mmd # Layer structure (graph TD) +│ ├── dependencies.mmd # Module dependencies (graph LR) +│ ├── class-diagram.mmd # Class relationships (classDiagram) +│ ├── dataflow.mmd # Data flow (flowchart LR) +│ ├── algorithm-*.mmd # Algorithm flowcharts (flowchart TD) +│ ├── sequence-*.mmd # Call sequences (sequenceDiagram) +│ └── state.mmd # State transitions (stateDiagram-v2) +├── {TYPE}-REPORT.md # Final report (main output) +└── iterations/ # Refinement history + ├── v1-initial.md + ├── v2-expanded.md + └── ... +``` + +## Report Quality Standards + +**All reports must include**: +1. **Executive Summary**: 3-5 key takeaways +2. **Visual Diagrams**: Mermaid syntax for architecture/flow visualization +3. **Code References**: `file:line` format for easy navigation +4. **Actionable Insights**: Specific recommendations, not generic advice +5. **Consistent Depth**: Match user's selected depth level throughout + +**Quality Gates**: +- [ ] All focus areas addressed +- [ ] Diagrams render correctly (Mermaid syntax valid) +- [ ] Code references are accurate (files exist) +- [ ] No placeholder content +- [ ] Recommendations are project-specific + +## Error Handling + +| Error | Recovery | +|-------|----------| +| CLI timeout | Reduce scope, retry with fewer files | +| Exploration failure | Fall back to direct file reading | +| User abandons iteration | Save current progress, allow resume | +| Invalid scope path | Prompt user to correct path | + +## Related Commands + +**Prerequisite Commands**: +- None required (can be run independently) + +**Follow-up Commands**: +- `/workflow:plan` - Create implementation tasks from recommendations +- `/memory:docs` - Generate project documentation +- `/workflow:review` - Review specific areas identified in analysis + +**Alternative Commands**: +- `/memory:code-map-memory` - For feature-specific code mapping +- `/memory:load` - For quick context loading without reports + +--- + +## Mermaid Diagram Specifications + +### Diagram Types by Report + +| Report Type | Diagrams Generated | +|-------------|-------------------| +| `architecture` | architecture.mmd, layers.mmd, dependencies.mmd, dataflow.mmd | +| `design` | class-diagram.mmd, components.mmd, patterns.mmd, state.mmd | +| `methods` | algorithm-*.mmd, sequence-*.mmd, critical-path.mmd, api.mmd | +| `comprehensive` | architecture.mmd, class-diagram.mmd, sequence-*.mmd, dataflow.mmd | + +### Syntax Rules (Ensuring Valid Diagrams) + +```javascript +// 1. Node IDs: Only alphanumeric and underscore +sanitizeId("User-Service") → "User_Service" +sanitizeId("3rdParty") → "_3rdParty" + +// 2. Labels: Escape special characters with HTML entities +escapeLabel("Process(data)") → "Process#40;data#41;" +escapeLabel("Check {valid?}") → "Check #123;valid?#125;" + +// 3. Edge labels: Always use double quotes +// ✓ Correct +A -->|"calls(param)"| B + +// ✗ Wrong +A -->|calls(param)| B + +// 4. Subgraph titles: Use quoted labels +// ✓ Correct +subgraph ServiceLayer["Service Layer (Core)"] + +// ✗ Wrong +subgraph ServiceLayer[Service Layer (Core)] +``` + +### Diagram Format Examples + +**Architecture (graph TD)**: +```mermaid +graph TD + subgraph Presentation["Presentation Layer"] + API["API Gateway"] + CLI["CLI Interface"] + end + subgraph Business["Business Layer"] + SVC["Core Services"] + end + API --> SVC + CLI --> SVC +``` + +**Class Diagram (classDiagram)**: +```mermaid +classDiagram + class UserService { + +string name + +getUser(id) User + -validate() boolean + } + class Repository { + <> + +find(id) Entity + } + UserService --> Repository : uses +``` + +**Sequence Diagram (sequenceDiagram)**: +```mermaid +sequenceDiagram + participant C as Client + participant S as Server + participant D as Database + C->>S: request(data) + activate S + S->>D: query + D-->>S: result + S-->>C: response + deactivate S +``` + +**Flowchart (flowchart TD)**: +```mermaid +flowchart TD + START(["Start"]) + INPUT[/"Read input"/] + CHECK{"Valid?"} + PROCESS["Process data"] + OUTPUT[/"Write output"/] + END_(["End"]) + + START --> INPUT --> CHECK + CHECK -->|"Yes"| PROCESS --> OUTPUT --> END_ + CHECK -->|"No"| END_ +``` + +### Validation Checks + +The diagram generator validates: +- [ ] Diagram type declaration present +- [ ] No `undefined` values in output +- [ ] Special characters properly escaped +- [ ] No double arrow syntax errors +- [ ] Subgraph brackets balanced +- [ ] Node IDs are valid identifiers diff --git a/.claude/commands/workflow/docs/copyright.md b/.claude/commands/workflow/docs/copyright.md new file mode 100644 index 00000000..d020090f --- /dev/null +++ b/.claude/commands/workflow/docs/copyright.md @@ -0,0 +1,1265 @@ +--- +name: copyright +description: Multi-phase iterative software copyright documentation generator for CPCC compliance, produces design specification with Mermaid diagrams through code analysis +argument-hint: "[scope|path] [--name=软件名称] [--version=版本号]" +allowed-tools: Task(*), AskUserQuestion(*), Read(*), Bash(*), Glob(*), Grep(*), TodoWrite(*), Write(*) +--- + +# Workflow Copyright Command (/workflow:docs:copyright) + +## Overview + +**软件著作权设计说明书生成器** - 基于源代码深度分析,生成符合中国版权保护中心(CPCC)规范的无界面软件设计说明书。通过多阶段迭代和用户交互,确保文档内容准确、完整、合规。 + +**核心原则**: +- **基于代码分析**:所有内容严格来源于代码分析,杜绝臆测 +- **Mermaid 规范**:所有图表使用正确的 Mermaid 语法,特殊字符正确转义 +- **CPCC 合规**:严格遵循鉴别材料必备组成部分要求 +- **迭代优化**:通过多轮交互确保文档质量 + +## 文档结构(鉴别材料必备组成部分) + +| 章节 | 内容 | 图表类型 | +|------|------|----------| +| 1. 软件概述 | 背景、目标、运行环境、技术架构 | - | +| 2. 系统架构图 | 整体架构、模块关系、数据流 | `graph TD` | +| 3. 功能模块设计 | 功能分解、模块职责、交互关系 | `flowchart TD` | +| 4. 核心算法与流程 | 关键业务逻辑、算法实现、处理流程 | `flowchart TD` | +| 5. 数据结构设计 | 数据实体、关系、约束 | `classDiagram` | +| 6. 接口设计 | API 定义、参数、返回值 | `sequenceDiagram` | +| 7. 异常处理设计 | 错误处理、异常流程、恢复机制 | `flowchart TD` | + +## Execution Process + +``` +Input Parsing: + ├─ Parse: scope/path (required, source code location) + ├─ Parse: --name (software name, will prompt if not provided) + └─ Parse: --version (version number, will prompt if not provided) + +Phase 1: Project Discovery & Metadata Collection + ├─ Ask: Software name and version (if not specified) + ├─ Ask: Software category and primary function + ├─ Explore: Project structure and tech stack + └─ Output: project-metadata.json + +Phase 2: Deep Code Analysis (Parallel Agents) + ├─ Agent 1: Architecture analysis (modules, layers, dependencies) + ├─ Agent 2: Function analysis (features, workflows, algorithms) + ├─ Agent 3: Data structure analysis (entities, relationships) + ├─ Agent 4: Interface analysis (APIs, protocols) + └─ Output: analysis-{dimension}.json files + +Phase 3: Mermaid Diagram Generation + ├─ Generate: System architecture diagram (graph TD) + ├─ Generate: Function module diagrams (flowchart TD) + ├─ Generate: Core algorithm flowcharts (flowchart TD) + ├─ Generate: Class diagrams (classDiagram) + ├─ Generate: Sequence diagrams (sequenceDiagram) + └─ Output: diagrams/*.mmd + validation + +Phase 4: Document Assembly + ├─ Synthesize: Merge all analysis results + ├─ Generate: 软件设计说明书.md (draft) + ├─ Validate: CPCC compliance check + └─ Output: Present document to user + +Phase 5: Iterative Refinement (Discovery-Driven) + ├─ Extract: Gaps and ambiguities from analysis + ├─ Ask: Targeted questions based on findings + ├─ Update: Incremental document modification + └─ Loop: Until user satisfied or no more discoveries + +Finalize: + └─ Output: Final 软件设计说明书.md +``` + +## 5-Phase Execution + +### Phase 1: Project Discovery & Metadata Collection + +**Purpose**: Collect essential metadata and understand project structure + +**Step 1.1: Initialize TodoWrite** + +```javascript +TodoWrite([ + {content: "Phase 1: Project Discovery", status: "in_progress", activeForm: "Discovering project structure"}, + {content: "Phase 2: Deep Code Analysis", status: "pending", activeForm: "Analyzing source code"}, + {content: "Phase 3: Diagram Generation", status: "pending", activeForm: "Generating Mermaid diagrams"}, + {content: "Phase 4: Document Assembly", status: "pending", activeForm: "Assembling design document"}, + {content: "Phase 5: Iterative Refinement", status: "pending", activeForm: "Refining based on feedback"} +]) +``` + +**Step 1.2: Collect Software Metadata (if not specified)** + +```javascript +if (!name_specified || !version_specified) { + AskUserQuestion({ + questions: [ + { + question: "请提供软件的正式名称(将显示在页眉和文档标题中)", + header: "软件名称", + multiSelect: false, + options: [ + {label: "使用项目名称", description: `自动检测: ${detected_project_name}`}, + {label: "自定义名称", description: "输入自定义的软件名称"} + ] + }, + { + question: "请提供软件版本号(格式如 V1.0.0)", + header: "版本号", + multiSelect: false, + options: [ + {label: "V1.0.0", description: "初始版本"}, + {label: "使用 package.json 版本", description: `自动检测: ${detected_version}`}, + {label: "自定义版本", description: "输入自定义版本号"} + ] + } + ] + }); +} +``` + +**Step 1.3: Software Category Selection** + +```javascript +AskUserQuestion({ + questions: [{ + question: "请选择软件的主要类型(影响文档描述风格)", + header: "软件类型", + multiSelect: false, + options: [ + {label: "命令行工具 (CLI)", description: "无图形界面的命令行应用程序"}, + {label: "后端服务/API", description: "Web API、微服务、后台服务"}, + {label: "SDK/库", description: "供其他程序调用的开发工具包"}, + {label: "数据处理系统", description: "ETL、数据分析、批处理系统"}, + {label: "自动化脚本", description: "运维自动化、构建工具、脚本集合"} + ] + }] +}); +``` + +**Step 1.4: Explore Project Structure** + +```javascript +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: "Explore project structure", + prompt: ` +## Exploration Objective +分析项目结构,提取软件著作权文档所需的基础信息。 + +## Target Path +${scope_path} + +## Required Analysis +1. **技术栈识别**:编程语言、框架、主要依赖 +2. **目录结构**:源代码组织方式、模块划分 +3. **入口点识别**:主程序入口、命令行入口 +4. **配置文件**:环境配置、构建配置 +5. **文档线索**:README、注释中的功能描述 + +## Output +Write to: ${outputDir}/project-discovery.json +{ + "tech_stack": {...}, + "directory_structure": {...}, + "entry_points": [...], + "main_modules": [...], + "detected_features": [...] +} +` +}); +``` + +**Step 1.5: Store Project Metadata** + +```javascript +const projectMetadata = { + software_name: selected_name, + version: selected_version, + category: selected_category, + scope_path: scope_path, + tech_stack: discovery.tech_stack, + entry_points: discovery.entry_points, + main_modules: discovery.main_modules, + timestamp: new Date().toISOString() +}; + +Write(`${outputDir}/project-metadata.json`, JSON.stringify(projectMetadata, null, 2)); +``` + +**TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress + +--- + +### Phase 2: Deep Code Analysis (Parallel Agents) + +**Purpose**: Multi-dimensional code analysis for comprehensive understanding + +**Step 2.1: Launch Parallel Analysis Agents** + +```javascript +const analysisAgents = [ + { + dimension: "architecture", + focus: "系统架构分析", + prompt: ` +## 分析目标 +分析项目的系统架构,为"系统架构图"章节提供数据。 + +## 分析内容 +1. **分层结构**:识别代码的分层(如 Controller/Service/Repository) +2. **模块边界**:各模块的职责范围和边界 +3. **依赖关系**:模块间的依赖方向和类型 +4. **核心组件**:系统的核心组件及其作用 +5. **数据流向**:数据在各层之间的流动路径 + +## 输出格式 +{ + "layers": [{name, components, responsibility}], + "modules": [{name, path, responsibility, dependencies}], + "data_flow": [{from, to, data_type, description}], + "core_components": [{name, type, responsibility}], + "mermaid_hints": {nodes: [], edges: []} +} +` + }, + { + dimension: "functions", + focus: "功能模块分析", + prompt: ` +## 分析目标 +分析项目的功能模块,为"功能模块设计"章节提供数据。 + +## 分析内容 +1. **功能清单**:从代码中提取的所有功能点 +2. **功能分组**:按业务逻辑分组的功能模块 +3. **功能层级**:功能的父子关系和层级结构 +4. **模块交互**:功能模块之间的调用关系 +5. **关键流程**:主要业务流程的步骤分解 + +## 输出格式 +{ + "feature_list": [{id, name, description, module, entry_file}], + "feature_groups": [{group_name, features: []}], + "feature_hierarchy": {root: {children: [...]}}, + "interactions": [{caller, callee, trigger, description}], + "key_workflows": [{name, steps: [], files_involved}] +} +` + }, + { + dimension: "algorithms", + focus: "核心算法分析", + prompt: ` +## 分析目标 +分析项目的核心算法和业务逻辑,为"核心算法与流程"章节提供数据。 + +## 分析内容 +1. **核心算法**:识别关键算法(排序、搜索、加密、业务规则等) +2. **复杂逻辑**:圈复杂度高的函数/方法 +3. **处理流程**:核心业务的处理步骤 +4. **输入输出**:算法的输入参数和输出结果 +5. **边界条件**:特殊情况的处理逻辑 + +## 输出格式 +{ + "algorithms": [{ + name, file, line, + description, + complexity, + inputs: [{name, type, description}], + outputs: [{name, type, description}], + steps: [{step_num, description, code_ref}] + }], + "complex_functions": [{name, file, cyclomatic_complexity, description}], + "flowchart_hints": [{algorithm_name, nodes: [], edges: []}] +} +` + }, + { + dimension: "data_structures", + focus: "数据结构分析", + prompt: ` +## 分析目标 +分析项目的数据结构,为"数据结构设计"章节提供数据。 + +## 分析内容 +1. **数据实体**:类、接口、类型定义 +2. **属性字段**:实体的属性及其类型 +3. **实体关系**:继承、组合、关联关系 +4. **约束规则**:数据验证、业务约束 +5. **枚举常量**:枚举类型和常量定义 + +## 输出格式 +{ + "entities": [{ + name, file, type, // class/interface/type + properties: [{name, type, visibility, description}], + methods: [{name, params, return_type, visibility}] + }], + "relationships": [{ + from, to, + type, // inheritance/composition/association/dependency + cardinality, description + }], + "enums": [{name, values: [{name, value, description}]}], + "class_diagram_hints": {classes: [], relationships: []} +} +` + }, + { + dimension: "interfaces", + focus: "接口设计分析", + prompt: ` +## 分析目标 +分析项目的接口设计,为"接口设计"章节提供数据。 + +## 分析内容 +1. **API 端点**:HTTP API、RPC 接口、CLI 命令 +2. **参数定义**:输入参数的名称、类型、约束 +3. **返回值**:输出结果的格式和类型 +4. **调用协议**:同步/异步、请求/响应模式 +5. **接口分组**:按功能或资源分组 + +## 输出格式 +{ + "apis": [{ + name, path, method, // GET/POST/CLI/RPC + description, + parameters: [{name, type, required, description}], + response: {type, schema, description}, + category + }], + "protocols": [{name, type, description}], + "sequence_hints": [{scenario, actors: [], messages: []}] +} +` + }, + { + dimension: "exceptions", + focus: "异常处理分析", + prompt: ` +## 分析目标 +分析项目的异常处理机制,为"异常处理设计"章节提供数据。 + +## 分析内容 +1. **异常类型**:自定义异常类、错误码定义 +2. **捕获策略**:try-catch 的使用模式 +3. **错误传播**:异常的传播和转换链 +4. **恢复机制**:重试、降级、回滚策略 +5. **日志记录**:错误日志的记录方式 + +## 输出格式 +{ + "exception_types": [{name, parent, code, message, file}], + "error_codes": [{code, message, severity, category}], + "handling_patterns": [{pattern, locations: [], description}], + "recovery_strategies": [{strategy, trigger, action, files}], + "logging_approach": {framework, levels, format} +} +` + } +]; + +// Launch all agents in parallel +const analysisTasks = analysisAgents.map(agent => + Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: agent.focus, + prompt: ` +${agent.prompt} + +## Context +- **Scope Path**: ${scope_path} +- **Tech Stack**: ${projectMetadata.tech_stack} +- **Main Modules**: ${projectMetadata.main_modules.join(', ')} + +## Output File +Write to: ${outputDir}/analysis-${agent.dimension}.json +` + }) +); +``` + +**Step 2.2: Validate Analysis Results** + +```javascript +// Verify all analysis files created +const requiredAnalyses = ['architecture', 'functions', 'algorithms', 'data_structures', 'interfaces', 'exceptions']; +for (const dimension of requiredAnalyses) { + const filePath = `${outputDir}/analysis-${dimension}.json`; + if (!file_exists(filePath)) { + throw new Error(`Missing analysis: ${dimension}`); + } +} +``` + +**TodoWrite**: Mark Phase 2 completed, Phase 3 in_progress + +--- + +### Phase 3: Mermaid Diagram Generation + +**Purpose**: Generate all required diagrams with correct Mermaid syntax + +**Step 3.1: System Architecture Diagram** + +```javascript +const archAnalysis = JSON.parse(Read(`${outputDir}/analysis-architecture.json`)); + +// Generate Mermaid graph TD +function generateArchitectureDiagram(analysis) { + let mermaid = 'graph TD\n'; + + // Add subgraphs for layers + for (const layer of analysis.layers) { + mermaid += ` subgraph ${sanitizeId(layer.name)}["${escapeLabel(layer.name)}"]\n`; + for (const comp of layer.components) { + mermaid += ` ${sanitizeId(comp)}["${escapeLabel(comp)}"]\n`; + } + mermaid += ' end\n'; + } + + // Add edges for data flow + for (const flow of analysis.data_flow) { + mermaid += ` ${sanitizeId(flow.from)} -->|"${escapeLabel(flow.description)}"| ${sanitizeId(flow.to)}\n`; + } + + return mermaid; +} + +// Helper: Escape special characters in labels +function escapeLabel(text) { + return text.replace(/["(){}[\]<>]/g, char => `#${char.charCodeAt(0)};`); +} + +const archDiagram = generateArchitectureDiagram(archAnalysis); +Write(`${outputDir}/diagrams/architecture.mmd`, archDiagram); +``` + +**Step 3.2: Function Module Diagrams** + +```javascript +const funcAnalysis = JSON.parse(Read(`${outputDir}/analysis-functions.json`)); + +function generateFunctionDiagram(analysis) { + let mermaid = 'flowchart TD\n'; + + // Root node + mermaid += ` ROOT["${escapeLabel(projectMetadata.software_name)}"]\n`; + + // Feature groups as subgraphs + for (const group of analysis.feature_groups) { + mermaid += ` subgraph ${sanitizeId(group.group_name)}["${escapeLabel(group.group_name)}"]\n`; + for (const feature of group.features) { + mermaid += ` ${sanitizeId(feature.id)}["${escapeLabel(feature.name)}"]\n`; + } + mermaid += ' end\n'; + mermaid += ` ROOT --> ${sanitizeId(group.group_name)}\n`; + } + + return mermaid; +} + +const funcDiagram = generateFunctionDiagram(funcAnalysis); +Write(`${outputDir}/diagrams/functions.mmd`, funcDiagram); +``` + +**Step 3.3: Algorithm Flowcharts** + +```javascript +const algoAnalysis = JSON.parse(Read(`${outputDir}/analysis-algorithms.json`)); + +function generateAlgorithmFlowchart(algorithm) { + let mermaid = 'flowchart TD\n'; + + // Start node + mermaid += ` START(["开始"])\n`; + + // Input nodes + for (const input of algorithm.inputs) { + mermaid += ` INPUT_${sanitizeId(input.name)}[/"${escapeLabel(input.name)}: ${escapeLabel(input.type)}"/]\n`; + } + + // Process steps + let prevNode = 'START'; + for (const step of algorithm.steps) { + const nodeId = `STEP_${step.step_num}`; + mermaid += ` ${nodeId}["${escapeLabel(step.description)}"]\n`; + mermaid += ` ${prevNode} --> ${nodeId}\n`; + prevNode = nodeId; + } + + // Output and end + mermaid += ` OUTPUT[/"输出结果"/]\n`; + mermaid += ` ${prevNode} --> OUTPUT\n`; + mermaid += ` END_(["结束"])\n`; + mermaid += ` OUTPUT --> END_\n`; + + return mermaid; +} + +// Generate flowchart for each core algorithm +for (const algo of algoAnalysis.algorithms.slice(0, 5)) { // Top 5 algorithms + const flowchart = generateAlgorithmFlowchart(algo); + Write(`${outputDir}/diagrams/algorithm-${sanitizeId(algo.name)}.mmd`, flowchart); +} +``` + +**Step 3.4: Class Diagrams** + +```javascript +const dataAnalysis = JSON.parse(Read(`${outputDir}/analysis-data_structures.json`)); + +function generateClassDiagram(analysis) { + let mermaid = 'classDiagram\n'; + + // Classes + for (const entity of analysis.entities) { + mermaid += ` class ${sanitizeId(entity.name)} {\n`; + + // Properties + for (const prop of entity.properties) { + const visibility = {public: '+', private: '-', protected: '#'}[prop.visibility] || '+'; + mermaid += ` ${visibility}${prop.type} ${prop.name}\n`; + } + + // Methods + for (const method of entity.methods) { + const visibility = {public: '+', private: '-', protected: '#'}[method.visibility] || '+'; + mermaid += ` ${visibility}${method.name}(${method.params}) ${method.return_type}\n`; + } + + mermaid += ' }\n'; + } + + // Relationships + for (const rel of analysis.relationships) { + const arrows = { + inheritance: '--|>', + composition: '*--', + aggregation: 'o--', + association: '-->', + dependency: '..>' + }; + const arrow = arrows[rel.type] || '-->'; + mermaid += ` ${sanitizeId(rel.from)} ${arrow} ${sanitizeId(rel.to)} : ${escapeLabel(rel.description || rel.type)}\n`; + } + + return mermaid; +} + +const classDiagram = generateClassDiagram(dataAnalysis); +Write(`${outputDir}/diagrams/class-diagram.mmd`, classDiagram); +``` + +**Step 3.5: Sequence Diagrams** + +```javascript +const interfaceAnalysis = JSON.parse(Read(`${outputDir}/analysis-interfaces.json`)); + +function generateSequenceDiagram(scenario) { + let mermaid = 'sequenceDiagram\n'; + + // Participants + for (const actor of scenario.actors) { + mermaid += ` participant ${sanitizeId(actor.id)} as ${escapeLabel(actor.name)}\n`; + } + + // Messages + for (const msg of scenario.messages) { + const arrow = msg.type === 'async' ? '-)' : '->>'; + mermaid += ` ${sanitizeId(msg.from)}${arrow}${sanitizeId(msg.to)}: ${escapeLabel(msg.description)}\n`; + } + + return mermaid; +} + +// Generate sequence diagram for each key scenario +for (const scenario of interfaceAnalysis.sequence_hints || []) { + const seqDiagram = generateSequenceDiagram(scenario); + Write(`${outputDir}/diagrams/sequence-${sanitizeId(scenario.scenario)}.mmd`, seqDiagram); +} +``` + +**Step 3.6: Validate Mermaid Syntax** + +```javascript +// Validate all generated diagrams +const diagramFiles = Glob(`${outputDir}/diagrams/*.mmd`); +const validationResults = []; + +for (const file of diagramFiles) { + const content = Read(file); + const issues = validateMermaidSyntax(content); + validationResults.push({ + file: file, + valid: issues.length === 0, + issues: issues + }); +} + +Write(`${outputDir}/diagrams/validation-report.json`, JSON.stringify(validationResults, null, 2)); +``` + +**TodoWrite**: Mark Phase 3 completed, Phase 4 in_progress + +--- + +### Phase 4: Document Assembly + +**Purpose**: Assemble all analysis and diagrams into final document + +**Step 4.1: Load All Analysis Data** + +```javascript +const metadata = JSON.parse(Read(`${outputDir}/project-metadata.json`)); +const analyses = { + architecture: JSON.parse(Read(`${outputDir}/analysis-architecture.json`)), + functions: JSON.parse(Read(`${outputDir}/analysis-functions.json`)), + algorithms: JSON.parse(Read(`${outputDir}/analysis-algorithms.json`)), + data_structures: JSON.parse(Read(`${outputDir}/analysis-data_structures.json`)), + interfaces: JSON.parse(Read(`${outputDir}/analysis-interfaces.json`)), + exceptions: JSON.parse(Read(`${outputDir}/analysis-exceptions.json`)) +}; +const diagrams = loadAllDiagrams(`${outputDir}/diagrams/`); +``` + +**Step 4.2: Generate Document Header** + +```javascript +const header = ` + + + +# ${metadata.software_name} 软件设计说明书 + +**版本号**:${metadata.version} +**生成日期**:${new Date().toLocaleDateString('zh-CN')} +**文档性质**:软件著作权鉴别材料 + +--- + +`; +``` + +**Step 4.3: Generate Each Section** + +```javascript +function generateSection1_Overview(metadata, analyses) { + return ` +## 1. 软件概述 + +### 1.1 软件背景与用途 + +${metadata.software_name}是一款${metadata.category}软件,主要用于${inferPurpose(analyses)}。 + +本软件基于${metadata.tech_stack.language}语言开发,采用${metadata.tech_stack.framework || '自研架构'}实现核心功能。 + +### 1.2 开发目标与特点 + +**开发目标**: +${generateObjectives(analyses.functions)} + +**技术特点**: +${generateFeatures(analyses.architecture)} + +### 1.3 运行环境与技术架构 + +**运行环境**: +- 操作系统:${metadata.tech_stack.os || '跨平台'} +- 运行时:${metadata.tech_stack.runtime} +- 依赖环境:${metadata.tech_stack.dependencies?.join('、') || '无特殊依赖'} + +**技术架构**: +- 架构模式:${analyses.architecture.pattern || '模块化架构'} +- 核心框架:${metadata.tech_stack.framework || '无'} +- 主要技术栈:${metadata.tech_stack.main_technologies?.join('、') || metadata.tech_stack.language} + +`; +} + +function generateSection2_Architecture(analyses, diagrams) { + return ` +## 2. 系统架构图 + +本章节展示${metadata.software_name}的整体系统架构,包括各主要模块之间的关系与核心数据流。 + +\`\`\`mermaid +${diagrams.architecture} +\`\`\` + +**图2-1 系统架构图** + +### 架构说明 + +${generateArchitectureDescription(analyses.architecture)} + +**核心模块说明**: + +${analyses.architecture.modules.map((m, i) => + `${i + 1}. **${m.name}**:${m.responsibility}` +).join('\n')} + +`; +} + +function generateSection3_FunctionModules(analyses, diagrams) { + return ` +## 3. 功能模块设计 + +本章节详细描述各功能模块的设计与职责划分。 + +\`\`\`mermaid +${diagrams.functions} +\`\`\` + +**图3-1 功能模块结构图** + +### 3.1 功能模块列表 + +${analyses.functions.feature_groups.map((group, gi) => ` +#### 3.1.${gi + 1} ${group.group_name} + +${group.features.map((f, fi) => + `- **${f.name}**:${f.description}` +).join('\n')} +`).join('\n')} + +### 3.2 模块交互关系 + +${generateInteractionDescription(analyses.functions.interactions)} + +`; +} + +function generateSection4_Algorithms(analyses, diagrams) { + return ` +## 4. 核心算法与流程 + +本章节描述软件中的核心算法实现与关键业务处理流程。 + +${analyses.algorithms.algorithms.slice(0, 5).map((algo, i) => ` +### 4.${i + 1} ${algo.name} + +**功能描述**:${algo.description} + +**输入参数**: +${algo.inputs.map(input => `- \`${input.name}\`(${input.type}):${input.description}`).join('\n')} + +**输出结果**: +${algo.outputs.map(output => `- \`${output.name}\`(${output.type}):${output.description}`).join('\n')} + +**处理流程**: + +\`\`\`mermaid +${diagrams[`algorithm-${sanitizeId(algo.name)}`] || generateSimpleFlowchart(algo)} +\`\`\` + +**图4-${i + 1} ${algo.name}流程图** + +**算法步骤说明**: + +${algo.steps.map((step, si) => + `${si + 1}. ${step.description}` +).join('\n')} + +`).join('\n')} +`; +} + +function generateSection5_DataStructures(analyses, diagrams) { + return ` +## 5. 数据结构设计 + +本章节描述软件中使用的主要数据实体及其关系。 + +\`\`\`mermaid +${diagrams['class-diagram']} +\`\`\` + +**图5-1 数据结构类图** + +### 5.1 主要数据实体 + +${analyses.data_structures.entities.map((entity, i) => ` +#### 5.1.${i + 1} ${entity.name} + +**类型**:${entity.type} +**文件位置**:\`${entity.file}\` + +**属性列表**: + +| 属性名 | 类型 | 可见性 | 说明 | +|--------|------|--------|------| +${entity.properties.map(p => + `| ${p.name} | ${p.type} | ${p.visibility} | ${p.description || '-'} |` +).join('\n')} + +`).join('\n')} + +### 5.2 实体关系说明 + +${analyses.data_structures.relationships.map((rel, i) => + `${i + 1}. **${rel.from}** ${rel.type} **${rel.to}**:${rel.description || '关联关系'}` +).join('\n')} + +`; +} + +function generateSection6_Interfaces(analyses, diagrams) { + return ` +## 6. 接口设计 + +本章节描述软件对外提供的接口定义。 + +${diagrams.sequence ? ` +\`\`\`mermaid +${diagrams.sequence} +\`\`\` + +**图6-1 接口调用时序图** +` : ''} + +### 6.1 接口列表 + +${analyses.interfaces.apis.map((api, i) => ` +#### 6.1.${i + 1} ${api.name} + +- **路径/命令**:\`${api.path}\` +- **方法类型**:${api.method} +- **功能描述**:${api.description} + +**请求参数**: + +| 参数名 | 类型 | 必填 | 说明 | +|--------|------|------|------| +${api.parameters.map(p => + `| ${p.name} | ${p.type} | ${p.required ? '是' : '否'} | ${p.description} |` +).join('\n')} + +**返回结果**: +- 类型:${api.response.type} +- 说明:${api.response.description} + +`).join('\n')} +`; +} + +function generateSection7_Exceptions(analyses) { + return ` +## 7. 异常处理设计 + +本章节描述软件的异常处理机制与错误恢复策略。 + +### 7.1 异常类型定义 + +${analyses.exceptions.exception_types.map((ex, i) => ` +#### 7.1.${i + 1} ${ex.name} + +- **错误码**:\`${ex.code || 'N/A'}\` +- **错误信息**:${ex.message} +- **父类**:${ex.parent || '基础异常类'} +- **定义位置**:\`${ex.file}\` +`).join('\n')} + +### 7.2 错误码说明 + +| 错误码 | 错误信息 | 严重程度 | 类别 | +|--------|----------|----------|------| +${analyses.exceptions.error_codes.map(e => + `| ${e.code} | ${e.message} | ${e.severity} | ${e.category} |` +).join('\n')} + +### 7.3 异常处理策略 + +${analyses.exceptions.handling_patterns.map((pattern, i) => ` +**${i + 1}. ${pattern.pattern}** + +${pattern.description} + +应用位置:${pattern.locations.join('、')} +`).join('\n')} + +### 7.4 恢复机制 + +${analyses.exceptions.recovery_strategies.map((strategy, i) => + `${i + 1}. **${strategy.strategy}**:${strategy.action}(触发条件:${strategy.trigger})` +).join('\n')} + +`; +} +``` + +**Step 4.4: Assemble Final Document** + +```javascript +const documentContent = [ + header, + generateSection1_Overview(metadata, analyses), + generateSection2_Architecture(analyses, diagrams), + generateSection3_FunctionModules(analyses, diagrams), + generateSection4_Algorithms(analyses, diagrams), + generateSection5_DataStructures(analyses, diagrams), + generateSection6_Interfaces(analyses, diagrams), + generateSection7_Exceptions(analyses) +].join('\n'); + +const documentPath = `${outputDir}/${metadata.software_name}-软件设计说明书.md`; +Write(documentPath, documentContent); +``` + +**Step 4.5: CPCC Compliance Check** + +```javascript +function validateCPCCCompliance(document, analyses) { + const checks = [ + {name: "软件概述完整性", pass: document.includes("## 1. 软件概述")}, + {name: "系统架构图存在", pass: document.includes("图2-1 系统架构图")}, + {name: "功能模块设计完整", pass: document.includes("## 3. 功能模块设计")}, + {name: "核心算法描述", pass: document.includes("## 4. 核心算法与流程")}, + {name: "数据结构设计", pass: document.includes("## 5. 数据结构设计")}, + {name: "接口设计说明", pass: document.includes("## 6. 接口设计")}, + {name: "异常处理设计", pass: document.includes("## 7. 异常处理设计")}, + {name: "Mermaid图表语法", pass: !document.includes("mermaid error")}, + {name: "页眉信息", pass: document.includes("页眉")}, + {name: "页码说明", pass: document.includes("页码")} + ]; + + return { + passed: checks.filter(c => c.pass).length, + total: checks.length, + details: checks + }; +} + +const compliance = validateCPCCCompliance(documentContent, analyses); +console.log(`CPCC 合规检查: ${compliance.passed}/${compliance.total} 项通过`); +``` + +**TodoWrite**: Mark Phase 4 completed, Phase 5 in_progress + +--- + +### Phase 5: Iterative Refinement (Discovery-Driven) + +**Purpose**: Refine document based on analysis gaps and user feedback + +**Step 5.1: Extract Document Gaps** + +```javascript +function extractDocumentGaps(analyses, document) { + return { + // Missing descriptions + missingDescriptions: analyses.functions.features + .filter(f => !f.description || f.description.length < 20), + + // Low confidence analyses + lowConfidenceAreas: Object.entries(analyses) + .flatMap(([dim, data]) => + (data.confidence_scores || []).filter(s => s.score < 0.7) + ), + + // Complex areas needing clarification + complexAreas: analyses.algorithms.algorithms + .filter(a => a.complexity === 'high' && a.steps.length < 3), + + // Incomplete relationships + incompleteRelationships: analyses.data_structures.relationships + .filter(r => !r.description), + + // Missing exception handling + missingExceptionHandling: analyses.exceptions.exception_types + .filter(e => !e.message || e.message === 'Unknown') + }; +} + +const gaps = extractDocumentGaps(analyses, documentContent); +``` + +**Step 5.2: Generate Targeted Questions** + +```javascript +function buildRefinementQuestions(gaps, metadata) { + const questions = []; + + // Question about missing feature descriptions + if (gaps.missingDescriptions.length > 0) { + questions.push({ + question: `以下功能缺少详细描述,请选择需要补充说明的功能:`, + header: "功能描述", + multiSelect: true, + options: gaps.missingDescriptions.slice(0, 4).map(f => ({ + label: f.name, + description: `文件: ${f.entry_file} - 当前描述不完整` + })) + }); + } + + // Question about complex algorithms + if (gaps.complexAreas.length > 0) { + questions.push({ + question: `发现 ${gaps.complexAreas.length} 个复杂算法的流程描述不够详细,是否需要深入分析?`, + header: "算法详解", + multiSelect: false, + options: [ + {label: "是,详细分析所有", description: "为所有复杂算法生成详细流程图"}, + {label: "选择性分析", description: "仅分析最核心的算法"}, + {label: "保持现状", description: "当前描述已足够"} + ] + }); + } + + // Question about data relationships + if (gaps.incompleteRelationships.length > 0) { + questions.push({ + question: `发现 ${gaps.incompleteRelationships.length} 个数据实体关系缺少说明,是否补充?`, + header: "数据关系", + multiSelect: false, + options: [ + {label: "自动推断并补充", description: "基于代码分析自动补充关系说明"}, + {label: "跳过", description: "保持当前状态"} + ] + }); + } + + // Final action question + questions.push({ + question: "如何处理当前文档?", + header: "操作", + multiSelect: false, + options: [ + {label: "继续优化", description: "应用上述选择并继续检查"}, + {label: "完成文档", description: "当前文档已满足需求,生成最终版本"}, + {label: "调整范围", description: "修改分析范围或重点"} + ] + }); + + return questions.slice(0, 4); +} + +const refinementQuestions = buildRefinementQuestions(gaps, metadata); +AskUserQuestion({questions: refinementQuestions}); +``` + +**Step 5.3: Apply Refinements** + +```javascript +async function applyRefinements(responses, gaps, outputDir) { + const updates = []; + + if (responses.功能描述) { + // Re-analyze selected features with deeper exploration + for (const feature of responses.功能描述) { + const deepAnalysis = await Task({ + subagent_type: "cli-explore-agent", + prompt: `深入分析功能 ${feature.name},提供详细描述...` + }); + updates.push({type: 'feature_description', data: deepAnalysis}); + } + } + + if (responses.算法详解 === "是,详细分析所有") { + // Generate detailed flowcharts for complex algorithms + for (const algo of gaps.complexAreas) { + const detailedFlow = await analyzeAlgorithmInDepth(algo); + updates.push({type: 'algorithm_flowchart', data: detailedFlow}); + } + } + + if (responses.数据关系 === "自动推断并补充") { + // Infer relationship descriptions from code + const inferences = await inferRelationshipDescriptions(gaps.incompleteRelationships); + updates.push({type: 'relationship_descriptions', data: inferences}); + } + + return updates; +} + +const updates = await applyRefinements(user_responses, gaps, outputDir); +``` + +**Step 5.4: Regenerate Affected Sections** + +```javascript +// Update document with refinements +for (const update of updates) { + switch (update.type) { + case 'feature_description': + analyses.functions = mergeFeatureDescriptions(analyses.functions, update.data); + break; + case 'algorithm_flowchart': + diagrams[`algorithm-${update.data.name}`] = update.data.flowchart; + break; + case 'relationship_descriptions': + analyses.data_structures.relationships = update.data; + break; + } +} + +// Regenerate document +const updatedDocument = regenerateDocument(metadata, analyses, diagrams); +Write(documentPath, updatedDocument); +Write(`${outputDir}/iterations/v${iteration_count}.md`, documentContent); // Archive +``` + +**Step 5.5: Loop or Finalize** + +```javascript +if (user_responses.操作 === "完成文档") { + finalized = true; +} else if (user_responses.操作 === "调整范围") { + goto Phase1_Step1_3; +} else { + iteration_count++; + if (iteration_count > 5) { + console.log("已达到最大迭代次数,建议完成文档"); + } + goto Step5.1; +} +``` + +--- + +### Finalization + +**Step 6.1: Generate Final Document** + +```javascript +const finalDocument = ` +${header} + +${documentContent} + +--- + +**文档生成信息** + +- 生成工具:/workflow:docs:copyright +- 分析范围:${metadata.scope_path} +- 迭代次数:${iteration_count} +- 生成时间:${new Date().toISOString()} + +--- + +*本文档基于源代码自动分析生成,所有描述均来源于代码实现。* +`; + +Write(documentPath, finalDocument); +``` + +**Step 6.2: Output Summary** + +```markdown +## 软件著作权设计说明书生成完成 + +**软件名称**:${metadata.software_name} +**版本号**:${metadata.version} +**文档路径**:${documentPath} + +### 文档统计 +- 总章节数:7 +- Mermaid 图表数:${Object.keys(diagrams).length} +- 功能模块数:${analyses.functions.feature_list.length} +- 数据实体数:${analyses.data_structures.entities.length} +- 接口数量:${analyses.interfaces.apis.length} + +### CPCC 合规检查 +${compliance.details.map(c => `- [${c.pass ? '✓' : '✗'}] ${c.name}`).join('\n')} + +### 后续步骤 +1. 检查生成的 Mermaid 图表是否正确渲染 +2. 补充任何需要人工说明的细节 +3. 将文档转换为 PDF 格式(A4 纵向) +4. 确认页眉、页码格式符合要求 +``` + +**TodoWrite**: Mark all phases completed + +--- + +## Mermaid 语法规范 + +**关键规则**(确保图表正确渲染): + +```javascript +// 1. 特殊字符转义 - 使用双引号包裹 +// 正确 +A["处理(数据)"] --> B["验证{结果}"] + +// 错误 +A[处理(数据)] --> B[验证{结果}] + +// 2. 边标签转义 +// 正确 +A -->|"调用(参数)"| B + +// 错误 +A -->|调用(参数)| B + +// 3. 节点 ID 规范 - 仅使用字母数字下划线 +// 正确 +UserService --> AuthModule + +// 错误 +User-Service --> Auth.Module + +// 4. 子图标题 +// 正确 +subgraph ServiceLayer["服务层(核心)"] + +// 错误 +subgraph ServiceLayer[服务层(核心)] +``` + +## Usage Examples + +```bash +# 交互式生成(引导输入所有信息) +/workflow:docs:copyright src/ + +# 指定软件名称和版本 +/workflow:docs:copyright src/ --name="智能数据分析系统" --version="V1.0.0" + +# 分析特定模块 +/workflow:docs:copyright src/core --name="核心处理引擎" --version="V2.1.0" +``` + +## Output Structure + +``` +.workflow/.scratchpad/copyright-{timestamp}/ +├── project-metadata.json # 软件元数据 +├── project-discovery.json # 项目发现结果 +├── analysis-architecture.json # 架构分析 +├── analysis-functions.json # 功能分析 +├── analysis-algorithms.json # 算法分析 +├── analysis-data_structures.json # 数据结构分析 +├── analysis-interfaces.json # 接口分析 +├── analysis-exceptions.json # 异常处理分析 +├── diagrams/ # Mermaid 图表 +│ ├── architecture.mmd +│ ├── functions.mmd +│ ├── class-diagram.mmd +│ ├── algorithm-*.mmd +│ └── sequence-*.mmd +├── iterations/ # 迭代版本 +│ ├── v1.md +│ └── ... +└── {软件名称}-软件设计说明书.md # 最终文档 +``` + +## Related Commands + +**Follow-up Commands**: +- `/workflow:analyze` - 更深入的项目分析 +- `/memory:docs` - 生成技术文档 + +**Alternative Commands**: +- `/workflow:docs:copyright --lite` - 简化版(仅生成必要章节) diff --git a/.claude/skills/_shared/mermaid-utils.md b/.claude/skills/_shared/mermaid-utils.md new file mode 100644 index 00000000..0db4f9e9 --- /dev/null +++ b/.claude/skills/_shared/mermaid-utils.md @@ -0,0 +1,584 @@ +# Mermaid Utilities Library + +Shared utilities for generating and validating Mermaid diagrams across all analysis skills. + +## Sanitization Functions + +### sanitizeId + +Convert any text to a valid Mermaid node ID. + +```javascript +/** + * Sanitize text to valid Mermaid node ID + * - Only alphanumeric and underscore allowed + * - Cannot start with number + * - Truncates to 50 chars max + * + * @param {string} text - Input text + * @returns {string} - Valid Mermaid ID + */ +function sanitizeId(text) { + if (!text) return '_empty'; + return text + .replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, '_') // Allow Chinese chars + .replace(/^[0-9]/, '_$&') // Prefix number with _ + .replace(/_+/g, '_') // Collapse multiple _ + .substring(0, 50); // Limit length +} + +// Examples: +// sanitizeId("User-Service") → "User_Service" +// sanitizeId("3rdParty") → "_3rdParty" +// sanitizeId("用户服务") → "用户服务" +``` + +### escapeLabel + +Escape special characters for Mermaid labels. + +```javascript +/** + * Escape special characters in Mermaid labels + * Uses HTML entity encoding for problematic chars + * + * @param {string} text - Label text + * @returns {string} - Escaped label + */ +function escapeLabel(text) { + if (!text) return ''; + return text + .replace(/"/g, "'") // Avoid quote issues + .replace(/\(/g, '#40;') // ( + .replace(/\)/g, '#41;') // ) + .replace(/\{/g, '#123;') // { + .replace(/\}/g, '#125;') // } + .replace(/\[/g, '#91;') // [ + .replace(/\]/g, '#93;') // ] + .replace(//g, '#62;') // > + .replace(/\|/g, '#124;') // | + .substring(0, 80); // Limit length +} + +// Examples: +// escapeLabel("Process(data)") → "Process#40;data#41;" +// escapeLabel("Check {valid?}") → "Check #123;valid?#125;" +``` + +### sanitizeType + +Sanitize type names for class diagrams. + +```javascript +/** + * Sanitize type names for Mermaid classDiagram + * Removes generics syntax that causes issues + * + * @param {string} type - Type name + * @returns {string} - Sanitized type + */ +function sanitizeType(type) { + if (!type) return 'any'; + return type + .replace(/<[^>]*>/g, '') // Remove generics + .replace(/\|/g, ' or ') // Union types + .replace(/&/g, ' and ') // Intersection types + .replace(/\[\]/g, 'Array') // Array notation + .substring(0, 30); +} + +// Examples: +// sanitizeType("Array") → "Array" +// sanitizeType("string | number") → "string or number" +``` + +## Diagram Generation Functions + +### generateFlowchartNode + +Generate a flowchart node with proper shape. + +```javascript +/** + * Generate flowchart node with shape + * + * @param {string} id - Node ID + * @param {string} label - Display label + * @param {string} type - Node type: start|end|process|decision|io|subroutine + * @returns {string} - Mermaid node definition + */ +function generateFlowchartNode(id, label, type = 'process') { + const safeId = sanitizeId(id); + const safeLabel = escapeLabel(label); + + const shapes = { + start: `${safeId}(["${safeLabel}"])`, // Stadium shape + end: `${safeId}(["${safeLabel}"])`, // Stadium shape + process: `${safeId}["${safeLabel}"]`, // Rectangle + decision: `${safeId}{"${safeLabel}"}`, // Diamond + io: `${safeId}[/"${safeLabel}"/]`, // Parallelogram + subroutine: `${safeId}[["${safeLabel}"]]`, // Subroutine + database: `${safeId}[("${safeLabel}")]`, // Cylinder + manual: `${safeId}[/"${safeLabel}"\\]` // Trapezoid + }; + + return shapes[type] || shapes.process; +} +``` + +### generateFlowchartEdge + +Generate a flowchart edge with optional label. + +```javascript +/** + * Generate flowchart edge + * + * @param {string} from - Source node ID + * @param {string} to - Target node ID + * @param {string} label - Edge label (optional) + * @param {string} style - Edge style: solid|dashed|thick + * @returns {string} - Mermaid edge definition + */ +function generateFlowchartEdge(from, to, label = '', style = 'solid') { + const safeFrom = sanitizeId(from); + const safeTo = sanitizeId(to); + const safeLabel = label ? `|"${escapeLabel(label)}"|` : ''; + + const arrows = { + solid: '-->', + dashed: '-.->', + thick: '==>' + }; + + const arrow = arrows[style] || arrows.solid; + return ` ${safeFrom} ${arrow}${safeLabel} ${safeTo}`; +} +``` + +### generateAlgorithmFlowchart (Enhanced) + +Generate algorithm flowchart with branch/loop support. + +```javascript +/** + * Generate algorithm flowchart with decision support + * + * @param {Object} algorithm - Algorithm definition + * - name: Algorithm name + * - inputs: [{name, type}] + * - outputs: [{name, type}] + * - steps: [{id, description, type, next: [id], conditions: [text]}] + * @returns {string} - Complete Mermaid flowchart + */ +function generateAlgorithmFlowchart(algorithm) { + let mermaid = 'flowchart TD\n'; + + // Start node + mermaid += ` START(["开始: ${escapeLabel(algorithm.name)}"])\n`; + + // Input node (if has inputs) + if (algorithm.inputs?.length > 0) { + const inputList = algorithm.inputs.map(i => `${i.name}: ${i.type}`).join(', '); + mermaid += ` INPUT[/"输入: ${escapeLabel(inputList)}"/]\n`; + mermaid += ` START --> INPUT\n`; + } + + // Process nodes + const steps = algorithm.steps || []; + for (const step of steps) { + const nodeId = sanitizeId(step.id || `STEP_${step.step_num}`); + + if (step.type === 'decision') { + mermaid += ` ${nodeId}{"${escapeLabel(step.description)}"}\n`; + } else if (step.type === 'io') { + mermaid += ` ${nodeId}[/"${escapeLabel(step.description)}"/]\n`; + } else if (step.type === 'loop_start') { + mermaid += ` ${nodeId}[["循环: ${escapeLabel(step.description)}"]]\n`; + } else { + mermaid += ` ${nodeId}["${escapeLabel(step.description)}"]\n`; + } + } + + // Output node + const outputDesc = algorithm.outputs?.map(o => o.name).join(', ') || '结果'; + mermaid += ` OUTPUT[/"输出: ${escapeLabel(outputDesc)}"/]\n`; + mermaid += ` END_(["结束"])\n`; + + // Connect first step to input/start + if (steps.length > 0) { + const firstStep = sanitizeId(steps[0].id || 'STEP_1'); + if (algorithm.inputs?.length > 0) { + mermaid += ` INPUT --> ${firstStep}\n`; + } else { + mermaid += ` START --> ${firstStep}\n`; + } + } + + // Connect steps based on next array + for (const step of steps) { + const nodeId = sanitizeId(step.id || `STEP_${step.step_num}`); + + if (step.next && step.next.length > 0) { + step.next.forEach((nextId, index) => { + const safeNextId = sanitizeId(nextId); + const condition = step.conditions?.[index]; + + if (condition) { + mermaid += ` ${nodeId} -->|"${escapeLabel(condition)}"| ${safeNextId}\n`; + } else { + mermaid += ` ${nodeId} --> ${safeNextId}\n`; + } + }); + } else if (!step.type?.includes('end')) { + // Default: connect to next step or output + const stepIndex = steps.indexOf(step); + if (stepIndex < steps.length - 1) { + const nextStep = sanitizeId(steps[stepIndex + 1].id || `STEP_${stepIndex + 2}`); + mermaid += ` ${nodeId} --> ${nextStep}\n`; + } else { + mermaid += ` ${nodeId} --> OUTPUT\n`; + } + } + } + + // Connect output to end + mermaid += ` OUTPUT --> END_\n`; + + return mermaid; +} +``` + +## Diagram Validation + +### validateMermaidSyntax + +Comprehensive Mermaid syntax validation. + +```javascript +/** + * Validate Mermaid diagram syntax + * + * @param {string} content - Mermaid diagram content + * @returns {Object} - {valid: boolean, issues: string[]} + */ +function validateMermaidSyntax(content) { + const issues = []; + + // Check 1: Diagram type declaration + if (!content.match(/^(graph|flowchart|classDiagram|sequenceDiagram|stateDiagram|erDiagram|gantt|pie|mindmap)/m)) { + issues.push('Missing diagram type declaration'); + } + + // Check 2: Undefined values + if (content.includes('undefined') || content.includes('null')) { + issues.push('Contains undefined/null values'); + } + + // Check 3: Invalid arrow syntax + if (content.match(/-->\s*-->/)) { + issues.push('Double arrow syntax error'); + } + + // Check 4: Unescaped special characters in labels + const labelMatches = content.match(/\["[^"]*[(){}[\]<>][^"]*"\]/g); + if (labelMatches?.some(m => !m.includes('#'))) { + issues.push('Unescaped special characters in labels'); + } + + // Check 5: Node ID starts with number + if (content.match(/\n\s*[0-9][a-zA-Z0-9_]*[\[\({]/)) { + issues.push('Node ID cannot start with number'); + } + + // Check 6: Nested subgraph syntax error + if (content.match(/subgraph\s+\S+\s*\n[^e]*subgraph/)) { + // This is actually valid, only flag if brackets don't match + const subgraphCount = (content.match(/subgraph/g) || []).length; + const endCount = (content.match(/\bend\b/g) || []).length; + if (subgraphCount > endCount) { + issues.push('Unbalanced subgraph/end blocks'); + } + } + + // Check 7: Invalid arrow type for diagram type + const diagramType = content.match(/^(graph|flowchart|classDiagram|sequenceDiagram)/m)?.[1]; + if (diagramType === 'classDiagram' && content.includes('-->|')) { + issues.push('Invalid edge label syntax for classDiagram'); + } + + // Check 8: Empty node labels + if (content.match(/\[""\]|\{\}|\(\)/)) { + issues.push('Empty node labels detected'); + } + + // Check 9: Reserved keywords as IDs + const reserved = ['end', 'graph', 'subgraph', 'direction', 'class', 'click']; + for (const keyword of reserved) { + const pattern = new RegExp(`\\n\\s*${keyword}\\s*[\\[\\(\\{]`, 'i'); + if (content.match(pattern)) { + issues.push(`Reserved keyword "${keyword}" used as node ID`); + } + } + + // Check 10: Line length (Mermaid has issues with very long lines) + const lines = content.split('\n'); + for (let i = 0; i < lines.length; i++) { + if (lines[i].length > 500) { + issues.push(`Line ${i + 1} exceeds 500 characters`); + } + } + + return { + valid: issues.length === 0, + issues + }; +} +``` + +### validateDiagramDirectory + +Validate all diagrams in a directory. + +```javascript +/** + * Validate all Mermaid diagrams in directory + * + * @param {string} diagramDir - Path to diagrams directory + * @returns {Object[]} - Array of {file, valid, issues} + */ +function validateDiagramDirectory(diagramDir) { + const files = Glob(`${diagramDir}/*.mmd`); + const results = []; + + for (const file of files) { + const content = Read(file); + const validation = validateMermaidSyntax(content); + + results.push({ + file: file.split('/').pop(), + path: file, + valid: validation.valid, + issues: validation.issues, + lines: content.split('\n').length + }); + } + + return results; +} +``` + +## Class Diagram Utilities + +### generateClassDiagram + +Generate class diagram with relationships. + +```javascript +/** + * Generate class diagram from analysis data + * + * @param {Object} analysis - Data structure analysis + * - entities: [{name, type, properties, methods}] + * - relationships: [{from, to, type, label}] + * @param {Object} options - Generation options + * - maxClasses: Max classes to include (default: 15) + * - maxProperties: Max properties per class (default: 8) + * - maxMethods: Max methods per class (default: 6) + * @returns {string} - Mermaid classDiagram + */ +function generateClassDiagram(analysis, options = {}) { + const maxClasses = options.maxClasses || 15; + const maxProperties = options.maxProperties || 8; + const maxMethods = options.maxMethods || 6; + + let mermaid = 'classDiagram\n'; + + const entities = (analysis.entities || []).slice(0, maxClasses); + + // Generate classes + for (const entity of entities) { + const className = sanitizeId(entity.name); + mermaid += ` class ${className} {\n`; + + // Properties + for (const prop of (entity.properties || []).slice(0, maxProperties)) { + const vis = {public: '+', private: '-', protected: '#'}[prop.visibility] || '+'; + const type = sanitizeType(prop.type); + mermaid += ` ${vis}${type} ${prop.name}\n`; + } + + // Methods + for (const method of (entity.methods || []).slice(0, maxMethods)) { + const vis = {public: '+', private: '-', protected: '#'}[method.visibility] || '+'; + const params = (method.params || []).map(p => p.name).join(', '); + const returnType = sanitizeType(method.returnType || 'void'); + mermaid += ` ${vis}${method.name}(${params}) ${returnType}\n`; + } + + mermaid += ' }\n'; + + // Add stereotype if applicable + if (entity.type === 'interface') { + mermaid += ` <> ${className}\n`; + } else if (entity.type === 'abstract') { + mermaid += ` <> ${className}\n`; + } + } + + // Generate relationships + const arrows = { + inheritance: '--|>', + implementation: '..|>', + composition: '*--', + aggregation: 'o--', + association: '-->', + dependency: '..>' + }; + + for (const rel of (analysis.relationships || [])) { + const from = sanitizeId(rel.from); + const to = sanitizeId(rel.to); + const arrow = arrows[rel.type] || '-->'; + const label = rel.label ? ` : ${escapeLabel(rel.label)}` : ''; + + // Only include if both entities exist + if (entities.some(e => sanitizeId(e.name) === from) && + entities.some(e => sanitizeId(e.name) === to)) { + mermaid += ` ${from} ${arrow} ${to}${label}\n`; + } + } + + return mermaid; +} +``` + +## Sequence Diagram Utilities + +### generateSequenceDiagram + +Generate sequence diagram from scenario. + +```javascript +/** + * Generate sequence diagram from scenario + * + * @param {Object} scenario - Sequence scenario + * - name: Scenario name + * - actors: [{id, name, type}] + * - messages: [{from, to, description, type}] + * - blocks: [{type, condition, messages}] + * @returns {string} - Mermaid sequenceDiagram + */ +function generateSequenceDiagram(scenario) { + let mermaid = 'sequenceDiagram\n'; + + // Title + if (scenario.name) { + mermaid += ` title ${escapeLabel(scenario.name)}\n`; + } + + // Participants + for (const actor of scenario.actors || []) { + const actorType = actor.type === 'external' ? 'actor' : 'participant'; + mermaid += ` ${actorType} ${sanitizeId(actor.id)} as ${escapeLabel(actor.name)}\n`; + } + + mermaid += '\n'; + + // Messages + for (const msg of scenario.messages || []) { + const from = sanitizeId(msg.from); + const to = sanitizeId(msg.to); + const desc = escapeLabel(msg.description); + + let arrow; + switch (msg.type) { + case 'async': arrow = '->>'; break; + case 'response': arrow = '-->>'; break; + case 'create': arrow = '->>+'; break; + case 'destroy': arrow = '->>-'; break; + case 'self': arrow = '->>'; break; + default: arrow = '->>'; + } + + mermaid += ` ${from}${arrow}${to}: ${desc}\n`; + + // Activation + if (msg.activate) { + mermaid += ` activate ${to}\n`; + } + if (msg.deactivate) { + mermaid += ` deactivate ${from}\n`; + } + + // Notes + if (msg.note) { + mermaid += ` Note over ${to}: ${escapeLabel(msg.note)}\n`; + } + } + + // Blocks (loops, alt, opt) + for (const block of scenario.blocks || []) { + switch (block.type) { + case 'loop': + mermaid += ` loop ${escapeLabel(block.condition)}\n`; + break; + case 'alt': + mermaid += ` alt ${escapeLabel(block.condition)}\n`; + break; + case 'opt': + mermaid += ` opt ${escapeLabel(block.condition)}\n`; + break; + } + + for (const m of block.messages || []) { + mermaid += ` ${sanitizeId(m.from)}->>${sanitizeId(m.to)}: ${escapeLabel(m.description)}\n`; + } + + mermaid += ' end\n'; + } + + return mermaid; +} +``` + +## Usage Examples + +### Example 1: Algorithm with Branches + +```javascript +const algorithm = { + name: "用户认证流程", + inputs: [{name: "credentials", type: "Object"}], + outputs: [{name: "token", type: "JWT"}], + steps: [ + {id: "validate", description: "验证输入格式", type: "process"}, + {id: "check_user", description: "用户是否存在?", type: "decision", + next: ["verify_pwd", "error_user"], conditions: ["是", "否"]}, + {id: "verify_pwd", description: "验证密码", type: "process"}, + {id: "pwd_ok", description: "密码正确?", type: "decision", + next: ["gen_token", "error_pwd"], conditions: ["是", "否"]}, + {id: "gen_token", description: "生成 JWT Token", type: "process"}, + {id: "error_user", description: "返回用户不存在", type: "io"}, + {id: "error_pwd", description: "返回密码错误", type: "io"} + ] +}; + +const flowchart = generateAlgorithmFlowchart(algorithm); +``` + +### Example 2: Validate Before Output + +```javascript +const diagram = generateClassDiagram(analysis); +const validation = validateMermaidSyntax(diagram); + +if (!validation.valid) { + console.log("Diagram has issues:", validation.issues); + // Fix issues or regenerate +} else { + Write(`${outputDir}/class-diagram.mmd`, diagram); +} +``` diff --git a/.claude/skills/copyright-docs/SKILL.md b/.claude/skills/copyright-docs/SKILL.md new file mode 100644 index 00000000..5bb1d3b6 --- /dev/null +++ b/.claude/skills/copyright-docs/SKILL.md @@ -0,0 +1,95 @@ +--- +name: copyright-docs +description: Generate software copyright design specification documents compliant with China Copyright Protection Center (CPCC) standards. Creates complete design documents with Mermaid diagrams based on source code analysis. Use for software copyright registration, generating design specification, creating CPCC-compliant documents, or documenting software for intellectual property protection. Triggers on "软件著作权", "设计说明书", "版权登记", "CPCC", "软著申请". +allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write +--- + +# Software Copyright Documentation Skill + +Generate CPCC-compliant software design specification documents (软件设计说明书) through multi-phase code analysis. + +## Execution Flow + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Phase 1: Metadata Collection │ +│ → Read: phases/01-metadata-collection.md │ +│ → Collect: software name, version, category, scope │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 2: Deep Code Analysis │ +│ → Read: phases/02-deep-analysis.md │ +│ → Launch: 6 parallel agents (architecture, functions, │ +│ algorithms, data_structures, interfaces, exceptions) │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 3: Diagram Generation │ +│ → Read: phases/03-diagram-generation.md │ +│ → Reference: ../_shared/mermaid-utils.md │ +│ → Generate: Mermaid diagrams for all 7 sections │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 4: Document Assembly │ +│ → Read: phases/04-document-assembly.md │ +│ → Reference: specs/cpcc-requirements.md │ +│ → Assemble: 7-section CPCC-compliant document │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 5: Compliance Review & Refinement │ +│ → Read: phases/05-compliance-refinement.md │ +│ → Reference: specs/cpcc-requirements.md (Compliance Checklist) │ +│ → Validate: run CPCC compliance checks before each iteration │ +│ → Loop: discovery-driven questions until all checks pass │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Document Sections (7 Required) + +| Section | Title | Diagram | +|---------|-------|---------| +| 1 | 软件概述 | - | +| 2 | 系统架构图 | graph TD | +| 3 | 功能模块设计 | flowchart TD | +| 4 | 核心算法与流程 | flowchart TD | +| 5 | 数据结构设计 | classDiagram | +| 6 | 接口设计 | sequenceDiagram | +| 7 | 异常处理设计 | flowchart TD | + +## Directory Setup + +```bash +timestamp=$(date +%Y%m%d-%H%M%S) +dir=".workflow/.scratchpad/copyright-$timestamp" +mkdir -p "$dir/diagrams" "$dir/iterations" +echo "$dir" +``` + +## Reference Documents + +| Document | Purpose | +|----------|---------| +| [phases/01-metadata-collection.md](phases/01-metadata-collection.md) | Software info collection | +| [phases/02-deep-analysis.md](phases/02-deep-analysis.md) | 6-agent parallel analysis | +| [phases/03-diagram-generation.md](phases/03-diagram-generation.md) | Mermaid diagram generation | +| [phases/04-document-assembly.md](phases/04-document-assembly.md) | Document structure assembly | +| [phases/05-compliance-refinement.md](phases/05-compliance-refinement.md) | Iterative refinement loop | +| [specs/cpcc-requirements.md](specs/cpcc-requirements.md) | CPCC compliance checklist | +| [../_shared/mermaid-utils.md](../_shared/mermaid-utils.md) | Shared Mermaid utilities | + +## Output Structure + +``` +.workflow/.scratchpad/copyright-{timestamp}/ +├── project-metadata.json +├── analysis-architecture.json +├── analysis-functions.json +├── analysis-algorithms.json +├── analysis-data_structures.json +├── analysis-interfaces.json +├── analysis-exceptions.json +├── diagrams/ +│ ├── manifest.json +│ ├── architecture.mmd +│ ├── functions.mmd +│ ├── class-diagram.mmd +│ ├── algorithm-*.mmd +│ └── sequence-*.mmd +├── iterations/ +└── {软件名称}-软件设计说明书.md +``` diff --git a/.claude/skills/copyright-docs/phases/01-metadata-collection.md b/.claude/skills/copyright-docs/phases/01-metadata-collection.md new file mode 100644 index 00000000..a2ab6726 --- /dev/null +++ b/.claude/skills/copyright-docs/phases/01-metadata-collection.md @@ -0,0 +1,78 @@ +# Phase 1: Metadata Collection + +Collect software metadata for document header and context. + +## Execution + +### Step 1: Software Name & Version + +```javascript +AskUserQuestion({ + questions: [{ + question: "请输入软件名称(将显示在文档页眉):", + header: "软件名称", + multiSelect: false, + options: [ + {label: "自动检测", description: "从 package.json 或项目配置读取"}, + {label: "手动输入", description: "输入自定义名称"} + ] + }] +}) +``` + +### Step 2: Software Category + +```javascript +AskUserQuestion({ + questions: [{ + question: "软件属于哪种类型?", + header: "软件类型", + multiSelect: false, + options: [ + {label: "命令行工具 (CLI)", description: "重点描述命令、参数"}, + {label: "后端服务/API", description: "重点描述端点、协议"}, + {label: "SDK/库", description: "重点描述接口、集成"}, + {label: "数据处理系统", description: "重点描述数据流、转换"}, + {label: "自动化脚本", description: "重点描述工作流、触发器"} + ] + }] +}) +``` + +### Step 3: Scope Definition + +```javascript +AskUserQuestion({ + questions: [{ + question: "分析范围是什么?", + header: "分析范围", + multiSelect: false, + options: [ + {label: "整个项目", description: "分析全部源代码"}, + {label: "指定目录", description: "仅分析 src/ 或其他目录"}, + {label: "自定义路径", description: "手动指定路径"} + ] + }] +}) +``` + +## Output + +Save metadata to `project-metadata.json`: + +```json +{ + "software_name": "智能数据分析系统", + "version": "V1.0.0", + "category": "后端服务/API", + "scope_path": "src/", + "tech_stack": { + "language": "TypeScript", + "runtime": "Node.js 18+", + "framework": "Express.js", + "dependencies": ["mongoose", "redis", "bull"] + }, + "entry_points": ["src/index.ts", "src/cli.ts"], + "main_modules": ["auth", "data", "api", "worker"] +} +``` diff --git a/.claude/skills/copyright-docs/phases/02-deep-analysis.md b/.claude/skills/copyright-docs/phases/02-deep-analysis.md new file mode 100644 index 00000000..c3e89f83 --- /dev/null +++ b/.claude/skills/copyright-docs/phases/02-deep-analysis.md @@ -0,0 +1,138 @@ +# Phase 2: Deep Code Analysis + +Launch 6 parallel agents for multi-dimensional code analysis. + +## Execution + +### Analysis Dimensions + +| Agent | Dimension | Analysis Focus | Output Section | +|-------|-----------|----------------|----------------| +| 1 | architecture | 分层、模块、依赖 | Section 2 | +| 2 | functions | 功能、工作流、交互 | Section 3 | +| 3 | algorithms | 核心逻辑、复杂度、流程 | Section 4 | +| 4 | data_structures | 实体、属性、关系 | Section 5 | +| 5 | interfaces | API、参数、响应 | Section 6 | +| 6 | exceptions | 错误类型、处理、恢复 | Section 7 | + +### Agent Prompts + +**Architecture Analysis:** +```javascript +Task({ + subagent_type: "cli-explore-agent", + prompt: ` +## 分析目标 +分析项目的系统架构,为"系统架构图"章节提供数据。 + +## 分析内容 +1. 分层结构:识别代码的分层(Controller/Service/Repository) +2. 模块边界:各模块的职责范围和边界 +3. 依赖关系:模块间的依赖方向和类型 +4. 核心组件:系统的核心组件及其作用 +5. 数据流向:数据在各层之间的流动路径 + +## 输出格式 +{ + "layers": [{name, components, responsibility}], + "modules": [{name, path, responsibility, dependencies}], + "data_flow": [{from, to, data_type, description}], + "core_components": [{name, type, responsibility}] +} +` +}) +``` + +**Function Analysis:** +```javascript +prompt = ` +## 分析目标 +分析项目的功能模块,为"功能模块设计"章节提供数据。 + +## 输出格式 +{ + "feature_list": [{id, name, description, module, entry_file}], + "feature_groups": [{group_name, features: []}], + "feature_hierarchy": {root: {children: [...]}}, + "interactions": [{caller, callee, trigger, description}], + "key_workflows": [{name, steps: [], files_involved}] +} +` +``` + +**Algorithm Analysis:** +```javascript +prompt = ` +## 分析目标 +分析项目的核心算法和业务逻辑,为"核心算法与流程"章节提供数据。 + +## 输出格式 +{ + "algorithms": [{ + name, file, line, description, complexity, + inputs: [{name, type, description}], + outputs: [{name, type, description}], + steps: [{step_num, description, type, next, conditions}] + }], + "complex_functions": [{name, file, cyclomatic_complexity}] +} +` +``` + +**Data Structure Analysis:** +```javascript +prompt = ` +## 分析目标 +分析项目的数据结构,为"数据结构设计"章节提供数据。 + +## 输出格式 +{ + "entities": [{ + name, file, type, + properties: [{name, type, visibility, description}], + methods: [{name, params, return_type, visibility}] + }], + "relationships": [{from, to, type, cardinality, description}], + "enums": [{name, values: [{name, value, description}]}] +} +` +``` + +**Interface Analysis:** +```javascript +prompt = ` +## 分析目标 +分析项目的接口设计,为"接口设计"章节提供数据。 + +## 输出格式 +{ + "apis": [{ + name, path, method, description, + parameters: [{name, type, required, description}], + response: {type, schema, description}, + category + }], + "protocols": [{name, type, description}] +} +` +``` + +**Exception Analysis:** +```javascript +prompt = ` +## 分析目标 +分析项目的异常处理机制,为"异常处理设计"章节提供数据。 + +## 输出格式 +{ + "exception_types": [{name, parent, code, message, file}], + "error_codes": [{code, message, severity, category}], + "handling_patterns": [{pattern, locations: [], description}], + "recovery_strategies": [{strategy, trigger, action, files}] +} +` +``` + +## Output + +Save each analysis to `analysis-{dimension}.json`. diff --git a/.claude/skills/copyright-docs/phases/03-diagram-generation.md b/.claude/skills/copyright-docs/phases/03-diagram-generation.md new file mode 100644 index 00000000..da798d14 --- /dev/null +++ b/.claude/skills/copyright-docs/phases/03-diagram-generation.md @@ -0,0 +1,147 @@ +# Phase 3: Mermaid Diagram Generation + +Generate Mermaid diagrams for each document section. + +> **Reference**: See [mermaid-utils.md](../../_shared/mermaid-utils.md) for utility functions. + +## Execution + +### Diagram Mapping + +| Section | Diagram Type | Format | File | +|---------|--------------|--------|------| +| 2. 系统架构图 | Architecture | graph TD | architecture.mmd | +| 3. 功能模块设计 | Function Tree | flowchart TD | functions.mmd | +| 4. 核心算法与流程 | Algorithm Flow | flowchart TD | algorithm-*.mmd | +| 5. 数据结构设计 | Class Diagram | classDiagram | class-diagram.mmd | +| 6. 接口设计 | Sequence | sequenceDiagram | sequence-*.mmd | +| 7. 异常处理设计 | Error Flow | flowchart TD | exception-flow.mmd | + +### Section 2: System Architecture + +```javascript +function generateArchitectureDiagram(analysis) { + let mermaid = 'graph TD\n'; + + for (const layer of analysis.layers) { + mermaid += ` subgraph ${sanitizeId(layer.name)}["${escapeLabel(layer.name)}"]\n`; + for (const comp of layer.components) { + mermaid += ` ${sanitizeId(comp)}["${escapeLabel(comp)}"]\n`; + } + mermaid += ' end\n'; + } + + for (const flow of analysis.data_flow) { + mermaid += ` ${sanitizeId(flow.from)} -->|"${escapeLabel(flow.description)}"| ${sanitizeId(flow.to)}\n`; + } + + return mermaid; +} +``` + +### Section 3: Function Modules + +```javascript +function generateFunctionDiagram(analysis, softwareName) { + let mermaid = 'flowchart TD\n'; + mermaid += ` ROOT["${escapeLabel(softwareName)}"]\n`; + + for (const group of analysis.feature_groups) { + mermaid += ` subgraph ${sanitizeId(group.group_name)}["${escapeLabel(group.group_name)}"]\n`; + for (const feature of group.features) { + mermaid += ` ${sanitizeId(feature.id)}["${escapeLabel(feature.name)}"]\n`; + } + mermaid += ' end\n'; + mermaid += ` ROOT --> ${sanitizeId(group.group_name)}\n`; + } + + return mermaid; +} +``` + +### Section 4: Algorithm Flowchart (with branches) + +```javascript +// Uses generateAlgorithmFlowchart from _shared/mermaid-utils.md +// Supports: type (process/decision/io), next, conditions + +const flowchart = generateAlgorithmFlowchart({ + name: algorithm.name, + inputs: algorithm.inputs, + outputs: algorithm.outputs, + steps: algorithm.steps // Each step can have type, next, conditions +}); +``` + +### Section 5: Class Diagram + +```javascript +function generateClassDiagram(analysis) { + let mermaid = 'classDiagram\n'; + + for (const entity of analysis.entities) { + mermaid += ` class ${sanitizeId(entity.name)} {\n`; + for (const prop of entity.properties) { + const vis = {public: '+', private: '-', protected: '#'}[prop.visibility] || '+'; + mermaid += ` ${vis}${sanitizeType(prop.type)} ${prop.name}\n`; + } + for (const method of entity.methods) { + const vis = {public: '+', private: '-', protected: '#'}[method.visibility] || '+'; + mermaid += ` ${vis}${method.name}(${method.params}) ${sanitizeType(method.return_type)}\n`; + } + mermaid += ' }\n'; + } + + const arrows = { + inheritance: '--|>', + composition: '*--', + aggregation: 'o--', + association: '-->' + }; + + for (const rel of analysis.relationships) { + const arrow = arrows[rel.type] || '-->'; + mermaid += ` ${sanitizeId(rel.from)} ${arrow} ${sanitizeId(rel.to)} : ${escapeLabel(rel.description)}\n`; + } + + return mermaid; +} +``` + +### Section 6: Sequence Diagram + +```javascript +function generateSequenceDiagram(scenario) { + let mermaid = 'sequenceDiagram\n'; + + for (const actor of scenario.actors) { + mermaid += ` participant ${sanitizeId(actor.id)} as ${escapeLabel(actor.name)}\n`; + } + + for (const msg of scenario.messages) { + const arrow = msg.type === 'async' ? '-)' : '->>'; + mermaid += ` ${sanitizeId(msg.from)}${arrow}${sanitizeId(msg.to)}: ${escapeLabel(msg.description)}\n`; + } + + return mermaid; +} +``` + +### Validation + +```javascript +// Validate all generated diagrams +const results = validateDiagramDirectory(`${outputDir}/diagrams`); +const failed = results.filter(r => !r.valid); + +if (failed.length > 0) { + // Regenerate failed diagrams with stricter escaping + for (const f of failed) { + regenerateWithFixes(f.file, f.issues); + } +} +``` + +## Output + +Save diagrams to `diagrams/` with `manifest.json`. diff --git a/.claude/skills/copyright-docs/phases/04-document-assembly.md b/.claude/skills/copyright-docs/phases/04-document-assembly.md new file mode 100644 index 00000000..25b5b6bd --- /dev/null +++ b/.claude/skills/copyright-docs/phases/04-document-assembly.md @@ -0,0 +1,128 @@ +# Phase 4: Document Assembly + +Assemble all analysis and diagrams into CPCC-compliant document. + +## Execution + +### Document Structure (7 Sections) + +```markdown + + + +## 1. 软件概述 +### 1.1 软件背景与用途 +### 1.2 开发目标与特点 +### 1.3 运行环境与技术架构 + +## 2. 系统架构图 +图2-1 系统架构图 +(Mermaid graph TD) + +## 3. 功能模块设计 +图3-1 功能模块结构图 +(Mermaid flowchart TD) + +## 4. 核心算法与流程 +图4-1 {算法名称}流程图 +(Mermaid flowchart TD) + +## 5. 数据结构设计 +图5-1 数据结构类图 +(Mermaid classDiagram) + +## 6. 接口设计 +图6-1 接口调用时序图 +(Mermaid sequenceDiagram) + +## 7. 异常处理设计 +图7-1 异常处理流程图 +(Mermaid flowchart TD) +``` + +### Section Templates + +**Section 1: 软件概述** +```markdown +## 1. 软件概述 + +### 1.1 软件背景与用途 + +${software_name}是一款${category}软件,主要用于${inferred_purpose}。 + +本软件基于${tech_stack.language}语言开发,采用${tech_stack.framework}实现核心功能。 + +### 1.2 开发目标与特点 + +**开发目标**: +${objectives} + +**技术特点**: +${features} + +### 1.3 运行环境与技术架构 + +**运行环境**: +- 操作系统:${os} +- 运行时:${runtime} +- 依赖环境:${dependencies} + +**技术架构**: +- 架构模式:${architecture_pattern} +- 核心框架:${framework} +``` + +**Section 2-7: Pattern** +```markdown +## {N}. {章节标题} + +本章节展示${software_name}的{描述}。 + +\`\`\`mermaid +${diagram_content} +\`\`\` + +**图{N}-1 {图表标题}** + +### {子标题} + +{详细说明} +``` + +### Figure Numbering + +| Section | Figure Number | Title | +|---------|---------------|-------| +| 2 | 图2-1 | 系统架构图 | +| 3 | 图3-1 | 功能模块结构图 | +| 4 | 图4-1, 图4-2... | {算法名称}流程图 | +| 5 | 图5-1 | 数据结构类图 | +| 6 | 图6-1, 图6-2... | {接口名称}时序图 | +| 7 | 图7-1 | 异常处理流程图 | + +### Assembly Code + +```javascript +function assembleDocument(metadata, analyses, diagrams) { + let doc = ''; + + // Header + doc += `\n`; + doc += `\n\n`; + + // Generate each section + doc += generateSection1(metadata, analyses.architecture); + doc += generateSection2(analyses.architecture, diagrams.architecture); + doc += generateSection3(analyses.functions, diagrams.functions, metadata.software_name); + doc += generateSection4(analyses.algorithms, diagrams.algorithms); + doc += generateSection5(analyses.data_structures, diagrams.class); + doc += generateSection6(analyses.interfaces, diagrams.sequences); + doc += generateSection7(analyses.exceptions, diagrams.exception_flow); + + return doc; +} +``` + +## Output + +Generate `{软件名称}-软件设计说明书.md`. diff --git a/.claude/skills/copyright-docs/phases/05-compliance-refinement.md b/.claude/skills/copyright-docs/phases/05-compliance-refinement.md new file mode 100644 index 00000000..bd62b7a3 --- /dev/null +++ b/.claude/skills/copyright-docs/phases/05-compliance-refinement.md @@ -0,0 +1,192 @@ +# Phase 5: Compliance Review & Iterative Refinement + +Discovery-driven refinement loop until CPCC compliance is met. + +## Execution + +### Step 1: Extract Compliance Issues + +```javascript +function extractComplianceIssues(validationResult, deepAnalysis) { + return { + // Missing or incomplete sections + missingSections: validationResult.details + .filter(d => !d.pass) + .map(d => ({ + section: d.name, + severity: 'critical', + suggestion: `需要补充 ${d.name} 相关内容` + })), + + // Features with weak descriptions (< 50 chars) + weakDescriptions: (deepAnalysis.functions?.feature_list || []) + .filter(f => !f.description || f.description.length < 50) + .map(f => ({ + feature: f.name, + current: f.description || '(无描述)', + severity: 'warning' + })), + + // Complex algorithms without detailed flowcharts + complexAlgorithms: (deepAnalysis.algorithms?.algorithms || []) + .filter(a => (a.complexity || 0) > 10 && (a.steps?.length || 0) < 5) + .map(a => ({ + algorithm: a.name, + complexity: a.complexity, + file: a.file, + severity: 'warning' + })), + + // Data relationships without descriptions + incompleteRelationships: (deepAnalysis.data_structures?.relationships || []) + .filter(r => !r.description) + .map(r => ({from: r.from, to: r.to, severity: 'info'})), + + // Diagram validation issues + diagramIssues: (deepAnalysis.diagrams?.validation || []) + .filter(d => !d.valid) + .map(d => ({file: d.file, issues: d.issues, severity: 'critical'})) + }; +} +``` + +### Step 2: Build Dynamic Questions + +```javascript +function buildComplianceQuestions(issues) { + const questions = []; + + if (issues.missingSections.length > 0) { + questions.push({ + question: `发现 ${issues.missingSections.length} 个章节内容不完整,需要补充哪些?`, + header: "章节补充", + multiSelect: true, + options: issues.missingSections.slice(0, 4).map(s => ({ + label: s.section, + description: s.suggestion + })) + }); + } + + if (issues.weakDescriptions.length > 0) { + questions.push({ + question: `以下 ${issues.weakDescriptions.length} 个功能描述过于简短,请选择需要详细说明的:`, + header: "功能描述", + multiSelect: true, + options: issues.weakDescriptions.slice(0, 4).map(f => ({ + label: f.feature, + description: `当前:${f.current.substring(0, 30)}...` + })) + }); + } + + if (issues.complexAlgorithms.length > 0) { + questions.push({ + question: `发现 ${issues.complexAlgorithms.length} 个复杂算法缺少详细流程图,是否生成?`, + header: "算法详解", + multiSelect: false, + options: [ + {label: "全部生成 (推荐)", description: "为所有复杂算法生成含分支/循环的流程图"}, + {label: "仅最复杂的", description: `仅为 ${issues.complexAlgorithms[0]?.algorithm} 生成`}, + {label: "跳过", description: "保持当前简单流程图"} + ] + }); + } + + questions.push({ + question: "如何处理当前文档?", + header: "操作", + multiSelect: false, + options: [ + {label: "应用修改并继续", description: "应用上述选择,继续检查"}, + {label: "完成文档", description: "当前文档满足要求,生成最终版本"}, + {label: "重新分析", description: "使用不同配置重新分析代码"} + ] + }); + + return questions.slice(0, 4); +} +``` + +### Step 3: Apply Updates + +```javascript +async function applyComplianceUpdates(responses, issues, analyses, outputDir) { + const updates = []; + + if (responses['章节补充']) { + for (const section of responses['章节补充']) { + const sectionAnalysis = await Task({ + subagent_type: "cli-explore-agent", + prompt: `深入分析 ${section.section} 所需内容...` + }); + updates.push({type: 'section_supplement', section: section.section, data: sectionAnalysis}); + } + } + + if (responses['算法详解'] === '全部生成 (推荐)') { + for (const algo of issues.complexAlgorithms) { + const detailedSteps = await analyzeAlgorithmInDepth(algo, analyses); + const flowchart = generateAlgorithmFlowchart({ + name: algo.algorithm, + inputs: detailedSteps.inputs, + outputs: detailedSteps.outputs, + steps: detailedSteps.steps + }); + Write(`${outputDir}/diagrams/algorithm-${sanitizeId(algo.algorithm)}-detailed.mmd`, flowchart); + updates.push({type: 'algorithm_flowchart', algorithm: algo.algorithm}); + } + } + + return updates; +} +``` + +### Step 4: Iteration Loop + +```javascript +async function runComplianceLoop(documentPath, analyses, metadata, outputDir) { + let iteration = 0; + const maxIterations = 5; + + while (iteration < maxIterations) { + iteration++; + + // Validate current document + const document = Read(documentPath); + const validation = validateCPCCCompliance(document, analyses); + + // Extract issues + const issues = extractComplianceIssues(validation, analyses); + const totalIssues = Object.values(issues).flat().length; + + if (totalIssues === 0) { + console.log("✅ 所有检查通过,文档符合 CPCC 要求"); + break; + } + + // Ask user + const questions = buildComplianceQuestions(issues); + const responses = await AskUserQuestion({questions}); + + if (responses['操作'] === '完成文档') break; + if (responses['操作'] === '重新分析') return {action: 'restart'}; + + // Apply updates + const updates = await applyComplianceUpdates(responses, issues, analyses, outputDir); + + // Regenerate document + const updatedDocument = regenerateDocument(document, updates, analyses); + Write(documentPath, updatedDocument); + + // Archive iteration + Write(`${outputDir}/iterations/v${iteration}.md`, document); + } + + return {action: 'finalized', iterations: iteration}; +} +``` + +## Output + +Final compliant document + iteration history in `iterations/`. diff --git a/.claude/skills/copyright-docs/specs/cpcc-requirements.md b/.claude/skills/copyright-docs/specs/cpcc-requirements.md new file mode 100644 index 00000000..3bf6b9c0 --- /dev/null +++ b/.claude/skills/copyright-docs/specs/cpcc-requirements.md @@ -0,0 +1,121 @@ +# CPCC Compliance Requirements + +China Copyright Protection Center (CPCC) requirements for software design specification. + +## When to Use + +| Phase | Usage | Section | +|-------|-------|---------| +| Phase 4 | Check document structure before assembly | Document Requirements, Mandatory Sections | +| Phase 4 | Apply correct figure numbering | Figure Numbering Convention | +| Phase 5 | Validate before each iteration | Validation Function | +| Phase 5 | Handle failures during refinement | Error Handling | + +--- + +## Document Requirements + +### Format +- [ ] 页眉包含软件名称和版本号 +- [ ] 页码位于右上角说明 +- [ ] 每页不少于30行文字(图表页除外) +- [ ] A4纵向排版,文字从左至右 + +### Mandatory Sections (7 章节) +- [ ] 1. 软件概述 +- [ ] 2. 系统架构图 +- [ ] 3. 功能模块设计 +- [ ] 4. 核心算法与流程 +- [ ] 5. 数据结构设计 +- [ ] 6. 接口设计 +- [ ] 7. 异常处理设计 + +### Content Requirements +- [ ] 所有内容基于代码分析 +- [ ] 无臆测或未来计划 +- [ ] 无原始指令性文字 +- [ ] Mermaid 语法正确 +- [ ] 图表编号和说明完整 + +## Validation Function + +```javascript +function validateCPCCCompliance(document, analyses) { + const checks = [ + {name: "软件概述完整性", pass: document.includes("## 1. 软件概述")}, + {name: "系统架构图存在", pass: document.includes("图2-1 系统架构图")}, + {name: "功能模块设计完整", pass: document.includes("## 3. 功能模块设计")}, + {name: "核心算法描述", pass: document.includes("## 4. 核心算法与流程")}, + {name: "数据结构设计", pass: document.includes("## 5. 数据结构设计")}, + {name: "接口设计说明", pass: document.includes("## 6. 接口设计")}, + {name: "异常处理设计", pass: document.includes("## 7. 异常处理设计")}, + {name: "Mermaid图表语法", pass: !document.includes("mermaid error")}, + {name: "页眉信息", pass: document.includes("页眉")}, + {name: "页码说明", pass: document.includes("页码")} + ]; + + return { + passed: checks.filter(c => c.pass).length, + total: checks.length, + details: checks + }; +} +``` + +## Software Categories + +| Category | Document Focus | +|----------|----------------| +| 命令行工具 (CLI) | 命令、参数、使用流程 | +| 后端服务/API | 端点、协议、数据流 | +| SDK/库 | 接口、集成、使用示例 | +| 数据处理系统 | 数据流、转换、ETL | +| 自动化脚本 | 工作流、触发器、调度 | + +## Figure Numbering Convention + +| Section | Figure | Title | +|---------|--------|-------| +| 2 | 图2-1 | 系统架构图 | +| 3 | 图3-1 | 功能模块结构图 | +| 4 | 图4-N | {算法名称}流程图 | +| 5 | 图5-1 | 数据结构类图 | +| 6 | 图6-N | {接口名称}时序图 | +| 7 | 图7-1 | 异常处理流程图 | + +## Error Handling + +| Error | Recovery | +|-------|----------| +| Analysis timeout | Reduce scope, retry | +| Missing section data | Re-run targeted agent | +| Diagram validation fails | Regenerate with fixes | +| User abandons iteration | Save progress, allow resume | + +--- + +## Integration with Phases + +**Phase 4 - Document Assembly**: +```javascript +// Before assembling document +const docChecks = [ + {check: "页眉格式", value: ``}, + {check: "页码说明", value: ``} +]; + +// Apply figure numbering from convention table +const figureNumbers = getFigureNumbers(sectionIndex); +``` + +**Phase 5 - Compliance Refinement**: +```javascript +// In 05-compliance-refinement.md +const validation = validateCPCCCompliance(document, analyses); + +if (validation.passed < validation.total) { + // Failed checks become discovery questions + const failedChecks = validation.details.filter(d => !d.pass); + discoveries.complianceIssues = failedChecks; +} +``` diff --git a/.claude/skills/project-analyze/SKILL.md b/.claude/skills/project-analyze/SKILL.md new file mode 100644 index 00000000..83d059ee --- /dev/null +++ b/.claude/skills/project-analyze/SKILL.md @@ -0,0 +1,89 @@ +--- +name: project-analyze +description: Multi-phase iterative project analysis with Mermaid diagrams. Generates architecture reports, design reports, method analysis reports. Use when analyzing codebases, understanding project structure, reviewing architecture, exploring design patterns, or documenting system components. Triggers on "analyze project", "architecture report", "design analysis", "code structure", "system overview". +allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write +--- + +# Project Analysis Skill + +Generate comprehensive project analysis reports through multi-phase iterative workflow. + +## Execution Flow + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Phase 1: Requirements Discovery │ +│ → Read: phases/01-requirements-discovery.md │ +│ → Collect: report type, depth level, scope │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 2: Project Exploration │ +│ → Read: phases/02-project-exploration.md │ +│ → Launch: parallel cli-explore-agents │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 3: Deep Analysis │ +│ → Read: phases/03-deep-analysis.md │ +│ → Execute: Gemini CLI with exploration context │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 3.5: Diagram Generation │ +│ → Read: phases/03.5-diagram-generation.md │ +│ → Reference: ../_shared/mermaid-utils.md │ +│ → Generate: Mermaid diagrams based on report type │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 4: Report Generation │ +│ → Read: phases/04-report-generation.md │ +│ → Reference: specs/quality-standards.md (Report Requirements) │ +│ → Assemble: Markdown report with embedded diagrams │ +├─────────────────────────────────────────────────────────────────┤ +│ Phase 5: Iterative Refinement │ +│ → Read: phases/05-iterative-refinement.md │ +│ → Reference: specs/quality-standards.md (Quality Gates) │ +│ → Validate: run quality checks before each iteration │ +│ → Loop: discovery-driven questions until all gates pass │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Report Types + +| Type | Output | Focus | +|------|--------|-------| +| `architecture` | ARCHITECTURE-REPORT.md | System structure, modules, dependencies | +| `design` | DESIGN-REPORT.md | Patterns, classes, interfaces | +| `methods` | METHODS-REPORT.md | Algorithms, critical paths, APIs | +| `comprehensive` | COMPREHENSIVE-REPORT.md | All above combined | + +## Directory Setup + +```bash +timestamp=$(date +%Y%m%d-%H%M%S) +dir=".workflow/.scratchpad/analyze-$timestamp" +mkdir -p "$dir/diagrams" "$dir/iterations" +echo "$dir" +``` + +## Reference Documents + +| Document | Purpose | +|----------|---------| +| [phases/01-requirements-discovery.md](phases/01-requirements-discovery.md) | User interaction, config collection | +| [phases/02-project-exploration.md](phases/02-project-exploration.md) | Parallel agent exploration | +| [phases/03-deep-analysis.md](phases/03-deep-analysis.md) | Gemini CLI analysis | +| [phases/03.5-diagram-generation.md](phases/03.5-diagram-generation.md) | Mermaid diagram generation | +| [phases/04-report-generation.md](phases/04-report-generation.md) | Report assembly | +| [phases/05-iterative-refinement.md](phases/05-iterative-refinement.md) | Discovery-driven refinement | +| [specs/quality-standards.md](specs/quality-standards.md) | Quality gates, error handling | +| [../_shared/mermaid-utils.md](../_shared/mermaid-utils.md) | Shared Mermaid utilities | + +## Output Structure + +``` +.workflow/.scratchpad/analyze-{timestamp}/ +├── analysis-config.json +├── exploration-*.json +├── deep-analysis.json +├── diagrams/ +│ ├── manifest.json +│ ├── validation.json +│ └── *.mmd +├── {TYPE}-REPORT.md +└── iterations/ +``` diff --git a/.claude/skills/project-analyze/phases/01-requirements-discovery.md b/.claude/skills/project-analyze/phases/01-requirements-discovery.md new file mode 100644 index 00000000..353d1133 --- /dev/null +++ b/.claude/skills/project-analyze/phases/01-requirements-discovery.md @@ -0,0 +1,79 @@ +# Phase 1: Requirements Discovery + +Collect user requirements before analysis begins. + +## Execution + +### Step 1: Report Type Selection + +```javascript +AskUserQuestion({ + questions: [{ + question: "What type of project analysis report would you like?", + header: "Report Type", + multiSelect: false, + options: [ + {label: "Architecture (Recommended)", description: "System structure, module relationships, layer analysis, dependency graph"}, + {label: "Design", description: "Design patterns, class relationships, component interactions, abstraction analysis"}, + {label: "Methods", description: "Key algorithms, critical code paths, core function explanations with examples"}, + {label: "Comprehensive", description: "All above combined into a complete project analysis"} + ] + }] +}) +``` + +### Step 2: Depth Level Selection + +```javascript +AskUserQuestion({ + questions: [{ + question: "What depth level do you need?", + header: "Depth", + multiSelect: false, + options: [ + {label: "Overview", description: "High-level understanding, suitable for onboarding"}, + {label: "Detailed", description: "In-depth analysis with code examples"}, + {label: "Deep-Dive", description: "Exhaustive analysis with implementation details"} + ] + }] +}) +``` + +### Step 3: Scope Definition + +```javascript +AskUserQuestion({ + questions: [{ + question: "What scope should the analysis cover?", + header: "Scope", + multiSelect: false, + options: [ + {label: "Full Project", description: "Analyze entire codebase"}, + {label: "Specific Module", description: "Focus on a specific module or directory"}, + {label: "Custom Path", description: "Specify custom path pattern"} + ] + }] +}) +``` + +## Focus Areas Mapping + +| Report Type | Focus Areas | +|-------------|-------------| +| Architecture | Layer Structure, Module Dependencies, Entry Points, Data Flow | +| Design | Design Patterns, Class Relationships, Interface Contracts, State Management | +| Methods | Core Algorithms, Critical Paths, Public APIs, Complex Logic | +| Comprehensive | All above combined | + +## Output + +Save configuration to `analysis-config.json`: + +```json +{ + "type": "architecture|design|methods|comprehensive", + "depth": "overview|detailed|deep-dive", + "scope": "**/*|src/**/*|custom", + "focus_areas": ["..."] +} +``` diff --git a/.claude/skills/project-analyze/phases/02-project-exploration.md b/.claude/skills/project-analyze/phases/02-project-exploration.md new file mode 100644 index 00000000..1b9507d0 --- /dev/null +++ b/.claude/skills/project-analyze/phases/02-project-exploration.md @@ -0,0 +1,74 @@ +# Phase 2: Project Exploration + +Launch parallel exploration agents based on report type. + +## Execution + +### Step 1: Map Exploration Angles + +```javascript +const angleMapping = { + architecture: ["Layer Structure", "Module Dependencies", "Entry Points", "Data Flow"], + design: ["Design Patterns", "Class Relationships", "Interface Contracts", "State Management"], + methods: ["Core Algorithms", "Critical Paths", "Public APIs", "Complex Logic"], + comprehensive: ["Layer Structure", "Design Patterns", "Core Algorithms", "Data Flow"] +}; + +const angles = angleMapping[config.type]; +``` + +### Step 2: Launch Parallel Agents + +For each angle, launch an exploration agent: + +```javascript +Task({ + subagent_type: "cli-explore-agent", + description: `Explore: ${angle}`, + prompt: ` +## Exploration Objective +Execute **${angle}** exploration for project analysis report. + +## Context +- **Angle**: ${angle} +- **Report Type**: ${config.type} +- **Depth**: ${config.depth} +- **Scope**: ${config.scope} + +## Exploration Protocol +1. Structural Discovery (get_modules_by_depth, rg, glob) +2. Pattern Recognition (conventions, naming, organization) +3. Relationship Mapping (dependencies, integration points) + +## Output Format +{ + "angle": "${angle}", + "findings": { + "structure": [...], + "patterns": [...], + "relationships": [...], + "key_files": [{path, relevance, rationale}] + }, + "insights": [...] +} +` +}) +``` + +### Step 3: Aggregate Results + +Merge all exploration results into unified findings: + +```javascript +const aggregatedFindings = { + structure: [], // from all angles + patterns: [], // from all angles + relationships: [], // from all angles + key_files: [], // deduplicated + insights: [] // prioritized +}; +``` + +## Output + +Save exploration results to `exploration-{angle}.json` files. diff --git a/.claude/skills/project-analyze/phases/03-deep-analysis.md b/.claude/skills/project-analyze/phases/03-deep-analysis.md new file mode 100644 index 00000000..f53452e0 --- /dev/null +++ b/.claude/skills/project-analyze/phases/03-deep-analysis.md @@ -0,0 +1,58 @@ +# Phase 3: Deep Analysis + +Execute deep analysis using Gemini CLI with exploration context. + +## Execution + +### Step 1: Prepare CLI Prompt + +```bash +ccw cli -p " +PURPOSE: Generate ${type} analysis report for project +TASK: + • Analyze project structure and patterns from ${type} perspective + • Focus on: ${focus_areas} + • Depth level: ${depth} + • Key files: ${key_files} +MODE: analysis +CONTEXT: @**/* | Exploration results +EXPECTED: + - Structured analysis + - Code references (file:line format) + - Mermaid diagram data + - Actionable insights +RULES: $(cat ~/.claude/workflows/cli-templates/protocols/analysis-protocol.md) +" --tool gemini --mode analysis +``` + +### Step 2: Parse Analysis Results + +Extract structured data from CLI response: + +```javascript +const deepAnalysis = { + findings: [], // Analyzed findings with confidence scores + patterns: [], // Identified patterns with consistency scores + dependencies: [], // Dependency relationships + recommendations: [], // Prioritized recommendations + sections: [], // Report section data + diagram_data: {} // Data for diagram generation +}; +``` + +### Step 3: Validate Analysis Quality + +Check analysis completeness: + +```javascript +const qualityChecks = { + has_executive_summary: Boolean, + focus_areas_covered: config.focus_areas.every(area => analysis.covers(area)), + code_references_valid: analysis.references.every(ref => fileExists(ref)), + insights_actionable: analysis.insights.filter(i => i.actionable).length > 0 +}; +``` + +## Output + +Save analysis results to `deep-analysis.json`. diff --git a/.claude/skills/project-analyze/phases/03.5-diagram-generation.md b/.claude/skills/project-analyze/phases/03.5-diagram-generation.md new file mode 100644 index 00000000..99fe9526 --- /dev/null +++ b/.claude/skills/project-analyze/phases/03.5-diagram-generation.md @@ -0,0 +1,86 @@ +# Phase 3.5: Diagram Generation + +Generate Mermaid diagrams based on report type and analysis data. + +> **Reference**: See [mermaid-utils.md](../../_shared/mermaid-utils.md) for utility functions. + +## Execution + +### Step 1: Determine Required Diagrams + +```javascript +const diagramRequirements = { + architecture: [ + {type: 'architecture', format: 'graph TD', file: 'architecture.mmd'}, + {type: 'layers', format: 'graph TD', file: 'layers.mmd'}, + {type: 'dependencies', format: 'graph LR', file: 'dependencies.mmd'}, + {type: 'dataflow', format: 'flowchart LR', file: 'dataflow.mmd'} + ], + design: [ + {type: 'class', format: 'classDiagram', file: 'class-diagram.mmd'}, + {type: 'components', format: 'graph TD', file: 'components.mmd'}, + {type: 'patterns', format: 'graph TD', file: 'patterns.mmd'}, + {type: 'state', format: 'stateDiagram-v2', file: 'state.mmd'} + ], + methods: [ + {type: 'algorithm', format: 'flowchart TD', file: 'algorithm-*.mmd'}, + {type: 'sequence', format: 'sequenceDiagram', file: 'sequence-*.mmd'}, + {type: 'critical_path', format: 'flowchart LR', file: 'critical-path.mmd'}, + {type: 'api', format: 'graph LR', file: 'api.mmd'} + ], + comprehensive: [ + {type: 'architecture', format: 'graph TD', file: 'architecture.mmd'}, + {type: 'class', format: 'classDiagram', file: 'class-diagram.mmd'}, + {type: 'sequence', format: 'sequenceDiagram', file: 'sequence-main.mmd'}, + {type: 'dataflow', format: 'flowchart LR', file: 'dataflow.mmd'} + ] +}; + +const required = diagramRequirements[config.type]; +``` + +### Step 2: Generate Each Diagram + +Use shared utilities from `../_shared/mermaid-utils.md`: + +```javascript +// Import utilities +const { sanitizeId, escapeLabel, generateClassDiagram, generateSequenceDiagram, validateMermaidSyntax } = require('../_shared/mermaid-utils.md'); + +for (const diagram of required) { + const content = generateDiagram(diagram.type, diagram.format, analysisData); + Write(`${outputDir}/diagrams/${diagram.file}`, content); +} +``` + +### Step 3: Validate All Diagrams + +```javascript +const validationResults = validateDiagramDirectory(`${outputDir}/diagrams`); +const failedDiagrams = validationResults.filter(r => !r.valid); + +if (failedDiagrams.length > 0) { + // Regenerate failed diagrams + for (const failed of failedDiagrams) { + regenerateDiagram(failed.file, failed.issues); + } +} +``` + +### Step 4: Create Diagram Manifest + +```javascript +Write(`${outputDir}/diagrams/manifest.json`, JSON.stringify({ + generated_at: new Date().toISOString(), + diagrams: required.map(d => ({ + type: d.type, + file: d.file, + format: d.format + })), + validation: validationResults +}, null, 2)); +``` + +## Output + +Save diagrams to `diagrams/` folder with `manifest.json`. diff --git a/.claude/skills/project-analyze/phases/04-report-generation.md b/.claude/skills/project-analyze/phases/04-report-generation.md new file mode 100644 index 00000000..566b2e1d --- /dev/null +++ b/.claude/skills/project-analyze/phases/04-report-generation.md @@ -0,0 +1,94 @@ +# Phase 4: Report Generation + +Assemble analysis and diagrams into structured Markdown report. + +## Execution + +### Step 1: Determine Report Sections + +```javascript +const reportSections = { + architecture: [ + "# Architecture Report", + "## Executive Summary", + "## System Overview", + "## Layer Analysis", + "## Module Dependencies", + "## Data Flow", + "## Entry Points & Critical Paths", + "## Dependency Graph", + "## Recommendations" + ], + design: [ + "# Design Report", + "## Executive Summary", + "## Design Patterns Used", + "## Class Relationships", + "## Interface Contracts", + "## State Management", + "## Component Diagrams", + "## Design Recommendations" + ], + methods: [ + "# Key Methods Report", + "## Executive Summary", + "## Core Algorithms", + "## Critical Code Paths", + "## Public API Reference", + "## Complex Logic Breakdown", + "## Sequence Diagrams", + "## Optimization Suggestions" + ], + comprehensive: [ + "# Comprehensive Project Analysis", + "## Executive Summary", + "## Architecture Overview", + "## Design Patterns & Principles", + "## Key Methods & Algorithms", + "## System Diagrams", + "## Recommendations & Next Steps" + ] +}; + +const sections = reportSections[config.type]; +``` + +### Step 2: Generate Report Content + +```javascript +let report = ''; + +for (const section of sections) { + report += section + '\n\n'; + + // Add section content from analysis + const sectionContent = generateSectionContent(section, deepAnalysis); + report += sectionContent + '\n\n'; + + // Embed relevant diagrams + const relatedDiagrams = findRelatedDiagrams(section, diagrams); + for (const diagram of relatedDiagrams) { + report += `\`\`\`mermaid\n${Read(diagram.path)}\n\`\`\`\n\n`; + } +} +``` + +### Step 3: Add Code References + +Format all code references as `file:line`: + +```javascript +// Example: src/auth/login.ts:42 +const codeRef = `${finding.file}:${finding.line}`; +``` + +### Step 4: Write Report + +```javascript +const reportFileName = `${config.type.toUpperCase()}-REPORT.md`; +Write(`${outputDir}/${reportFileName}`, report); +``` + +## Output + +Generate `{TYPE}-REPORT.md` in output directory. diff --git a/.claude/skills/project-analyze/phases/05-iterative-refinement.md b/.claude/skills/project-analyze/phases/05-iterative-refinement.md new file mode 100644 index 00000000..09747098 --- /dev/null +++ b/.claude/skills/project-analyze/phases/05-iterative-refinement.md @@ -0,0 +1,124 @@ +# Phase 5: Iterative Refinement + +Discovery-driven refinement based on analysis findings. + +## Execution + +### Step 1: Extract Discoveries + +```javascript +function extractDiscoveries(deepAnalysis) { + return { + ambiguities: deepAnalysis.findings.filter(f => f.confidence < 0.7), + complexityHotspots: deepAnalysis.findings.filter(f => f.complexity === 'high'), + patternDeviations: deepAnalysis.patterns.filter(p => p.consistency < 0.8), + unclearDependencies: deepAnalysis.dependencies.filter(d => d.type === 'implicit'), + potentialIssues: deepAnalysis.recommendations.filter(r => r.priority === 'investigate'), + depthOpportunities: deepAnalysis.sections.filter(s => s.has_more_detail) + }; +} + +const discoveries = extractDiscoveries(deepAnalysis); +``` + +### Step 2: Build Dynamic Questions + +Questions emerge from discoveries, NOT predetermined: + +```javascript +function buildDynamicQuestions(discoveries, config) { + const questions = []; + + if (discoveries.ambiguities.length > 0) { + questions.push({ + question: `Analysis found ambiguity in "${discoveries.ambiguities[0].area}". Which interpretation is correct?`, + header: "Clarify", + options: discoveries.ambiguities[0].interpretations + }); + } + + if (discoveries.complexityHotspots.length > 0) { + questions.push({ + question: `These areas have high complexity. Which would you like explained?`, + header: "Deep-Dive", + multiSelect: true, + options: discoveries.complexityHotspots.slice(0, 4).map(h => ({ + label: h.name, + description: h.summary + })) + }); + } + + if (discoveries.patternDeviations.length > 0) { + questions.push({ + question: `Found pattern deviations. Should these be highlighted in the report?`, + header: "Patterns", + options: [ + {label: "Yes, include analysis", description: "Add section explaining deviations"}, + {label: "No, skip", description: "Omit from report"} + ] + }); + } + + // Always include action question + questions.push({ + question: "How would you like to proceed?", + header: "Action", + options: [ + {label: "Continue refining", description: "Address more discoveries"}, + {label: "Finalize report", description: "Generate final output"}, + {label: "Change scope", description: "Modify analysis scope"} + ] + }); + + return questions.slice(0, 4); // Max 4 questions +} +``` + +### Step 3: Apply Refinements + +```javascript +if (userAction === "Continue refining") { + // Apply selected refinements + for (const selection of userSelections) { + applyRefinement(selection, deepAnalysis, report); + } + + // Save iteration + Write(`${outputDir}/iterations/iteration-${iterationCount}.json`, { + timestamp: new Date().toISOString(), + discoveries: discoveries, + selections: userSelections, + changes: appliedChanges + }); + + // Loop back to Step 1 + iterationCount++; + goto Step1; +} + +if (userAction === "Finalize report") { + // Proceed to final output + goto FinalizeReport; +} +``` + +### Step 4: Finalize Report + +```javascript +// Add iteration history to report metadata +const finalReport = { + ...report, + metadata: { + iterations: iterationCount, + refinements_applied: allRefinements, + final_discoveries: discoveries + } +}; + +Write(`${outputDir}/${config.type.toUpperCase()}-REPORT.md`, finalReport); +``` + +## Output + +Updated report with refinements, saved iterations to `iterations/` folder. diff --git a/.claude/skills/project-analyze/specs/quality-standards.md b/.claude/skills/project-analyze/specs/quality-standards.md new file mode 100644 index 00000000..c68f12f1 --- /dev/null +++ b/.claude/skills/project-analyze/specs/quality-standards.md @@ -0,0 +1,115 @@ +# Quality Standards + +Quality gates and requirements for project analysis reports. + +## When to Use + +| Phase | Usage | Section | +|-------|-------|---------| +| Phase 4 | Check report structure before assembly | Report Requirements | +| Phase 5 | Validate before each iteration | Quality Gates | +| Phase 5 | Handle failures during refinement | Error Handling | + +--- + +## Report Requirements + +**Use in Phase 4**: Ensure report includes all required elements. + +| Requirement | Check | How to Fix | +|-------------|-------|------------| +| Executive Summary | 3-5 key takeaways | Extract from analysis findings | +| Visual diagrams | Valid Mermaid syntax | Use `../_shared/mermaid-utils.md` | +| Code references | `file:line` format | Link to actual source locations | +| Recommendations | Actionable, specific | Derive from analysis insights | +| Consistent depth | Match user's depth level | Adjust detail per config.depth | + +--- + +## Quality Gates + +**Use in Phase 5**: Run these checks before asking user questions. + +```javascript +function runQualityGates(report, config, diagrams) { + const gates = [ + { + name: "focus_areas_covered", + check: () => config.focus_areas.every(area => + report.toLowerCase().includes(area.toLowerCase()) + ), + fix: "Re-analyze missing focus areas" + }, + { + name: "diagrams_valid", + check: () => diagrams.every(d => d.valid), + fix: "Regenerate failed diagrams with mermaid-utils" + }, + { + name: "code_refs_accurate", + check: () => extractCodeRefs(report).every(ref => fileExists(ref)), + fix: "Update invalid file references" + }, + { + name: "no_placeholders", + check: () => !report.includes('[TODO]') && !report.includes('[PLACEHOLDER]'), + fix: "Fill in all placeholder content" + }, + { + name: "recommendations_specific", + check: () => !report.includes('consider') || report.includes('specifically'), + fix: "Make recommendations project-specific" + } + ]; + + const results = gates.map(g => ({...g, passed: g.check()})); + const allPassed = results.every(r => r.passed); + + return { allPassed, results }; +} +``` + +**Integration with Phase 5**: +```javascript +// In 05-iterative-refinement.md +const { allPassed, results } = runQualityGates(report, config, diagrams); + +if (allPassed) { + // All gates passed → ask user to confirm or finalize +} else { + // Gates failed → include failed gates in discovery questions + const failedGates = results.filter(r => !r.passed); + discoveries.qualityIssues = failedGates; +} +``` + +--- + +## Error Handling + +**Use when**: Encountering errors during any phase. + +| Error | Detection | Recovery | +|-------|-----------|----------| +| CLI timeout | Bash exits with timeout | Reduce scope via `config.scope`, retry | +| Exploration failure | Agent returns error | Fall back to `Read` + `Grep` directly | +| User abandons | User selects "cancel" | Save to `iterations/`, allow resume | +| Invalid scope path | Path doesn't exist | `AskUserQuestion` to correct path | +| Diagram validation fails | `validateMermaidSyntax` returns issues | Regenerate with stricter escaping | + +**Recovery Flow**: +```javascript +try { + await executePhase(phase); +} catch (error) { + const recovery = ERROR_HANDLERS[error.type]; + if (recovery) { + await recovery.action(error, config); + // Retry phase or continue + } else { + // Save progress and ask user + Write(`${outputDir}/error-state.json`, { phase, error, config }); + AskUserQuestion({ question: "遇到错误,如何处理?", ... }); + } +} +``` diff --git a/ccw/.gitignore b/ccw/.gitignore index 663aef67..131ce0dc 100644 --- a/ccw/.gitignore +++ b/ccw/.gitignore @@ -1,3 +1,4 @@ # TypeScript build output dist/ +.ace-tool/ diff --git a/ccw/src/core/routes/cli-routes.ts b/ccw/src/core/routes/cli-routes.ts index 3146adb0..b594e8ed 100644 --- a/ccw/src/core/routes/cli-routes.ts +++ b/ccw/src/core/routes/cli-routes.ts @@ -769,9 +769,9 @@ export async function handleCliRoutes(ctx: RouteContext): Promise { if (pathname === '/api/cli/code-index-mcp' && req.method === 'PUT') { handlePostRequest(req, res, async (body: unknown) => { try { - const { provider } = body as { provider: 'codexlens' | 'ace' }; - if (!provider || !['codexlens', 'ace'].includes(provider)) { - return { error: 'Invalid provider. Must be "codexlens" or "ace"', status: 400 }; + const { provider } = body as { provider: 'codexlens' | 'ace' | 'none' }; + if (!provider || !['codexlens', 'ace', 'none'].includes(provider)) { + return { error: 'Invalid provider. Must be "codexlens", "ace", or "none"', status: 400 }; } const result = updateCodeIndexMcp(initialPath, provider); diff --git a/ccw/src/templates/dashboard-js/components/cli-status.js b/ccw/src/templates/dashboard-js/components/cli-status.js index 03dbc8d7..1f69a901 100644 --- a/ccw/src/templates/dashboard-js/components/cli-status.js +++ b/ccw/src/templates/dashboard-js/components/cli-status.js @@ -21,9 +21,24 @@ let nativeResumeEnabled = localStorage.getItem('ccw-native-resume') !== 'false'; // Recursive Query settings (for hierarchical storage aggregation) let recursiveQueryEnabled = localStorage.getItem('ccw-recursive-query') !== 'false'; // default true -// Code Index MCP provider (codexlens or ace) +// Code Index MCP provider (codexlens, ace, or none) let codeIndexMcpProvider = 'codexlens'; +// ========== Helper Functions ========== +/** + * Get the context-tools filename based on provider + */ +function getContextToolsFileName(provider) { + switch (provider) { + case 'ace': + return 'context-tools-ace.md'; + case 'none': + return 'context-tools-none.md'; + default: + return 'context-tools.md'; + } +} + // ========== Initialization ========== function initCliStatus() { // Load all statuses in one call using aggregated endpoint @@ -637,9 +652,17 @@ function renderCliStatus() { onclick="setCodeIndexMcpProvider('ace')"> ACE +

Code search provider (updates CLAUDE.md context-tools reference)

+

+ + Current: ${getContextToolsFileName(codeIndexMcpProvider)} +

@@ -775,7 +798,8 @@ async function setCodeIndexMcpProvider(provider) { if (window.claudeCliToolsConfig && window.claudeCliToolsConfig.settings) { window.claudeCliToolsConfig.settings.codeIndexMcp = provider; } - showRefreshToast(`Code Index MCP switched to ${provider === 'ace' ? 'ACE (Augment)' : 'CodexLens'}`, 'success'); + const providerName = provider === 'ace' ? 'ACE (Augment)' : provider === 'none' ? 'None (Built-in only)' : 'CodexLens'; + showRefreshToast(`Code Index MCP switched to ${providerName}`, 'success'); // Re-render both CLI status and settings section if (typeof renderCliStatus === 'function') renderCliStatus(); if (typeof renderCliSettingsSection === 'function') renderCliSettingsSection(); diff --git a/ccw/src/templates/dashboard-js/views/cli-manager.js b/ccw/src/templates/dashboard-js/views/cli-manager.js index 6427d757..9392c5cf 100644 --- a/ccw/src/templates/dashboard-js/views/cli-manager.js +++ b/ccw/src/templates/dashboard-js/views/cli-manager.js @@ -996,9 +996,14 @@ function renderCliSettingsSection() { '' + '' + '

' + t('cli.codeIndexMcpDesc') + '

' + + '

' + + '' + + 'Current: ' + getContextToolsFileName(codeIndexMcpProvider) + '' + + '

' + '' + ''; diff --git a/ccw/src/templates/dashboard-js/views/history.js b/ccw/src/templates/dashboard-js/views/history.js index 25523c75..2e3a0111 100644 --- a/ccw/src/templates/dashboard-js/views/history.js +++ b/ccw/src/templates/dashboard-js/views/history.js @@ -70,7 +70,7 @@ async function renderCliHistoryView() { : ''; historyHtml += '
' + + 'onclick="' + (isMultiSelectMode ? 'toggleExecutionSelection(\'' + exec.id + '\')' : 'showExecutionDetail(\'' + exec.id + '\', \'' + (exec.sourceDir || '').replace(/\'/g, "\\'") + '\')') + '">' + checkboxHtml + '
' + '
' + @@ -87,14 +87,17 @@ async function renderCliHistoryView() { '
' + ' ' + timeAgo + '' + ' ' + duration + '' + - ' ' + exec.id.split('-')[0] + '' + + ' ' + exec.id.substring(0, 13) + '...' + exec.id.split('-').pop() + '' + '
' + '
' + '
' + - '' + + '' + - '' + '
' + diff --git a/ccw/src/tools/claude-cli-tools.ts b/ccw/src/tools/claude-cli-tools.ts index 6b9f1af0..9f5fedc1 100644 --- a/ccw/src/tools/claude-cli-tools.ts +++ b/ccw/src/tools/claude-cli-tools.ts @@ -42,7 +42,7 @@ export interface ClaudeCliToolsConfig { nativeResume: boolean; recursiveQuery: boolean; cache: ClaudeCacheSettings; - codeIndexMcp: 'codexlens' | 'ace'; // Code Index MCP provider + codeIndexMcp: 'codexlens' | 'ace' | 'none'; // Code Index MCP provider }; } @@ -308,7 +308,7 @@ export function getClaudeCliToolsInfo(projectDir: string): { */ export function updateCodeIndexMcp( projectDir: string, - provider: 'codexlens' | 'ace' + provider: 'codexlens' | 'ace' | 'none' ): { success: boolean; error?: string; config?: ClaudeCliToolsConfig } { try { // Update config @@ -319,21 +319,28 @@ export function updateCodeIndexMcp( // Only update global CLAUDE.md (consistent with Chinese response / Windows platform) const globalClaudeMdPath = path.join(os.homedir(), '.claude', 'CLAUDE.md'); + // Define patterns for all formats + const codexlensPattern = /@~\/\.claude\/workflows\/context-tools\.md/g; + const acePattern = /@~\/\.claude\/workflows\/context-tools-ace\.md/g; + const nonePattern = /@~\/\.claude\/workflows\/context-tools-none\.md/g; + + // Determine target file based on provider + const targetFile = provider === 'ace' + ? '@~/.claude/workflows/context-tools-ace.md' + : provider === 'none' + ? '@~/.claude/workflows/context-tools-none.md' + : '@~/.claude/workflows/context-tools.md'; + if (!fs.existsSync(globalClaudeMdPath)) { // If global CLAUDE.md doesn't exist, check project-level const projectClaudeMdPath = path.join(projectDir, '.claude', 'CLAUDE.md'); if (fs.existsSync(projectClaudeMdPath)) { let content = fs.readFileSync(projectClaudeMdPath, 'utf-8'); - // Define patterns for both formats - const codexlensPattern = /@~\/\.claude\/workflows\/context-tools\.md/g; - const acePattern = /@~\/\.claude\/workflows\/context-tools-ace\.md/g; - - if (provider === 'ace') { - content = content.replace(codexlensPattern, '@~/.claude/workflows/context-tools-ace.md'); - } else { - content = content.replace(acePattern, '@~/.claude/workflows/context-tools.md'); - } + // Replace any existing pattern with the target + content = content.replace(codexlensPattern, targetFile); + content = content.replace(acePattern, targetFile); + content = content.replace(nonePattern, targetFile); fs.writeFileSync(projectClaudeMdPath, content, 'utf-8'); console.log(`[claude-cli-tools] Updated project CLAUDE.md to use ${provider} (no global CLAUDE.md found)`); @@ -342,14 +349,10 @@ export function updateCodeIndexMcp( // Update global CLAUDE.md (primary target) let content = fs.readFileSync(globalClaudeMdPath, 'utf-8'); - const codexlensPattern = /@~\/\.claude\/workflows\/context-tools\.md/g; - const acePattern = /@~\/\.claude\/workflows\/context-tools-ace\.md/g; - - if (provider === 'ace') { - content = content.replace(codexlensPattern, '@~/.claude/workflows/context-tools-ace.md'); - } else { - content = content.replace(acePattern, '@~/.claude/workflows/context-tools.md'); - } + // Replace any existing pattern with the target + content = content.replace(codexlensPattern, targetFile); + content = content.replace(acePattern, targetFile); + content = content.replace(nonePattern, targetFile); fs.writeFileSync(globalClaudeMdPath, content, 'utf-8'); console.log(`[claude-cli-tools] Updated global CLAUDE.md to use ${provider}`); @@ -365,7 +368,21 @@ export function updateCodeIndexMcp( /** * Get current Code Index MCP provider */ -export function getCodeIndexMcp(projectDir: string): 'codexlens' | 'ace' { +export function getCodeIndexMcp(projectDir: string): 'codexlens' | 'ace' | 'none' { const config = loadClaudeCliTools(projectDir); return config.settings.codeIndexMcp || 'codexlens'; } + +/** + * Get the context-tools file path based on provider + */ +export function getContextToolsPath(provider: 'codexlens' | 'ace' | 'none'): string { + switch (provider) { + case 'ace': + return 'context-tools-ace.md'; + case 'none': + return 'context-tools-none.md'; + default: + return 'context-tools.md'; + } +}