From b3c47294e7861dc35b24272c0355de044fc7cc0f Mon Sep 17 00:00:00 2001 From: catlog22 Date: Wed, 28 Jan 2026 00:02:45 +0800 Subject: [PATCH] Enhance workflow commands and context management - Updated `plan.md` to include new fields in context-package.json: prioritized_context, user_intent, priority_tiers, dependency_order, and sorting_rationale. - Added validation for the existence of the prioritized_context field in context-package.json. - Modified user decision flow in task generation to present action choices after planning completion. - Improved context-gathering process in `context-gather.md` to integrate user intent and prioritize context based on user goals. - Revised conflict-resolution documentation to require planning notes records after conflict analysis. - Streamlined task generation in `task-generate-agent.md` to utilize pre-sorted context without redundant sorting. - Removed unused settings persistence functions and corresponding tests from `claude-cli-tools.ts` and `settings-persistence.test.ts`. --- .../commands/workflow/action-plan-verify.md | 485 ------------ .claude/commands/workflow/plan-verify.md | 740 ++++++++++++------ .claude/commands/workflow/plan.md | 69 +- .../workflow/tools/conflict-resolution.md | 11 + .../commands/workflow/tools/context-gather.md | 94 ++- .../workflow/tools/task-generate-agent.md | 86 +- ccw/src/tools/claude-cli-tools.ts | 60 -- ccw/tests/settings-persistence.test.ts | 375 --------- 8 files changed, 744 insertions(+), 1176 deletions(-) delete mode 100644 .claude/commands/workflow/action-plan-verify.md delete mode 100644 ccw/tests/settings-persistence.test.ts diff --git a/.claude/commands/workflow/action-plan-verify.md b/.claude/commands/workflow/action-plan-verify.md deleted file mode 100644 index 8ae2222a..00000000 --- a/.claude/commands/workflow/action-plan-verify.md +++ /dev/null @@ -1,485 +0,0 @@ ---- -name: plan-verify -description: Perform READ-ONLY verification analysis between IMPL_PLAN.md, task JSONs, and brainstorming artifacts. Generates structured report with quality gate recommendation. Does NOT modify any files. -argument-hint: "[optional: --session session-id]" -allowed-tools: Read(*), Write(*), Glob(*), Bash(*) ---- - -## User Input - -```text -$ARGUMENTS -``` - -You **MUST** consider the user input before proceeding (if not empty). - -## Goal - -Generate a comprehensive verification report that identifies inconsistencies, duplications, ambiguities, and underspecified items between action planning artifacts (`IMPL_PLAN.md`, `task.json`) and brainstorming artifacts (`role analysis documents`). This command MUST run only after `/workflow:plan` has successfully produced complete `IMPL_PLAN.md` and task JSON files. - -**Output**: A structured Markdown report saved to `.workflow/active/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md` containing: -- Executive summary with quality gate recommendation -- Detailed findings by severity (CRITICAL/HIGH/MEDIUM/LOW) -- Requirements coverage analysis -- Dependency integrity check -- Synthesis alignment validation -- Actionable remediation recommendations - -## Operating Constraints - -**STRICTLY READ-ONLY FOR SOURCE ARTIFACTS**: -- **MUST NOT** modify `IMPL_PLAN.md`, any `task.json` files, or brainstorming artifacts -- **MUST NOT** create or delete task files -- **MUST ONLY** write the verification report to `.process/ACTION_PLAN_VERIFICATION.md` - -**Synthesis Authority**: The `role analysis documents` are **authoritative** for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements. - -**Quality Gate Authority**: The verification report provides a binding recommendation (BLOCK_EXECUTION / PROCEED_WITH_FIXES / PROCEED_WITH_CAUTION / PROCEED) based on objective severity criteria. User MUST review critical/high issues before proceeding with implementation. - -## Execution Steps - -### 1. Initialize Analysis Context - -```bash -# Detect active workflow session -IF --session parameter provided: - session_id = provided session -ELSE: - # Auto-detect active session - active_sessions = bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null) - IF active_sessions is empty: - ERROR: "No active workflow session found. Use --session " - EXIT - ELSE IF active_sessions has multiple entries: - # Use most recently modified session - session_id = bash(ls -td .workflow/active/WFS-*/ 2>/dev/null | head -1 | xargs basename) - ELSE: - session_id = basename(active_sessions[0]) - -# Derive absolute paths -session_dir = .workflow/active/WFS-{session} -brainstorm_dir = session_dir/.brainstorming -task_dir = session_dir/.task -process_dir = session_dir/.process -session_file = session_dir/workflow-session.json - -# Create .process directory if not exists (report output location) -IF NOT EXISTS(process_dir): - bash(mkdir -p "{process_dir}") - -# Validate required artifacts -# Note: "role analysis documents" refers to [role]/analysis.md files (e.g., product-manager/analysis.md) -SYNTHESIS_DIR = brainstorm_dir # Contains role analysis files: */analysis.md -IMPL_PLAN = session_dir/IMPL_PLAN.md -TASK_FILES = Glob(task_dir/*.json) - -# Abort if missing - in order of dependency -SESSION_FILE_EXISTS = EXISTS(session_file) -IF NOT SESSION_FILE_EXISTS: - WARNING: "workflow-session.json not found. User intent alignment verification will be skipped." - # Continue execution - this is optional context, not blocking - -SYNTHESIS_FILES = Glob(brainstorm_dir/*/analysis.md) -IF SYNTHESIS_FILES.count == 0: - ERROR: "No role analysis documents found in .brainstorming/*/analysis.md. Run /workflow:brainstorm:synthesis first" - EXIT - -IF NOT EXISTS(IMPL_PLAN): - ERROR: "IMPL_PLAN.md not found. Run /workflow:plan first" - EXIT - -IF TASK_FILES.count == 0: - ERROR: "No task JSON files found. Run /workflow:plan first" - EXIT -``` - -### 2. Load Artifacts (Progressive Disclosure) - -Load only minimal necessary context from each artifact: - -**From workflow-session.json** (OPTIONAL - Primary Reference for User Intent): -- **ONLY IF EXISTS**: Load user intent context -- Original user prompt/intent (project or description field) -- User's stated goals and objectives -- User's scope definition -- **IF MISSING**: Set user_intent_analysis = "SKIPPED: workflow-session.json not found" - -**From role analysis documents** (AUTHORITATIVE SOURCE): -- Functional Requirements (IDs, descriptions, acceptance criteria) -- Non-Functional Requirements (IDs, targets) -- Business Requirements (IDs, success metrics) -- Key Architecture Decisions -- Risk factors and mitigation strategies -- Implementation Roadmap (high-level phases) - -**From IMPL_PLAN.md**: -- Summary and objectives -- Context Analysis -- Implementation Strategy -- Task Breakdown Summary -- Success Criteria -- Brainstorming Artifacts References (if present) - -**From task.json files**: -- Task IDs -- Titles and descriptions -- Status -- Dependencies (depends_on, blocks) -- Context (requirements, focus_paths, acceptance, artifacts) -- Flow control (pre_analysis, implementation_approach) -- Meta (complexity, priority) - -### 3. Build Semantic Models - -Create internal representations (do not include raw artifacts in output): - -**Requirements inventory**: -- Each functional/non-functional/business requirement with stable ID -- Requirement text, acceptance criteria, priority - -**Architecture decisions inventory**: -- ADRs from synthesis -- Technology choices -- Data model references - -**Task coverage mapping**: -- Map each task to one or more requirements (by ID reference or keyword inference) -- Map each requirement to covering tasks - -**Dependency graph**: -- Task-to-task dependencies (depends_on, blocks) -- Requirement-level dependencies (from synthesis) - -### 4. Detection Passes (Token-Efficient Analysis) - -**Token Budget Strategy**: -- **Total Limit**: 50 findings maximum (aggregate remainder in overflow summary) -- **Priority Allocation**: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15) -- **Early Exit**: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM priority checks - -**Execution Order** (Process in sequence; skip if token budget exhausted): - -1. **Tier 1 (CRITICAL Path)**: A, B, C - User intent, coverage, consistency (process fully) -2. **Tier 2 (HIGH Priority)**: D, E - Dependencies, synthesis alignment (limit 15 findings total) -3. **Tier 3 (MEDIUM Priority)**: F - Specification quality (limit 20 findings) -4. **Tier 4 (LOW Priority)**: G, H - Duplication, feasibility (limit 15 findings total) - ---- - -#### A. User Intent Alignment (CRITICAL - Tier 1) - -- **Goal Alignment**: IMPL_PLAN objectives match user's original intent -- **Scope Drift**: Plan covers user's stated scope without unauthorized expansion -- **Success Criteria Match**: Plan's success criteria reflect user's expectations -- **Intent Conflicts**: Tasks contradicting user's original objectives - -#### B. Requirements Coverage Analysis - -- **Orphaned Requirements**: Requirements in synthesis with zero associated tasks -- **Unmapped Tasks**: Tasks with no clear requirement linkage -- **NFR Coverage Gaps**: Non-functional requirements (performance, security, scalability) not reflected in tasks - -#### C. Consistency Validation - -- **Requirement Conflicts**: Tasks contradicting synthesis requirements -- **Architecture Drift**: IMPL_PLAN architecture not matching synthesis ADRs -- **Terminology Drift**: Same concept named differently across IMPL_PLAN and tasks -- **Data Model Inconsistency**: Tasks referencing entities/fields not in synthesis data model - -#### D. Dependency Integrity - -- **Circular Dependencies**: Task A depends on B, B depends on C, C depends on A -- **Missing Dependencies**: Task requires outputs from another task but no explicit dependency -- **Broken Dependencies**: Task depends on non-existent task ID -- **Logical Ordering Issues**: Implementation tasks before foundational setup without dependency note - -#### E. Synthesis Alignment - -- **Priority Conflicts**: High-priority synthesis requirements mapped to low-priority tasks -- **Success Criteria Mismatch**: IMPL_PLAN success criteria not covering synthesis acceptance criteria -- **Risk Mitigation Gaps**: Critical risks in synthesis without corresponding mitigation tasks - -#### F. Task Specification Quality - -- **Ambiguous Focus Paths**: Tasks with vague or missing focus_paths -- **Underspecified Acceptance**: Tasks without clear acceptance criteria -- **Missing Artifacts References**: Tasks not referencing relevant brainstorming artifacts in context.artifacts -- **Weak Flow Control**: Tasks without clear implementation_approach or pre_analysis steps -- **Missing Target Files**: Tasks without flow_control.target_files specification - -#### G. Duplication Detection - -- **Overlapping Task Scope**: Multiple tasks with nearly identical descriptions -- **Redundant Requirements Coverage**: Same requirement covered by multiple tasks without clear partitioning - -#### H. Feasibility Assessment - -- **Complexity Misalignment**: Task marked "simple" but requires multiple file modifications -- **Resource Conflicts**: Parallel tasks requiring same resources/files -- **Skill Gap Risks**: Tasks requiring skills not in team capability assessment (from synthesis) - -### 5. Severity Assignment - -Use this heuristic to prioritize findings: - -- **CRITICAL**: - - Violates user's original intent (goal misalignment, scope drift) - - Violates synthesis authority (requirement conflict) - - Core requirement with zero coverage - - Circular dependencies - - Broken dependencies - -- **HIGH**: - - NFR coverage gaps - - Priority conflicts - - Missing risk mitigation tasks - - Ambiguous acceptance criteria - -- **MEDIUM**: - - Terminology drift - - Missing artifacts references - - Weak flow control - - Logical ordering issues - -- **LOW**: - - Style/wording improvements - - Minor redundancy not affecting execution - -### 6. Produce Compact Analysis Report - -**Report Generation**: Generate report content and save to file. - -Output a Markdown report with the following structure: - -```markdown -## Action Plan Verification Report - -**Session**: WFS-{session-id} -**Generated**: {timestamp} -**Artifacts Analyzed**: role analysis documents, IMPL_PLAN.md, {N} task files - ---- - -### Executive Summary - -- **Overall Risk Level**: CRITICAL | HIGH | MEDIUM | LOW -- **Recommendation**: (See decision matrix below) - - BLOCK_EXECUTION: Critical issues exist (must fix before proceeding) - - PROCEED_WITH_FIXES: High issues exist, no critical (fix recommended before execution) - - PROCEED_WITH_CAUTION: Medium issues only (proceed with awareness) - - PROCEED: Low issues only or no issues (safe to execute) -- **Critical Issues**: {count} -- **High Issues**: {count} -- **Medium Issues**: {count} -- **Low Issues**: {count} - ---- - -### Findings Summary - -| ID | Category | Severity | Location(s) | Summary | Recommendation | -|----|----------|----------|-------------|---------|----------------| -| C1 | Coverage | CRITICAL | synthesis:FR-03 | Requirement "User auth" has zero task coverage | Add authentication implementation task | -| H1 | Consistency | HIGH | IMPL-1.2 vs synthesis:ADR-02 | Task uses REST while synthesis specifies GraphQL | Align task with ADR-02 decision | -| M1 | Specification | MEDIUM | IMPL-2.1 | Missing context.artifacts reference | Add @synthesis reference | -| L1 | Duplication | LOW | IMPL-3.1, IMPL-3.2 | Similar scope | Consider merging | - -(Add one row per finding; generate stable IDs prefixed by severity initial.) - ---- - -### Requirements Coverage Analysis - -| Requirement ID | Requirement Summary | Has Task? | Task IDs | Priority Match | Notes | -|----------------|---------------------|-----------|----------|----------------|-------| -| FR-01 | User authentication | Yes | IMPL-1.1, IMPL-1.2 | Match | Complete | -| FR-02 | Data export | Yes | IMPL-2.3 | Mismatch | High req → Med priority task | -| FR-03 | Profile management | No | - | - | **CRITICAL: Zero coverage** | -| NFR-01 | Response time <200ms | No | - | - | **HIGH: No performance tasks** | - -**Coverage Metrics**: -- Functional Requirements: 85% (17/20 covered) -- Non-Functional Requirements: 40% (2/5 covered) -- Business Requirements: 100% (5/5 covered) - ---- - -### Unmapped Tasks - -| Task ID | Title | Issue | Recommendation | -|---------|-------|-------|----------------| -| IMPL-4.5 | Refactor utils | No requirement linkage | Link to technical debt or remove | - ---- - -### Dependency Graph Issues - -**Circular Dependencies**: None detected - -**Broken Dependencies**: -- IMPL-2.3 depends on "IMPL-2.4" (non-existent) - -**Logical Ordering Issues**: -- IMPL-5.1 (integration test) has no dependency on IMPL-1.* (implementation tasks) - ---- - -### Synthesis Alignment Issues - -| Issue Type | Synthesis Reference | IMPL_PLAN/Task | Impact | Recommendation | -|------------|---------------------|----------------|--------|----------------| -| Architecture Conflict | synthesis:ADR-01 (JWT auth) | IMPL_PLAN uses session cookies | HIGH | Update IMPL_PLAN to use JWT | -| Priority Mismatch | synthesis:FR-02 (High) | IMPL-2.3 (Medium) | MEDIUM | Elevate task priority | -| Missing Risk Mitigation | synthesis:Risk-03 (API rate limits) | No mitigation tasks | HIGH | Add rate limiting implementation task | - ---- - -### Task Specification Quality Issues - -**Missing Artifacts References**: 12 tasks lack context.artifacts -**Weak Flow Control**: 5 tasks lack implementation_approach -**Missing Target Files**: 8 tasks lack flow_control.target_files - -**Sample Issues**: -- IMPL-1.2: No context.artifacts reference to synthesis -- IMPL-3.1: Missing flow_control.target_files specification -- IMPL-4.2: Vague focus_paths ["src/"] - needs refinement - ---- - -### Feasibility Concerns - -| Concern | Tasks Affected | Issue | Recommendation | -|---------|----------------|-------|----------------| -| Skill Gap | IMPL-6.1, IMPL-6.2 | Requires Kubernetes expertise not in team | Add training task or external consultant | -| Resource Conflict | IMPL-3.1, IMPL-3.2 | Both modify src/auth/service.ts in parallel | Add dependency or serialize | - ---- - -### Metrics - -- **Total Requirements**: 30 (20 functional, 5 non-functional, 5 business) -- **Total Tasks**: 25 -- **Overall Coverage**: 77% (23/30 requirements with ≥1 task) -- **Critical Issues**: 2 -- **High Issues**: 5 -- **Medium Issues**: 8 -- **Low Issues**: 3 - ---- - -### Next Actions - -#### Action Recommendations - -**Recommendation Decision Matrix**: - -| Condition | Recommendation | Action | -|-----------|----------------|--------| -| Critical > 0 | BLOCK_EXECUTION | Must resolve all critical issues before proceeding | -| Critical = 0, High > 0 | PROCEED_WITH_FIXES | Fix high-priority issues before execution | -| Critical = 0, High = 0, Medium > 0 | PROCEED_WITH_CAUTION | Proceed with awareness of medium issues | -| Only Low or None | PROCEED | Safe to execute workflow | - -**If CRITICAL Issues Exist** (BLOCK_EXECUTION): -- Resolve all critical issues before proceeding -- Use TodoWrite to track required fixes -- Fix broken dependencies and circular references first - -**If HIGH Issues Exist** (PROCEED_WITH_FIXES): -- Fix high-priority issues before execution -- Use TodoWrite to systematically track and complete improvements - -**If Only MEDIUM/LOW Issues** (PROCEED_WITH_CAUTION / PROCEED): -- Can proceed with execution -- Address issues during or after implementation - -#### TodoWrite-Based Remediation Workflow - -**Report Location**: `.workflow/active/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md` - -**Recommended Workflow**: -1. **Create TodoWrite Task List**: Extract all findings from report -2. **Process by Priority**: CRITICAL → HIGH → MEDIUM → LOW -3. **Complete Each Fix**: Mark tasks as in_progress/completed as you work -4. **Validate Changes**: Verify each modification against requirements - -**TodoWrite Task Structure Example**: -```markdown -Priority Order: -1. Fix coverage gaps (CRITICAL) -2. Resolve consistency conflicts (CRITICAL/HIGH) -3. Add missing specifications (MEDIUM) -4. Improve task quality (LOW) -``` - -**Notes**: -- TodoWrite provides real-time progress tracking -- Each finding becomes a trackable todo item -- User can monitor progress throughout remediation -- Architecture drift in IMPL_PLAN requires manual editing -``` - -### 7. Save Report and Execute TodoWrite-Based Remediation - -**Step 7.1: Save Analysis Report**: -```bash -report_path = ".workflow/active/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md" -Write(report_path, full_report_content) -``` - -**Step 7.2: Display Report Summary to User**: -- Show executive summary with counts -- Display recommendation (BLOCK/PROCEED_WITH_FIXES/PROCEED_WITH_CAUTION/PROCEED) -- List critical and high issues if any - -**Step 7.3: After Report Generation**: - -1. **Extract Findings**: Parse all issues by severity -2. **Create TodoWrite Task List**: Convert findings to actionable todos -3. **Execute Fixes**: Process each todo systematically -4. **Update Task Files**: Apply modifications directly to task JSON files -5. **Update IMPL_PLAN**: Apply strategic changes if needed - -At end of report, provide remediation guidance: - -```markdown -### 🔧 Remediation Workflow - -**Recommended Approach**: -1. **Initialize TodoWrite**: Create comprehensive task list from all findings -2. **Process by Severity**: Start with CRITICAL, then HIGH, MEDIUM, LOW -3. **Apply Fixes Directly**: Modify task.json files and IMPL_PLAN.md as needed -4. **Track Progress**: Mark todos as completed after each fix - -**TodoWrite Execution Pattern**: -```bash -# Step 1: Create task list from verification report -TodoWrite([ - { content: "Fix FR-03 coverage gap - add authentication task", status: "pending", activeForm: "Fixing FR-03 coverage gap" }, - { content: "Fix IMPL-1.2 consistency - align with ADR-02", status: "pending", activeForm: "Fixing IMPL-1.2 consistency" }, - { content: "Add context.artifacts to IMPL-1.2", status: "pending", activeForm: "Adding context.artifacts to IMPL-1.2" }, - # ... additional todos for each finding -]) - -# Step 2: Process each todo systematically -# Mark as in_progress when starting -# Apply fix using Read/Edit tools -# Mark as completed when done -# Move to next priority item -``` - -**File Modification Workflow**: -```bash -# For task JSON modifications: -1. Read(.workflow/active/WFS-{session}/.task/IMPL-X.Y.json) -2. Edit() to apply fixes -3. Mark todo as completed - -# For IMPL_PLAN modifications: -1. Read(.workflow/active/WFS-{session}/IMPL_PLAN.md) -2. Edit() to apply strategic changes -3. Mark todo as completed -``` - -**Note**: All fixes execute immediately after user confirmation without additional commands. diff --git a/.claude/commands/workflow/plan-verify.md b/.claude/commands/workflow/plan-verify.md index f0567f6e..01d5c065 100644 --- a/.claude/commands/workflow/plan-verify.md +++ b/.claude/commands/workflow/plan-verify.md @@ -150,114 +150,299 @@ Create internal representations (do not include raw artifacts in output): - Task-to-task dependencies (depends_on, blocks) - Requirement-level dependencies (from synthesis) -### 4. Detection Passes (Token-Efficient Analysis) +### 4. Detection Passes (Agent-Driven Multi-Dimensional Analysis) -**Token Budget Strategy**: -- **Total Limit**: 50 findings maximum (aggregate remainder in overflow summary) -- **Priority Allocation**: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15) -- **Early Exit**: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM priority checks +**Execution Strategy**: +- Single `cli-explore-agent` invocation +- Agent executes multiple CLI analyses internally (different dimensions: A-H) +- Token Budget: 50 findings maximum (aggregate remainder in overflow summary) +- Priority Allocation: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15) +- Early Exit: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM checks -**Execution Order** (Process in sequence; skip if token budget exhausted): +**Execution Order** (Agent orchestrates internally): -1. **Tier 1 (CRITICAL Path)**: A, B, C - User intent, coverage, consistency (process fully) -2. **Tier 2 (HIGH Priority)**: D, E - Dependencies, synthesis alignment (limit 15 findings total) +1. **Tier 1 (CRITICAL Path)**: A, B, C - User intent, coverage, consistency (full analysis) +2. **Tier 2 (HIGH Priority)**: D, E - Dependencies, synthesis alignment (limit 15 findings) 3. **Tier 3 (MEDIUM Priority)**: F - Specification quality (limit 20 findings) -4. **Tier 4 (LOW Priority)**: G, H - Duplication, feasibility (limit 15 findings total) +4. **Tier 4 (LOW Priority)**: G, H - Duplication, feasibility (limit 15 findings) --- -#### A. User Intent Alignment (CRITICAL - Tier 1) +#### Phase 4.1: Launch Unified Verification Agent -- **Goal Alignment**: IMPL_PLAN objectives match user's original intent -- **Scope Drift**: Plan covers user's stated scope without unauthorized expansion -- **Success Criteria Match**: Plan's success criteria reflect user's expectations -- **Intent Conflicts**: Tasks contradicting user's original objectives +**Single Agent, Multi-Dimensional Analysis**: -#### B. Requirements Coverage Analysis +```javascript +Task( + subagent_type="cli-explore-agent", + run_in_background=false, // ⚠️ MANDATORY: Must wait for results + description="Multi-dimensional plan verification", + prompt=` +## Plan Verification Task -- **Orphaned Requirements**: Requirements in synthesis with zero associated tasks -- **Unmapped Tasks**: Tasks with no clear requirement linkage -- **NFR Coverage Gaps**: Non-functional requirements (performance, security, scalability) not reflected in tasks +Execute comprehensive verification across dimensions A-H, using Gemini CLI for semantic analysis. -#### C. Consistency Validation +### MANDATORY FIRST STEPS +1. Read: ${session_file} (user intent/context) +2. Read: ${IMPL_PLAN} (implementation plan) +3. Glob: ${task_dir}/*.json (all task JSON files) +4. Glob: ${SYNTHESIS_DIR}/*/analysis.md (role analysis documents) +5. Read: \~/.claude/workflows/cli-templates/schemas/verify-json-schema.json (output schema reference) -- **Requirement Conflicts**: Tasks contradicting synthesis requirements -- **Architecture Drift**: IMPL_PLAN architecture not matching synthesis ADRs -- **Terminology Drift**: Same concept named differently across IMPL_PLAN and tasks -- **Data Model Inconsistency**: Tasks referencing entities/fields not in synthesis data model +### Output Location +${process_dir}/verification-findings.json -#### D. Dependency Integrity +### Verification Dimensions -- **Circular Dependencies**: Task A depends on B, B depends on C, C depends on A -- **Missing Dependencies**: Task requires outputs from another task but no explicit dependency -- **Broken Dependencies**: Task depends on non-existent task ID -- **Logical Ordering Issues**: Implementation tasks before foundational setup without dependency note +#### Dimension A: User Intent Alignment (CRITICAL - Tier 1) +- Goal Alignment: IMPL_PLAN objectives match user's original intent +- Scope Drift: Plan covers user's stated scope without unauthorized expansion +- Success Criteria Match: Plan's success criteria reflect user's expectations +- Intent Conflicts: Tasks contradicting user's original objectives -#### E. Synthesis Alignment +#### Dimension B: Requirements Coverage Analysis (CRITICAL - Tier 1) +- Orphaned Requirements: Requirements in synthesis with zero associated tasks +- Unmapped Tasks: Tasks with no clear requirement linkage +- NFR Coverage Gaps: Non-functional requirements not reflected in tasks -- **Priority Conflicts**: High-priority synthesis requirements mapped to low-priority tasks -- **Success Criteria Mismatch**: IMPL_PLAN success criteria not covering synthesis acceptance criteria -- **Risk Mitigation Gaps**: Critical risks in synthesis without corresponding mitigation tasks +#### Dimension C: Consistency Validation (CRITICAL - Tier 1) +- Requirement Conflicts: Tasks contradicting synthesis requirements +- Architecture Drift: IMPL_PLAN architecture not matching synthesis ADRs +- Terminology Drift: Same concept named differently across artifacts +- Data Model Inconsistency: Tasks referencing entities/fields not in synthesis -#### F. Task Specification Quality +#### Dimension D: Dependency Integrity (HIGH - Tier 2) +- Circular Dependencies: Cyclic task dependencies +- Missing Dependencies: Task requires outputs from another task but no explicit dependency +- Broken Dependencies: Task depends on non-existent task ID +- Logical Ordering Issues: Implementation tasks before foundational setup -- **Ambiguous Focus Paths**: Tasks with vague or missing focus_paths -- **Underspecified Acceptance**: Tasks without clear acceptance criteria -- **Missing Artifacts References**: Tasks not referencing relevant brainstorming artifacts in context.artifacts -- **Weak Flow Control**: Tasks without clear implementation_approach or pre_analysis steps -- **Missing Target Files**: Tasks without flow_control.target_files specification +#### Dimension E: Synthesis Alignment (HIGH - Tier 2) +- Priority Conflicts: High-priority synthesis requirements mapped to low-priority tasks +- Success Criteria Mismatch: IMPL_PLAN success criteria not covering synthesis acceptance criteria +- Risk Mitigation Gaps: Critical risks without corresponding mitigation tasks -#### G. Duplication Detection +#### Dimension F: Task Specification Quality (MEDIUM - Tier 3) +- Ambiguous Focus Paths: Tasks with vague/missing focus_paths +- Underspecified Acceptance: Tasks without clear acceptance criteria +- Missing Artifacts References: Tasks not referencing brainstorming artifacts +- Weak Flow Control: Tasks without clear implementation_approach or pre_analysis +- Missing Target Files: Tasks without flow_control.target_files -- **Overlapping Task Scope**: Multiple tasks with nearly identical descriptions -- **Redundant Requirements Coverage**: Same requirement covered by multiple tasks without clear partitioning +#### Dimension G: Duplication Detection (LOW - Tier 4) +- Overlapping Task Scope: Multiple tasks with nearly identical descriptions +- Redundant Requirements Coverage: Same requirement covered by multiple tasks -#### H. Feasibility Assessment +#### Dimension H: Feasibility Assessment (LOW - Tier 4) +- Complexity Misalignment: Task marked "simple" but requires multiple file modifications +- Resource Conflicts: Parallel tasks requiring same resources/files +- Skill Gap Risks: Tasks requiring unavailable team skills -- **Complexity Misalignment**: Task marked "simple" but requires multiple file modifications -- **Resource Conflicts**: Parallel tasks requiring same resources/files -- **Skill Gap Risks**: Tasks requiring skills not in team capability assessment (from synthesis) +### CLI Analysis Execution -### 5. Severity Assignment +**Execute Tier 1 Analysis (All Dimensions)**: -Use this heuristic to prioritize findings: +\`\`\`bash +ccw cli -p "PURPOSE: Multi-dimensional plan verification for Tier 1 (user intent, coverage, consistency) +TASK: +• Verify user original intent matches IMPL_PLAN objectives (dimension A) +• Check all synthesis requirements have corresponding tasks (dimension B) +• Identify conflicts between tasks and synthesis decisions (dimension C) +• Find orphaned requirements or unmapped tasks +CONTEXT: @${session_dir}/**/* | Memory: Verification session WFS-${session_id} +EXPECTED: Findings JSON array with: dimension, severity, location, summary, recommendation +CONSTRAINTS: Focus on CRITICAL issues only | Identify all intent misalignments +" --tool gemini --mode analysis --rule analysis-review-architecture +\`\`\` -- **CRITICAL**: - - Violates user's original intent (goal misalignment, scope drift) - - Violates synthesis authority (requirement conflict) - - Core requirement with zero coverage - - Circular dependencies - - Broken dependencies +**If CRITICAL findings == 0, continue to Tier 2**: -- **HIGH**: - - NFR coverage gaps - - Priority conflicts - - Missing risk mitigation tasks - - Ambiguous acceptance criteria +\`\`\`bash +ccw cli -p "PURPOSE: Plan verification for Tier 2 (dependencies and synthesis alignment) +TASK: +• Detect circular or broken task dependencies (dimension D) +• Identify priority conflicts between synthesis and tasks (dimension E) +• Check risk mitigation coverage +CONTEXT: @${session_dir}/**/* | Previous: Tier 1 verified, no critical issues +EXPECTED: Findings JSON with dimension D-E results +CONSTRAINTS: Limit to 15 HIGH severity findings +" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause +\`\`\` -- **MEDIUM**: - - Terminology drift - - Missing artifacts references - - Weak flow control - - Logical ordering issues +**If High findings <= 15, continue to Tier 3**: -- **LOW**: - - Style/wording improvements - - Minor redundancy not affecting execution +\`\`\`bash +ccw cli -p "PURPOSE: Plan verification for Tier 3 (task specification quality) +TASK: +• Check for missing or vague acceptance criteria (dimension F) +• Validate flow control specifications in tasks +• Identify missing artifact references +CONTEXT: @${task_dir}/**/* @${IMPL_PLAN} +EXPECTED: Findings JSON with dimension F results +CONSTRAINTS: Limit to 20 MEDIUM severity findings +" --tool gemini --mode analysis --rule analysis-analyze-code-patterns +\`\`\` -### 6. Produce Compact Analysis Report +**If Medium findings <= 20, execute Tier 4**: -**Report Generation**: Generate report content and save to file. +\`\`\`bash +ccw cli -p "PURPOSE: Plan verification for Tier 4 (duplication and feasibility) +TASK: +• Detect overlapping task scopes (dimension G) +• Assess complexity alignment and resource conflicts (dimension H) +CONTEXT: @${task_dir}/**/* +EXPECTED: Findings JSON with dimension G-H results +CONSTRAINTS: Limit to 15 LOW severity findings +" --tool gemini --mode analysis --rule analysis-analyze-code-patterns +\`\`\` + +### Severity Assignment + +**CRITICAL**: +- Violates user's original intent (goal misalignment, scope drift) +- Violates synthesis authority (requirement conflict) +- Core requirement with zero coverage +- Circular dependencies +- Broken dependencies + +**HIGH**: +- NFR coverage gaps +- Priority conflicts +- Missing risk mitigation tasks +- Ambiguous acceptance criteria + +**MEDIUM**: +- Terminology drift +- Missing artifacts references +- Weak flow control +- Logical ordering issues + +**LOW**: +- Style/wording improvements +- Minor redundancy not affecting execution + +### Output Schema + +JSON findings array (reference from step 5 above): + +\`\`\`json +{ + "session_id": "${session_id}", + "timestamp": "2025-01-27T...", + "verification_tiers_completed": ["Tier 1", "Tier 2"], + "findings": [ + { + "id": "C1", + "dimension": "A", + "dimension_name": "User Intent Alignment", + "severity": "CRITICAL", + "location": ["${IMPL_PLAN}:L45", "synthesis:FR-03"], + "summary": "User goal: add user profiles, but IMPL_PLAN focuses on authentication", + "recommendation": "Update IMPL_PLAN to include profile management tasks" + }, + { + "id": "H1", + "dimension": "D", + "dimension_name": "Dependency Integrity", + "severity": "HIGH", + "location": ["task:IMPL-2.3"], + "summary": "Depends on non-existent IMPL-2.4", + "recommendation": "Fix depends_on reference or remove dependency" + } + ], + "summary": { + "critical_count": 2, + "high_count": 3, + "medium_count": 5, + "low_count": 8, + "total_findings": 18, + "coverage_percentage": 92, + "recommendation": "PROCEED_WITH_FIXES" + } +} +\`\`\` + +### Success Criteria + +- [ ] All Tier 1 findings identified (no early exit) +- [ ] Tier 2-4 executed in sequence (skipped only by token budget exhaustion) +- [ ] Each finding includes: dimension, severity, location, recommendation +- [ ] Findings aggregated in single JSON output file +- [ ] Agent returns completion summary with quality gate recommendation + +### Return Output + +Write: \`${process_dir}/verification-findings.json\` + +Return: 2-3 sentence summary with quality gate decision (BLOCK_EXECUTION / PROCEED_WITH_FIXES / PROCEED_WITH_CAUTION / PROCEED) +` +) +``` + +--- + +#### Phase 4.2: Parse and Aggregate Agent Results + +```javascript +// Load agent findings +const findings = JSON.parse(Read(\`${process_dir}/verification-findings.json\`)) + +// Organize by severity +const byServerity = { + CRITICAL: findings.findings.filter(f => f.severity === 'CRITICAL'), + HIGH: findings.findings.filter(f => f.severity === 'HIGH'), + MEDIUM: findings.findings.filter(f => f.severity === 'MEDIUM'), + LOW: findings.findings.filter(f => f.severity === 'LOW') +} + +// Determine quality gate +const recommendation = + byServerity.CRITICAL.length > 0 ? 'BLOCK_EXECUTION' : + byServerity.HIGH.length > 0 ? 'PROCEED_WITH_FIXES' : + byServerity.MEDIUM.length > 0 ? 'PROCEED_WITH_CAUTION' : + 'PROCEED' +``` + +### 5. Generate Human-Readable Report + +**Report Generation**: Transform agent findings JSON into comprehensive Markdown report. + +**Step 5.1: Load Agent Findings** +```javascript +// Load verification findings from agent +const findingsData = JSON.parse(Read(`${process_dir}/verification-findings.json`)) + +// Extract key metrics +const { session_id, timestamp, verification_tiers_completed, findings, summary } = findingsData +const { critical_count, high_count, medium_count, low_count, total_findings, coverage_percentage, recommendation } = summary + +// Organize findings by severity +const bySeverity = { + CRITICAL: findings.filter(f => f.severity === 'CRITICAL'), + HIGH: findings.filter(f => f.severity === 'HIGH'), + MEDIUM: findings.filter(f => f.severity === 'MEDIUM'), + LOW: findings.filter(f => f.severity === 'LOW') +} + +// Organize findings by dimension +const byDimension = findings.reduce((acc, f) => { + acc[f.dimension] = acc[f.dimension] || [] + acc[f.dimension].push(f) + return acc +}, {}) +``` + +**Step 5.2: Generate Markdown Report** Output a Markdown report with the following structure: ```markdown # Plan Verification Report -**Session**: WFS-{session-id} -**Generated**: {timestamp} -**Artifacts Analyzed**: role analysis documents, IMPL_PLAN.md, {N} task files -**User Intent Analysis**: {user_intent_analysis or "SKIPPED: workflow-session.json not found"} +**Session**: WFS-${session_id} +**Generated**: ${timestamp} +**Verification Tiers Completed**: ${verification_tiers_completed.join(', ')} +**Artifacts Analyzed**: role analysis documents, IMPL_PLAN.md, ${task_files_count} task files --- @@ -267,18 +452,27 @@ Output a Markdown report with the following structure: | Metric | Value | Status | |--------|-------|--------| -| Overall Risk Level | CRITICAL \| HIGH \| MEDIUM \| LOW | {status_emoji} | -| Critical Issues | {count} | 🔴 | -| High Issues | {count} | 🟠 | -| Medium Issues | {count} | 🟡 | -| Low Issues | {count} | 🟢 | +| Overall Risk Level | ${critical_count > 0 ? 'CRITICAL' : high_count > 0 ? 'HIGH' : medium_count > 0 ? 'MEDIUM' : 'LOW'} | ${critical_count > 0 ? '🔴' : high_count > 0 ? '🟠' : medium_count > 0 ? '🟡' : '🟢'} | +| Critical Issues | ${critical_count} | 🔴 | +| High Issues | ${high_count} | 🟠 | +| Medium Issues | ${medium_count} | 🟡 | +| Low Issues | ${low_count} | 🟢 | +| Requirements Coverage | ${coverage_percentage}% | ${coverage_percentage >= 90 ? '🟢' : coverage_percentage >= 75 ? '🟡' : '🔴'} | ### Recommendation -**{RECOMMENDATION}** +**${recommendation}** **Decision Rationale**: -{brief explanation based on severity criteria} +${ + recommendation === 'BLOCK_EXECUTION' ? + `Critical issues detected that violate core requirements or user intent. Must be resolved before implementation.` : + recommendation === 'PROCEED_WITH_FIXES' ? + `No critical issues, but high-severity concerns exist. Recommended to fix before execution to ensure quality.` : + recommendation === 'PROCEED_WITH_CAUTION' ? + `Medium-severity issues detected. May proceed but address concerns during/after implementation.` : + `No significant issues detected. Safe to proceed with implementation.` +} **Quality Gate Criteria**: - **BLOCK_EXECUTION**: Critical issues > 0 (must fix before proceeding) @@ -290,146 +484,217 @@ Output a Markdown report with the following structure: ## Findings Summary -| ID | Category | Severity | Location(s) | Summary | Recommendation | -|----|----------|----------|-------------|---------|----------------| -| C1 | Coverage | CRITICAL | synthesis:FR-03 | Requirement "User auth" has zero task coverage | Add authentication implementation task | -| H1 | Consistency | HIGH | IMPL-1.2 vs synthesis:ADR-02 | Task uses REST while synthesis specifies GraphQL | Align task with ADR-02 decision | -| M1 | Specification | MEDIUM | IMPL-2.1 | Missing context.artifacts reference | Add @synthesis reference | -| L1 | Duplication | LOW | IMPL-3.1, IMPL-3.2 | Similar scope | Consider merging | +| ID | Dimension | Severity | Location(s) | Summary | Recommendation | +|----|-----------|----------|-------------|---------|----------------| +${findings.map(f => `| ${f.id} | ${f.dimension_name} | ${f.severity} | ${f.location.join(', ')} | ${f.summary} | ${f.recommendation} |`).join('\n')} -(Generate stable IDs prefixed by severity initial: C/H/M/L + number) +(IDs prefixed by severity initial: C/H/M/L + number) --- -## User Intent Alignment Analysis +## User Intent Alignment Analysis (Dimension A) -{IF user_intent_analysis != "SKIPPED"} +${ + byDimension['A'] && byDimension['A'].length > 0 ? + byDimension['A'].map(f => ` +### ${f.summary} -### Goal Alignment -- **User Intent**: {user_original_intent} -- **IMPL_PLAN Objectives**: {plan_objectives} -- **Alignment Status**: {ALIGNED/MISALIGNED/PARTIAL} -- **Findings**: {specific alignment issues} +**Severity**: ${f.severity} +**Location**: ${f.location.join(', ')} -### Scope Verification -- **User Scope**: {user_defined_scope} -- **Plan Scope**: {plan_actual_scope} -- **Drift Detection**: {NONE/MINOR/MAJOR} -- **Findings**: {specific scope issues} +**Issue Description**: +${f.summary} -{ELSE} -> ⚠️ User intent alignment analysis was skipped because workflow-session.json was not found. - -{END IF} +**Recommendation**: +${f.recommendation} +`).join('\n') : + `> ✅ No user intent alignment issues detected. IMPL_PLAN objectives and scope match user's original intent.` +} --- -## Requirements Coverage Analysis - -### Functional Requirements - -| Requirement ID | Requirement Summary | Has Task? | Task IDs | Priority Match | Notes | -|----------------|---------------------|-----------|----------|----------------|-------| -| FR-01 | User authentication | Yes | IMPL-1.1, IMPL-1.2 | Match | Complete | -| FR-02 | Data export | Yes | IMPL-2.3 | Mismatch | High req → Med priority task | -| FR-03 | Profile management | No | - | - | **CRITICAL: Zero coverage** | - -### Non-Functional Requirements - -| Requirement ID | Requirement Summary | Has Task? | Task IDs | Notes | -|----------------|---------------------|-----------|----------|-------| -| NFR-01 | Response time <200ms | No | - | **HIGH: No performance tasks** | -| NFR-02 | Security compliance | Yes | IMPL-4.1 | Complete | - -### Business Requirements - -| Requirement ID | Requirement Summary | Has Task? | Task IDs | Notes | -|----------------|---------------------|-----------|----------|-------| -| BR-01 | Launch by Q2 | Yes | IMPL-1.* through IMPL-5.* | Timeline realistic | +## Requirements Coverage Analysis (Dimension B) ### Coverage Metrics -| Requirement Type | Total | Covered | Coverage % | -|------------------|-------|---------|------------| -| Functional | {count} | {count} | {percent}% | -| Non-Functional | {count} | {count} | {percent}% | -| Business | {count} | {count} | {percent}% | -| **Overall** | **{total}** | **{covered}** | **{percent}%** | +| Metric | Value | +|--------|-------| +| Overall Coverage | ${coverage_percentage}% | +| Total Findings | ${byDimension['B']?.length || 0} | + +### Findings + +${ + byDimension['B'] && byDimension['B'].length > 0 ? + byDimension['B'].map(f => ` +#### ${f.id}: ${f.summary} + +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ All synthesis requirements have corresponding tasks. No coverage gaps detected.` +} --- -## Dependency Integrity +## Consistency Validation (Dimension C) -### Dependency Graph Analysis +${ + byDimension['C'] && byDimension['C'].length > 0 ? + byDimension['C'].map(f => ` +### ${f.id}: ${f.summary} -**Circular Dependencies**: {None or List} - -**Broken Dependencies**: -- IMPL-2.3 depends on "IMPL-2.4" (non-existent) - -**Missing Dependencies**: -- IMPL-5.1 (integration test) has no dependency on IMPL-1.* (implementation tasks) - -**Logical Ordering Issues**: -{List or "None detected"} +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No consistency issues detected. Tasks align with synthesis requirements and architecture.` +} --- -## Synthesis Alignment Issues +## Dependency Integrity (Dimension D) -| Issue Type | Synthesis Reference | IMPL_PLAN/Task | Impact | Recommendation | -|------------|---------------------|----------------|--------|----------------| -| Architecture Conflict | synthesis:ADR-01 (JWT auth) | IMPL_PLAN uses session cookies | HIGH | Update IMPL_PLAN to use JWT | -| Priority Mismatch | synthesis:FR-02 (High) | IMPL-2.3 (Medium) | MEDIUM | Elevate task priority | -| Missing Risk Mitigation | synthesis:Risk-03 (API rate limits) | No mitigation tasks | HIGH | Add rate limiting implementation task | +${ + byDimension['D'] && byDimension['D'].length > 0 ? + byDimension['D'].map(f => ` +### ${f.id}: ${f.summary} + +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No dependency issues detected. All task dependencies are valid and logically ordered.` +} --- -## Task Specification Quality +## Synthesis Alignment (Dimension E) -### Aggregate Statistics +${ + byDimension['E'] && byDimension['E'].length > 0 ? + byDimension['E'].map(f => ` +### ${f.id}: ${f.summary} -| Quality Dimension | Tasks Affected | Percentage | -|-------------------|----------------|------------| -| Missing Artifacts References | {count} | {percent}% | -| Weak Flow Control | {count} | {percent}% | -| Missing Target Files | {count} | {percent}% | -| Ambiguous Focus Paths | {count} | {percent}% | - -### Sample Issues - -- **IMPL-1.2**: No context.artifacts reference to synthesis -- **IMPL-3.1**: Missing flow_control.target_files specification -- **IMPL-4.2**: Vague focus_paths ["src/"] - needs refinement +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No synthesis alignment issues. Task priorities and success criteria match synthesis specifications.` +} --- -## Feasibility Concerns +## Task Specification Quality (Dimension F) -| Concern | Tasks Affected | Issue | Recommendation | -|---------|----------------|-------|----------------| -| Skill Gap | IMPL-6.1, IMPL-6.2 | Requires Kubernetes expertise not in team | Add training task or external consultant | -| Resource Conflict | IMPL-3.1, IMPL-3.2 | Both modify src/auth/service.ts in parallel | Add dependency or serialize | +${ + byDimension['F'] && byDimension['F'].length > 0 ? + byDimension['F'].map(f => ` +### ${f.id}: ${f.summary} + +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ All tasks have clear specifications with proper focus_paths, acceptance criteria, and flow control.` +} + +--- + +## Duplication Detection (Dimension G) + +${ + byDimension['G'] && byDimension['G'].length > 0 ? + byDimension['G'].map(f => ` +### ${f.id}: ${f.summary} + +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No duplicate task scopes detected. All tasks have distinct responsibilities.` +} + +--- + +## Feasibility Assessment (Dimension H) + +${ + byDimension['H'] && byDimension['H'].length > 0 ? + byDimension['H'].map(f => ` +### ${f.id}: ${f.summary} + +- **Severity**: ${f.severity} +- **Location**: ${f.location.join(', ')} +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No feasibility concerns. Task complexity assessments and resource allocations are appropriate.` +} --- ## Detailed Findings by Severity -### CRITICAL Issues ({count}) +### CRITICAL Issues (${critical_count}) -{Detailed breakdown of each critical issue with location, impact, and recommendation} +${ + bySeverity.CRITICAL.length > 0 ? + bySeverity.CRITICAL.map(f => ` +#### ${f.id}: ${f.summary} -### HIGH Issues ({count}) +- **Dimension**: ${f.dimension_name} (${f.dimension}) +- **Location**: ${f.location.join(', ')} +- **Impact**: Blocks execution - must be resolved before implementation +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No critical issues detected.` +} -{Detailed breakdown of each high issue with location, impact, and recommendation} +### HIGH Issues (${high_count}) -### MEDIUM Issues ({count}) +${ + bySeverity.HIGH.length > 0 ? + bySeverity.HIGH.map(f => ` +#### ${f.id}: ${f.summary} -{Detailed breakdown of each medium issue with location, impact, and recommendation} +- **Dimension**: ${f.dimension_name} (${f.dimension}) +- **Location**: ${f.location.join(', ')} +- **Impact**: Significant quality concern - recommended to fix before execution +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No high-severity issues detected.` +} -### LOW Issues ({count}) +### MEDIUM Issues (${medium_count}) -{Detailed breakdown of each low issue with location, impact, and recommendation} +${ + bySeverity.MEDIUM.length > 0 ? + bySeverity.MEDIUM.map(f => ` +#### ${f.id}: ${f.summary} + +- **Dimension**: ${f.dimension_name} (${f.dimension}) +- **Location**: ${f.location.join(', ')} +- **Impact**: Quality improvement opportunity - address during/after implementation +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No medium-severity issues detected.` +} + +### LOW Issues (${low_count}) + +${ + bySeverity.LOW.length > 0 ? + bySeverity.LOW.map(f => ` +#### ${f.id}: ${f.summary} + +- **Dimension**: ${f.dimension_name} (${f.dimension}) +- **Location**: ${f.location.join(', ')} +- **Impact**: Minor improvement - optional +- **Recommendation**: ${f.recommendation} +`).join('\n') : + `> ✅ No low-severity issues detected.` +} --- @@ -437,14 +702,13 @@ Output a Markdown report with the following structure: | Metric | Value | |--------|-------| -| Total Requirements | {count} ({functional} functional, {nonfunctional} non-functional, {business} business) | -| Total Tasks | {count} | -| Overall Coverage | {percent}% ({covered}/{total} requirements with ≥1 task) | -| Critical Issues | {count} | -| High Issues | {count} | -| Medium Issues | {count} | -| Low Issues | {count} | -| Total Findings | {total_findings} | +| Requirements Coverage | ${coverage_percentage}% | +| Total Findings | ${total_findings} | +| Critical Issues | ${critical_count} | +| High Issues | ${high_count} | +| Medium Issues | ${medium_count} | +| Low Issues | ${low_count} | +| Verification Tiers Completed | ${verification_tiers_completed.join(', ')} | --- @@ -459,69 +723,103 @@ Output a Markdown report with the following structure: ### Next Steps -Based on the quality gate recommendation ({RECOMMENDATION}): +Based on the quality gate recommendation (**${recommendation}**): -{IF BLOCK_EXECUTION} +${ + recommendation === 'BLOCK_EXECUTION' ? + ` **🛑 BLOCK EXECUTION** You must resolve all CRITICAL issues before proceeding with implementation: -1. Review each critical issue in detail -2. Determine remediation approach (modify IMPL_PLAN.md, update task.json, or add new tasks) +1. Review each critical issue in detail (see section "CRITICAL Issues" above) +2. Determine remediation approach: + - Modify IMPL_PLAN.md for goal/scope conflicts + - Update task.json for requirement misalignments + - Add new tasks for coverage gaps + - Fix dependencies for circular/broken references 3. Apply fixes systematically -4. Re-run verification to confirm resolution - -{ELSE IF PROCEED_WITH_FIXES} +4. Re-run verification to confirm resolution: \`/workflow:plan-verify --session ${session_id}\` +` : + recommendation === 'PROCEED_WITH_FIXES' ? + ` **⚠️ PROCEED WITH FIXES RECOMMENDED** No critical issues detected, but HIGH issues exist. Recommended workflow: -1. Review high-priority issues -2. Apply fixes before execution for optimal results -3. Re-run verification (optional) - -{ELSE IF PROCEED_WITH_CAUTION} +1. Review high-priority issues (see section "HIGH Issues" above) +2. Apply fixes before execution for optimal results: + - Use IMPL_PLAN.md for architecture/priority misalignments + - Update task.json for specification improvements + - Add missing dependencies or risk mitigation tasks +3. Re-run verification to confirm resolution: \`/workflow:plan-verify --session ${session_id}\` +4. Proceed to implementation when ready +` : + recommendation === 'PROCEED_WITH_CAUTION' ? + ` **✅ PROCEED WITH CAUTION** Only MEDIUM issues detected. You may proceed with implementation: -- Address medium issues during or after implementation +- Review medium-severity issues (see section "MEDIUM Issues" above) +- Address concerns during or after implementation - Maintain awareness of identified concerns - -{ELSE} +- Schedule remediation for future improvement cycles +` : + ` **✅ PROCEED** -No significant issues detected. Safe to execute implementation workflow. +No significant issues detected. Safe to execute implementation workflow: -{END IF} +- Requirements fully covered +- User intent aligned +- Dependencies valid and logically ordered +- All tasks properly specified +- Ready for immediate execution +` +} --- **Report End** +\`\`\` + +### 6. Save and Display Report + +**Step 6.1: Generate Complete Markdown Report** + +```javascript +// Build complete report from template above using findings data +const fullReport = \` +# Plan Verification Report +... [complete markdown template generated above] ... +\` + +// Write report to file +const reportPath = \`${process_dir}/PLAN_VERIFICATION.md\` +Write(reportPath, fullReport) ``` -### 7. Save and Display Report +**Step 6.2: Display Summary to User** -**Step 7.1: Save Report**: -```bash -report_path = ".workflow/active/WFS-{session}/.process/PLAN_VERIFICATION.md" -Write(report_path, full_report_content) +```javascript +console.log(\` +=== Plan Verification Complete === +Report saved to: ${reportPath} + +Quality Gate: \${recommendation} +Critical: \${critical_count} | High: \${high_count} | Medium: \${medium_count} | Low: \${low_count} +Coverage: \${coverage_percentage}% + +Next: Review full report at ${reportPath} for detailed findings and recommendations +\`) ``` -**Step 7.2: Display Summary to User**: -```bash -# Display executive summary in terminal -echo "=== Plan Verification Complete ===" -echo "Report saved to: {report_path}" -echo "" -echo "Quality Gate: {RECOMMENDATION}" -echo "Critical: {count} | High: {count} | Medium: {count} | Low: {count}" -echo "" -echo "Next: Review full report for detailed findings and recommendations" -``` +**Step 6.3: Completion** -**Step 7.3: Completion**: -- Report is saved to `.process/PLAN_VERIFICATION.md` -- User can review findings and decide on remediation approach -- No automatic modifications are made to source artifacts -- User can manually apply fixes or use separate remediation command (if available) +- ✅ Agent JSON findings saved to: \`${process_dir}/verification-findings.json\` +- ✅ Human-readable report saved to: \`${process_dir}/PLAN_VERIFICATION.md\` +- ✅ Quality gate decision: \`${recommendation}\` +- ℹ️ No automatic modifications to IMPL_PLAN.md, tasks, or synthesis artifacts +- ℹ️ User can review findings and decide on remediation approach +- ℹ️ Re-run verification after fixes: \`/workflow:plan-verify --session ${session_id}\` diff --git a/.claude/commands/workflow/plan.md b/.claude/commands/workflow/plan.md index f507eba6..b24c8e37 100644 --- a/.claude/commands/workflow/plan.md +++ b/.claude/commands/workflow/plan.md @@ -169,6 +169,7 @@ SlashCommand(command="/workflow:tools:context-gather --session [sessionId] \"[st **Validation**: - Context package path extracted - File exists and is valid JSON +- `prioritized_context` field exists @@ -419,20 +420,55 @@ SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]" **Note**: Agent task completed. No collapse needed (single task). -**Return to User**: -``` -Planning complete for session: [sessionId] -Tasks generated: [count] -Plan: .workflow/active/[sessionId]/IMPL_PLAN.md +**Step 4.2: User Decision** - Choose next action -Recommended Next Steps: -1. /workflow:plan-verify --session [sessionId] # Verify plan quality before execution -2. /workflow:status # Review task breakdown -3. /workflow:execute # Start implementation (after verification) +After Phase 4 completes, present user with action choices: -Quality Gate: Consider running /workflow:plan-verify to catch issues early +```javascript +console.log(` +✅ Planning complete for session: ${sessionId} +📊 Tasks generated: ${taskCount} +📋 Plan: .workflow/active/${sessionId}/IMPL_PLAN.md +`); + +// Ask user for next action +const userChoice = AskUserQuestion({ + questions: [{ + question: "Planning complete. What would you like to do next?", + header: "Next Action", + multiSelect: false, + options: [ + { + label: "Verify Plan Quality (Recommended)", + description: "Run quality verification to catch issues before execution. Checks plan structure, task dependencies, and completeness." + }, + { + label: "Start Execution", + description: "Begin implementing tasks immediately. Use this if you've already reviewed the plan or want to start quickly." + }, + { + label: "Review Status Only", + description: "View task breakdown and session status without taking further action. You can decide what to do next manually." + } + ] + }] +}); + +// Execute based on user choice +if (userChoice.answers["Next Action"] === "Verify Plan Quality (Recommended)") { + console.log("\n🔍 Starting plan verification...\n"); + SlashCommand(command="/workflow:plan-verify --session " + sessionId); +} else if (userChoice.answers["Next Action"] === "Start Execution") { + console.log("\n🚀 Starting task execution...\n"); + SlashCommand(command="/workflow:execute --session " + sessionId); +} else if (userChoice.answers["Next Action"] === "Review Status Only") { + console.log("\n📊 Displaying session status...\n"); + SlashCommand(command="/workflow:status --session " + sessionId); +} ``` +**Return to User**: Based on user's choice, execute the corresponding workflow command. + ## TodoWrite Pattern **Core Concept**: Dynamic task attachment and collapse for real-time visibility into workflow execution. @@ -511,8 +547,11 @@ Phase 1: session:start --auto "structured-description" ↓ Write: planning-notes.md (User Intent section) ↓ Phase 2: context-gather --session sessionId "structured-description" - ↓ Input: sessionId + structured description - ↓ Output: contextPath (context-package.json) + conflict_risk + ↓ Input: sessionId + structured description + planning-notes.md (Phase 1 user intent) + ↓ CONTEXT PRIORITY SORTING IN CONTEXT-GATHER (Phase 2 Track -1 + Phase 3) + ↓ Output: contextPath (context-package.json with prioritized_context) + conflict_risk + ↓ - prioritized_context contains: user_intent, priority_tiers, dependency_order + ↓ - Eliminates redundant sorting in task-generate-agent Phase 1 ↓ Update: planning-notes.md (Context Findings + Consolidated Constraints) ↓ Phase 3: conflict-resolution [AUTO-TRIGGERED if conflict_risk ≥ medium] @@ -522,8 +561,10 @@ Phase 3: conflict-resolution [AUTO-TRIGGERED if conflict_risk ≥ medium] ↓ Skip if conflict_risk is none/low → proceed directly to Phase 4 ↓ Phase 4: task-generate-agent --session sessionId - ↓ Input: sessionId + planning-notes.md + context-package.json + brainstorm artifacts - ↓ planning-notes.md provides: User Intent, Context Findings, Constraints + ↓ Input: sessionId + planning-notes.md + context-package.json (with prioritized_context) + brainstorm artifacts + ↓ USE PRIORITIZED_CONTEXT DIRECTLY - NO REDUNDANT SORTING + ↓ - planning-notes.md provides: User Intent, Context Findings, Constraints + ↓ - context-package.prioritized_context provides: Pre-sorted priority_tiers, dependency_order ↓ Output: IMPL_PLAN.md, task JSONs, TODO_LIST.md ↓ Return summary to user diff --git a/.claude/commands/workflow/tools/conflict-resolution.md b/.claude/commands/workflow/tools/conflict-resolution.md index ffe73aed..10687f2a 100644 --- a/.claude/commands/workflow/tools/conflict-resolution.md +++ b/.claude/commands/workflow/tools/conflict-resolution.md @@ -186,6 +186,17 @@ Task(subagent_type="cli-execution-agent", run_in_background=false, prompt=` - modifications.old_content: 20-100 chars for unique Edit tool matching - modifications.new_content: preserves markdown formatting - modification_suggestions: 2-5 actionable suggestions for custom handling + + ### 5. Planning Notes Record (REQUIRED) + After analysis complete, append a brief execution record to planning-notes.md: + + **File**: .workflow/active/{session_id}/planning-notes.md + **Location**: Under "## Conflict Decisions (Phase 3)" section + **Format**: + \`\`\` + ### [Conflict-Resolution Agent] YYYY-MM-DD + - **Note**: [智能补充:简短总结冲突类型、解决策略、关键决策等] + \`\`\` `) ``` diff --git a/.claude/commands/workflow/tools/context-gather.md b/.claude/commands/workflow/tools/context-gather.md index 2db25e4a..e257befd 100644 --- a/.claude/commands/workflow/tools/context-gather.md +++ b/.claude/commands/workflow/tools/context-gather.md @@ -35,7 +35,7 @@ Step 1: Context-Package Detection ├─ Valid package exists → Return existing (skip execution) └─ No valid package → Continue to Step 2 -Step 2: Complexity Assessment & Parallel Explore (NEW) +Step 2: Complexity Assessment & Parallel Explore ├─ Analyze task_description → classify Low/Medium/High ├─ Select exploration angles (1-4 based on complexity) ├─ Launch N cli-explore-agents in parallel @@ -213,19 +213,37 @@ Write(`${sessionFolder}/explorations-manifest.json`, JSON.stringify(explorationM **Only execute after Step 2 completes** ```javascript +// Load user intent from planning-notes.md (from Phase 1) +const planningNotesPath = `.workflow/active/${session_id}/planning-notes.md`; +let userIntent = { goal: task_description, key_constraints: "None specified" }; + +if (file_exists(planningNotesPath)) { + const notesContent = Read(planningNotesPath); + const goalMatch = notesContent.match(/\*\*GOAL\*\*:\s*(.+)/); + const constraintsMatch = notesContent.match(/\*\*KEY_CONSTRAINTS\*\*:\s*(.+)/); + if (goalMatch) userIntent.goal = goalMatch[1].trim(); + if (constraintsMatch) userIntent.key_constraints = constraintsMatch[1].trim(); +} + Task( subagent_type="context-search-agent", run_in_background=false, description="Gather comprehensive context for plan", prompt=` ## Execution Mode -**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution +**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution with priority sorting ## Session Information - **Session ID**: ${session_id} - **Task Description**: ${task_description} - **Output Path**: .workflow/${session_id}/.process/context-package.json +## User Intent (from Phase 1 - Planning Notes) +**GOAL**: ${userIntent.goal} +**KEY_CONSTRAINTS**: ${userIntent.key_constraints} + +This is the PRIMARY context source - all subsequent analysis must align with user intent. + ## Exploration Input (from Step 2) - **Manifest**: ${sessionFolder}/explorations-manifest.json - **Exploration Count**: ${explorationManifest.exploration_count} @@ -245,7 +263,13 @@ Execute complete context-search-agent workflow for implementation planning: 4. **Analysis**: Extract keywords, determine scope, classify complexity based on task description and project state ### Phase 2: Multi-Source Context Discovery -Execute all discovery tracks: +Execute all discovery tracks (WITH USER INTENT INTEGRATION): +- **Track -1**: User Intent & Priority Foundation (EXECUTE FIRST) + - Load user intent (GOAL, KEY_CONSTRAINTS) from session input + - Map user requirements to codebase entities (files, modules, patterns) + - Establish baseline priority scores based on user goal alignment + - Output: user_intent_mapping.json with preliminary priority scores + - **Track 0**: Exploration Synthesis (load ${sessionFolder}/explorations-manifest.json, prioritize critical_files, deduplicate patterns/integration_points) - **Track 1**: Historical archive analysis (query manifest.json for lessons learned) - **Track 2**: Reference documentation (CLAUDE.md, architecture docs) @@ -254,13 +278,45 @@ Execute all discovery tracks: ### Phase 3: Synthesis, Assessment & Packaging 1. Apply relevance scoring and build dependency graph -2. **Synthesize 4-source data**: Merge findings from all sources (archive > docs > code > web). **Prioritize the context from `project-tech.json`** for architecture and tech stack unless code analysis reveals it's outdated. -3. **Populate `project_context`**: Directly use the `overview` from `project-tech.json` to fill the `project_context` section. Include description, technology_stack, architecture, and key_components. -4. **Populate `project_guidelines`**: Load conventions, constraints, and learnings from `project-guidelines.json` into a dedicated section. -5. Integrate brainstorm artifacts (if .brainstorming/ exists, read content) -6. Perform conflict detection with risk assessment -7. **Inject historical conflicts** from archive analysis into conflict_detection -8. Generate and validate context-package.json +2. **Synthesize 5-source data** (including Track -1): Merge findings from all sources + - Priority order: User Intent > Archive > Docs > Exploration > Code > Web + - **Prioritize the context from `project-tech.json`** for architecture and tech stack unless code analysis reveals it's outdated +3. **Context Priority Sorting**: + a. Combine scores from Track -1 (user intent alignment) + relevance scores + exploration critical_files + b. Classify files into priority tiers: + - **Critical** (score ≥ 0.85): Directly mentioned in user goal OR exploration critical_files + - **High** (0.70-0.84): Key dependencies, patterns required for goal + - **Medium** (0.50-0.69): Supporting files, indirect dependencies + - **Low** (< 0.50): Contextual awareness only + c. Generate dependency_order: Based on dependency graph + user goal sequence + d. Document sorting_rationale: Explain prioritization logic + +4. **Populate `project_context`**: Directly use the `overview` from `project-tech.json` to fill the `project_context` section. Include description, technology_stack, architecture, and key_components. +5. **Populate `project_guidelines`**: Load conventions, constraints, and learnings from `project-guidelines.json` into a dedicated section. +6. Integrate brainstorm artifacts (if .brainstorming/ exists, read content) +7. Perform conflict detection with risk assessment +8. **Inject historical conflicts** from archive analysis into conflict_detection +9. **Generate prioritized_context section**: + ```json + { + "prioritized_context": { + "user_intent": { + "goal": "...", + "scope": "...", + "key_constraints": ["..."] + }, + "priority_tiers": { + "critical": [{ "path": "...", "relevance": 0.95, "rationale": "..." }], + "high": [...], + "medium": [...], + "low": [...] + }, + "dependency_order": ["module1", "module2", "module3"], + "sorting_rationale": "Based on user goal alignment (Track -1), exploration critical files, and dependency graph analysis" + } + } + ``` +10. Generate and validate context-package.json with prioritized_context field ## Output Requirements Complete context-package.json with: @@ -272,6 +328,7 @@ Complete context-package.json with: - **brainstorm_artifacts**: {guidance_specification, role_analyses[], synthesis_output} with content - **conflict_detection**: {risk_level, risk_factors, affected_modules[], mitigation_strategy, historical_conflicts[]} - **exploration_results**: {manifest_path, exploration_count, angles, explorations[], aggregated_insights} (from Track 0) +- **prioritized_context**: {user_intent, priority_tiers{critical, high, medium, low}, dependency_order[], sorting_rationale} ## Quality Validation Before completion verify: @@ -282,6 +339,17 @@ Before completion verify: - [ ] No sensitive data exposed - [ ] Total files ≤50 (prioritize high-relevance) +## Planning Notes Record (REQUIRED) +After completing context-package.json, append a brief execution record to planning-notes.md: + +**File**: .workflow/active/${session_id}/planning-notes.md +**Location**: Under "## Context Findings (Phase 2)" section +**Format**: +\`\`\` +### [Context-Search Agent] YYYY-MM-DD +- **Note**: [智能补充:简短总结关键发现,如探索角度、关键文件、冲突风险等] +\`\`\` + Execute autonomously following agent documentation. Report completion with statistics. ` @@ -326,6 +394,7 @@ Refer to `context-search-agent.md` Phase 3.7 for complete `context-package.json` - **brainstorm_artifacts**: Brainstorm documents with full content (if exists) - **conflict_detection**: Risk assessment with mitigation strategies and historical conflicts - **exploration_results**: Aggregated exploration insights (from parallel explore phase) +- **prioritized_context**: Pre-sorted context with user intent and priority tiers (critical/high/medium/low) ## Historical Archive Analysis @@ -435,7 +504,10 @@ if (historicalConflicts.length > 0 && currentRisk === "low") { ## Notes - **Detection-first**: Always check for existing package before invoking agent +- **User intent integration**: Load user intent from planning-notes.md (Phase 1 output) to ensure context aligns with user goals +- **Priority sorting in Phase 2**: Track -1 (User Intent & Priority Foundation) establishes baseline priorities BEFORE other track analysis - **Dual project file integration**: Agent reads both `.workflow/project-tech.json` (tech analysis) and `.workflow/project-guidelines.json` (user constraints) as primary sources - **Guidelines injection**: Project guidelines are included in context-package to ensure task generation respects user-defined constraints -- **No redundancy**: This command is a thin orchestrator, all logic in agent +- **Prioritized context output**: `prioritized_context` field provides pre-sorted context with priority tiers +- **No redundancy**: Context sorting happens once (Phase 2 Track -1 + Phase 3), not duplicated in Phase 4 - **Plan-specific**: Use this for implementation planning; brainstorm mode uses direct agent call diff --git a/.claude/commands/workflow/tools/task-generate-agent.md b/.claude/commands/workflow/tools/task-generate-agent.md index 1d7c773c..11ff652f 100644 --- a/.claude/commands/workflow/tools/task-generate-agent.md +++ b/.claude/commands/workflow/tools/task-generate-agent.md @@ -19,6 +19,10 @@ Generate implementation planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST. ## Core Philosophy - **Planning Only**: Generate planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) - does NOT implement code - **Agent-Driven Document Generation**: Delegate plan generation to action-planning-agent +- **NO Redundant Context Sorting**: Context priority sorting is ALREADY completed in context-gather Phase 2/3 + - Use `context-package.json.prioritized_context` directly + - DO NOT re-sort files or re-compute priorities + - `priority_tiers` and `dependency_order` are pre-computed and ready-to-use - **N+1 Parallel Planning**: Auto-detect multi-module projects, enable parallel planning (2+1 or 3+1 mode) - **Progressive Loading**: Load context incrementally (Core → Selective → On-Demand) due to analysis.md file size - **Memory-First**: Reuse loaded documents from conversation memory @@ -161,13 +165,13 @@ const userConfig = { ### Phase 1: Context Preparation & Module Detection (Command Responsibility) -**Command prepares session paths, metadata, detects module structure, and loads planning-notes.md.** +**Command prepares session paths, metadata, detects module structure. Context priority sorting is NOT performed here - it's already completed in context-gather Phase 2/3.** **Session Path Structure**: ``` .workflow/active/WFS-{session-id}/ ├── workflow-session.json # Session metadata -├── planning-notes.md # Consolidated planning notes (NEW) +├── planning-notes.md # Consolidated planning notes ├── .process/ │ └── context-package.json # Context package with artifact catalog ├── .task/ # Output: Task JSON files @@ -263,7 +267,7 @@ This document contains: ## SESSION PATHS Input: - Session Metadata: .workflow/active/{session-id}/workflow-session.json - - Planning Notes: .workflow/active/{session-id}/planning-notes.md (NEW) + - Planning Notes: .workflow/active/{session-id}/planning-notes.md - Context Package: .workflow/active/{session-id}/.process/context-package.json Output: @@ -291,7 +295,17 @@ CLI Resume Support (MANDATORY for all CLI commands): - Read previous task's cliExecutionId from session state - Format: ccw cli -p "[prompt]" --resume ${previousCliId} --tool ${tool} --mode write -## EXPLORATION CONTEXT (from context-package.exploration_results) +## PRIORITIZED CONTEXT (from context-package.prioritized_context) - ALREADY SORTED +Context sorting is ALREADY COMPLETED in context-gather Phase 2/3. DO NOT re-sort. +Direct usage: +- **user_intent**: Use goal/scope/key_constraints for task alignment +- **priority_tiers.critical**: These files are PRIMARY focus for task generation +- **priority_tiers.high**: These files are SECONDARY focus +- **dependency_order**: Use this for task sequencing - already computed +- **sorting_rationale**: Reference for understanding priority decisions + +## EXPLORATION CONTEXT (from context-package.exploration_results) - SUPPLEMENT ONLY +If prioritized_context is incomplete, fall back to exploration_results: - Load exploration_results from context-package.json - Use aggregated_insights.critical_files for focus_paths generation - Apply aggregated_insights.constraints to acceptance criteria @@ -311,8 +325,10 @@ CLI Resume Support (MANDATORY for all CLI commands): - 6-field schema (id, title, status, context_package_path, meta, context, flow_control) - Quantified requirements with explicit counts - Artifacts integration from context package - - **focus_paths enhanced with exploration critical_files** - - Flow control with pre_analysis steps (include exploration integration_points analysis) + - **focus_paths generated directly from prioritized_context.priority_tiers (critical + high)** + - NO re-sorting or re-prioritization - use pre-computed tiers as-is + - Critical files are PRIMARY focus, High files are SECONDARY + - Flow control with pre_analysis steps (use prioritized_context.dependency_order for task sequencing) - **CLI Execution IDs and strategies (MANDATORY)** 2. Implementation Plan (IMPL_PLAN.md) @@ -360,6 +376,19 @@ Hard Constraints: - IMPL_PLAN.md created with complete structure - TODO_LIST.md generated matching task JSONs - Return completion status with document count and task breakdown summary + +## PLANNING NOTES RECORD (REQUIRED) +After completing all documents, append a brief execution record to planning-notes.md: + +**File**: .workflow/active/{session_id}/planning-notes.md +**Location**: Create new section after "## Consolidated Constraints" +**Format**: +\`\`\` +## Task Generation (Phase 4) + +### [Action-Planning Agent] YYYY-MM-DD +- **Note**: [智能补充:简短总结任务数量、关键任务、依赖关系等] +\`\`\` ` ) ``` @@ -404,7 +433,7 @@ This document contains consolidated constraints and user intent to guide module- ## SESSION PATHS Input: - Session Metadata: .workflow/active/{session-id}/workflow-session.json - - Planning Notes: .workflow/active/{session-id}/planning-notes.md (NEW) + - Planning Notes: .workflow/active/{session-id}/planning-notes.md - Context Package: .workflow/active/{session-id}/.process/context-package.json Output: @@ -430,7 +459,16 @@ CLI Resume Support (MANDATORY for all CLI commands): - Read previous task's cliExecutionId from session state - Format: ccw cli -p "[prompt]" --resume ${previousCliId} --tool ${tool} --mode write -## EXPLORATION CONTEXT (from context-package.exploration_results) +## PRIORITIZED CONTEXT (from context-package.prioritized_context) - ALREADY SORTED +Context sorting is ALREADY COMPLETED in context-gather Phase 2/3. DO NOT re-sort. +Filter by module scope (${module.paths.join(', ')}): +- **user_intent**: Use for task alignment within module +- **priority_tiers.critical**: Filter for files in ${module.paths.join(', ')} → PRIMARY focus +- **priority_tiers.high**: Filter for files in ${module.paths.join(', ')} → SECONDARY focus +- **dependency_order**: Use module-relevant entries for task sequencing + +## EXPLORATION CONTEXT (from context-package.exploration_results) - SUPPLEMENT ONLY +If prioritized_context is incomplete for this module, fall back to exploration_results: - Load exploration_results from context-package.json - Filter for ${module.name} module: Use aggregated_insights.critical_files matching ${module.paths.join(', ')} - Apply module-relevant constraints from aggregated_insights.constraints @@ -457,8 +495,10 @@ Task JSON Files (.task/IMPL-${module.prefix}*.json): - Task ID format: IMPL-${module.prefix}1, IMPL-${module.prefix}2, ... - Quantified requirements with explicit counts - Artifacts integration from context package (filtered for ${module.name}) - - **focus_paths enhanced with exploration critical_files (module-scoped)** - - Flow control with pre_analysis steps (include exploration integration_points analysis) + - **focus_paths generated directly from prioritized_context.priority_tiers filtered by ${module.paths.join(', ')}** + - NO re-sorting - use pre-computed tiers filtered for this module + - Critical files are PRIMARY focus, High files are SECONDARY + - Flow control with pre_analysis steps (use prioritized_context.dependency_order for module task sequencing) - **CLI Execution IDs and strategies (MANDATORY)** - Focus ONLY on ${module.name} module scope @@ -501,6 +541,21 @@ Hard Constraints: - Cross-module dependencies use CROSS:: placeholder format consistently - Focus paths scoped to ${module.paths.join(', ')} only - Return: task count, task IDs, dependency summary (internal + cross-module) + +## PLANNING NOTES RECORD (REQUIRED) +After completing module task JSONs, append a brief execution record to planning-notes.md: + +**File**: .workflow/active/{session_id}/planning-notes.md +**Location**: Create new section after "## Consolidated Constraints" (if not exists) +**Format**: +\`\`\` +## Task Generation (Phase 4) + +### [Action-Planning Agent - ${module.name}] YYYY-MM-DD +- **Note**: [智能补充:简短总结本模块任务数量、关键任务等] +\`\`\` + +**Note**: Multiple module agents will append their records. Phase 3 Integration Coordinator will add final summary. ` ) ); @@ -581,6 +636,17 @@ Module Count: ${modules.length} - No CROSS:: placeholders remaining in task JSONs - IMPL_PLAN.md and TODO_LIST.md generated with multi-module structure - Return: task count, per-module breakdown, resolved dependency count + +## PLANNING NOTES RECORD (REQUIRED) +After completing integration, append final summary to planning-notes.md: + +**File**: .workflow/active/{session_id}/planning-notes.md +**Location**: Under "## Task Generation (Phase 4)" section (after module agent records) +**Format**: +\`\`\` +### [Integration Coordinator] YYYY-MM-DD +- **Note**: [智能补充:简短总结总任务数、跨模块依赖解决情况等] +\`\`\` ` ) ``` diff --git a/ccw/src/tools/claude-cli-tools.ts b/ccw/src/tools/claude-cli-tools.ts index b54f6083..7e1fa798 100644 --- a/ccw/src/tools/claude-cli-tools.ts +++ b/ccw/src/tools/claude-cli-tools.ts @@ -733,66 +733,6 @@ export function getPromptFormat(projectDir: string): 'plain' | 'yaml' | 'json' { } } -/** - * Update default model setting - * @param projectDir - Project directory path - * @param model - Default model name - * @returns Updated settings config - */ -export function setDefaultModel( - projectDir: string, - model: string -): ClaudeCliSettingsConfig { - const settings = loadClaudeCliSettings(projectDir); - settings.defaultModel = model; - saveClaudeCliSettings(projectDir, settings); - return settings; -} - -/** - * Get default model setting - * @param projectDir - Project directory path - * @returns Current default model or undefined if not set - */ -export function getDefaultModel(projectDir: string): string | undefined { - try { - const settings = loadClaudeCliSettings(projectDir); - return settings.defaultModel; - } catch { - return undefined; - } -} - -/** - * Update auto-sync enabled setting - * @param projectDir - Project directory path - * @param enabled - Whether auto-sync is enabled - * @returns Updated settings config - */ -export function setAutoSyncEnabled( - projectDir: string, - enabled: boolean -): ClaudeCliSettingsConfig { - const settings = loadClaudeCliSettings(projectDir); - settings.autoSyncEnabled = enabled; - saveClaudeCliSettings(projectDir, settings); - return settings; -} - -/** - * Get auto-sync enabled setting - * @param projectDir - Project directory path - * @returns Current auto-sync status or undefined if not set - */ -export function getAutoSyncEnabled(projectDir: string): boolean | undefined { - try { - const settings = loadClaudeCliSettings(projectDir); - return settings.autoSyncEnabled; - } catch { - return undefined; - } -} - /** * Update smart context enabled setting * @param projectDir - Project directory path diff --git a/ccw/tests/settings-persistence.test.ts b/ccw/tests/settings-persistence.test.ts deleted file mode 100644 index 6de10cd4..00000000 --- a/ccw/tests/settings-persistence.test.ts +++ /dev/null @@ -1,375 +0,0 @@ -/** - * Unit tests for Settings Persistence Functions - * - * Tests the new setter/getter functions for ClaudeCliSettingsConfig: - * - setPromptFormat / getPromptFormat - * - setDefaultModel / getDefaultModel - * - setAutoSyncEnabled / getAutoSyncEnabled - * - setSmartContextEnabled / getSmartContextEnabled - * - setNativeResume / getNativeResume - */ - -import { after, afterEach, before, describe, it } from 'node:test'; -import assert from 'node:assert/strict'; -import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -// Set up isolated test environment -const TEST_CCW_HOME = mkdtempSync(join(tmpdir(), 'ccw-settings-test-')); -process.env.CCW_DATA_DIR = TEST_CCW_HOME; - -const claudeCliToolsPath = new URL('../dist/tools/claude-cli-tools.js', import.meta.url).href; - -describe('Settings Persistence Functions', async () => { - let claudeCliTools: any; - const testProjectDir = join(TEST_CCW_HOME, 'test-project'); - - before(async () => { - claudeCliTools = await import(claudeCliToolsPath); - }); - - after(() => { - rmSync(TEST_CCW_HOME, { recursive: true, force: true }); - }); - - afterEach(() => { - // Clean up settings file after each test - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - if (existsSync(settingsPath)) { - rmSync(settingsPath); - } - }); - - describe('setPromptFormat / getPromptFormat', () => { - it('should set and get prompt format', () => { - const result = claudeCliTools.setPromptFormat(testProjectDir, 'yaml'); - assert.equal(result.promptFormat, 'yaml'); - - const retrieved = claudeCliTools.getPromptFormat(testProjectDir); - assert.equal(retrieved, 'yaml'); - }); - - it('should persist prompt format to file', () => { - claudeCliTools.setPromptFormat(testProjectDir, 'json'); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - assert.ok(existsSync(settingsPath), 'Settings file should exist'); - - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.promptFormat, 'json'); - }); - - it('should update existing prompt format', () => { - claudeCliTools.setPromptFormat(testProjectDir, 'plain'); - claudeCliTools.setPromptFormat(testProjectDir, 'yaml'); - - const retrieved = claudeCliTools.getPromptFormat(testProjectDir); - assert.equal(retrieved, 'yaml'); - }); - - it('should return default when file does not exist', () => { - const retrieved = claudeCliTools.getPromptFormat(testProjectDir); - assert.equal(retrieved, 'plain'); - }); - - it('should accept all valid format values', () => { - const formats: Array<'plain' | 'yaml' | 'json'> = ['plain', 'yaml', 'json']; - - for (const format of formats) { - claudeCliTools.setPromptFormat(testProjectDir, format); - const retrieved = claudeCliTools.getPromptFormat(testProjectDir); - assert.equal(retrieved, format, `Format ${format} should be set correctly`); - } - }); - }); - - describe('setDefaultModel / getDefaultModel', () => { - it('should set and get default model', () => { - const result = claudeCliTools.setDefaultModel(testProjectDir, 'gemini-2.5-pro'); - assert.equal(result.defaultModel, 'gemini-2.5-pro'); - - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, 'gemini-2.5-pro'); - }); - - it('should persist default model to file', () => { - claudeCliTools.setDefaultModel(testProjectDir, 'claude-opus-4'); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - assert.ok(existsSync(settingsPath), 'Settings file should exist'); - - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.defaultModel, 'claude-opus-4'); - }); - - it('should update existing default model', () => { - claudeCliTools.setDefaultModel(testProjectDir, 'gpt-4.1'); - claudeCliTools.setDefaultModel(testProjectDir, 'gpt-5.2'); - - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, 'gpt-5.2'); - }); - - it('should return undefined when not set', () => { - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, undefined); - }); - - it('should handle arbitrary model names', () => { - const models = ['custom-model-1', 'test-model', 'my-fine-tuned-model']; - - for (const model of models) { - claudeCliTools.setDefaultModel(testProjectDir, model); - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, model, `Model ${model} should be set correctly`); - } - }); - }); - - describe('setAutoSyncEnabled / getAutoSyncEnabled', () => { - it('should set and get auto-sync enabled status', () => { - const result = claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - assert.equal(result.autoSyncEnabled, true); - - const retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, true); - }); - - it('should persist auto-sync status to file', () => { - claudeCliTools.setAutoSyncEnabled(testProjectDir, false); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - assert.ok(existsSync(settingsPath), 'Settings file should exist'); - - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.autoSyncEnabled, false); - }); - - it('should update existing auto-sync status', () => { - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - claudeCliTools.setAutoSyncEnabled(testProjectDir, false); - - const retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, false); - }); - - it('should return undefined when not set', () => { - const retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, undefined); - }); - - it('should toggle between true and false', () => { - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - let retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, true); - - claudeCliTools.setAutoSyncEnabled(testProjectDir, false); - retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, false); - - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - retrieved = claudeCliTools.getAutoSyncEnabled(testProjectDir); - assert.equal(retrieved, true); - }); - }); - - describe('setSmartContextEnabled / getSmartContextEnabled', () => { - it('should set and get smart context enabled status', () => { - const result = claudeCliTools.setSmartContextEnabled(testProjectDir, true); - assert.equal(result.smartContext.enabled, true); - - const retrieved = claudeCliTools.getSmartContextEnabled(testProjectDir); - assert.equal(retrieved, true); - }); - - it('should persist smart context status to file', () => { - claudeCliTools.setSmartContextEnabled(testProjectDir, true); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - assert.ok(existsSync(settingsPath), 'Settings file should exist'); - - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.smartContext.enabled, true); - }); - - it('should preserve other smartContext properties', () => { - // First, load settings to check default maxFiles - const settings = claudeCliTools.loadClaudeCliSettings(testProjectDir); - const defaultMaxFiles = settings.smartContext.maxFiles; - - claudeCliTools.setSmartContextEnabled(testProjectDir, true); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - - assert.equal(content.smartContext.enabled, true); - assert.equal(content.smartContext.maxFiles, defaultMaxFiles, 'maxFiles should be preserved'); - }); - - it('should return false when not set', () => { - const retrieved = claudeCliTools.getSmartContextEnabled(testProjectDir); - assert.equal(retrieved, false); - }); - }); - - describe('setNativeResume / getNativeResume', () => { - it('should set and get native resume status', () => { - const result = claudeCliTools.setNativeResume(testProjectDir, false); - assert.equal(result.nativeResume, false); - - const retrieved = claudeCliTools.getNativeResume(testProjectDir); - assert.equal(retrieved, false); - }); - - it('should persist native resume status to file', () => { - claudeCliTools.setNativeResume(testProjectDir, false); - - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - assert.ok(existsSync(settingsPath), 'Settings file should exist'); - - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.nativeResume, false); - }); - - it('should return true when not set (default)', () => { - const retrieved = claudeCliTools.getNativeResume(testProjectDir); - assert.equal(retrieved, true); - }); - }); - - describe('Multiple settings updates', () => { - it('should handle multiple settings updates in sequence', () => { - claudeCliTools.setPromptFormat(testProjectDir, 'yaml'); - claudeCliTools.setDefaultModel(testProjectDir, 'gemini-2.5-pro'); - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - claudeCliTools.setSmartContextEnabled(testProjectDir, true); - claudeCliTools.setNativeResume(testProjectDir, false); - - assert.equal(claudeCliTools.getPromptFormat(testProjectDir), 'yaml'); - assert.equal(claudeCliTools.getDefaultModel(testProjectDir), 'gemini-2.5-pro'); - assert.equal(claudeCliTools.getAutoSyncEnabled(testProjectDir), true); - assert.equal(claudeCliTools.getSmartContextEnabled(testProjectDir), true); - assert.equal(claudeCliTools.getNativeResume(testProjectDir), false); - }); - - it('should preserve existing settings when updating one', () => { - claudeCliTools.setPromptFormat(testProjectDir, 'json'); - claudeCliTools.setDefaultModel(testProjectDir, 'test-model'); - - // Update only auto-sync - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - - // Verify previous settings are preserved - assert.equal(claudeCliTools.getPromptFormat(testProjectDir), 'json'); - assert.equal(claudeCliTools.getDefaultModel(testProjectDir), 'test-model'); - assert.equal(claudeCliTools.getAutoSyncEnabled(testProjectDir), true); - }); - }); - - describe('Performance', () => { - it('should complete setter operations in under 10ms', () => { - const operations = [ - () => claudeCliTools.setPromptFormat(testProjectDir, 'yaml'), - () => claudeCliTools.setDefaultModel(testProjectDir, 'test-model'), - () => claudeCliTools.setAutoSyncEnabled(testProjectDir, true), - () => claudeCliTools.setSmartContextEnabled(testProjectDir, true), - () => claudeCliTools.setNativeResume(testProjectDir, false), - ]; - - for (const operation of operations) { - const start = Date.now(); - operation(); - const duration = Date.now() - start; - assert.ok(duration < 10, `Operation should complete in under 10ms (took ${duration}ms)`); - } - }); - - it('should complete getter operations in under 10ms', () => { - // Set up some data first - claudeCliTools.setPromptFormat(testProjectDir, 'yaml'); - claudeCliTools.setDefaultModel(testProjectDir, 'test-model'); - claudeCliTools.setAutoSyncEnabled(testProjectDir, true); - - const operations = [ - () => claudeCliTools.getPromptFormat(testProjectDir), - () => claudeCliTools.getDefaultModel(testProjectDir), - () => claudeCliTools.getAutoSyncEnabled(testProjectDir), - () => claudeCliTools.getSmartContextEnabled(testProjectDir), - () => claudeCliTools.getNativeResume(testProjectDir), - ]; - - for (const operation of operations) { - const start = Date.now(); - operation(); - const duration = Date.now() - start; - assert.ok(duration < 10, `Operation should complete in under 10ms (took ${duration}ms)`); - } - }); - }); - - describe('File corruption handling', () => { - it('should handle invalid JSON gracefully', () => { - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - const claudeDir = join(TEST_CCW_HOME, '.claude'); - - // Create .claude directory if it doesn't exist - if (!existsSync(claudeDir)) { - mkdtempSync(claudeDir); - } - - // Write invalid JSON - writeFileSync(settingsPath, '{invalid json}', 'utf-8'); - - // Getters should return defaults - assert.equal(claudeCliTools.getPromptFormat(testProjectDir), 'plain'); - assert.equal(claudeCliTools.getDefaultModel(testProjectDir), undefined); - assert.equal(claudeCliTools.getAutoSyncEnabled(testProjectDir), undefined); - }); - - it('should recover from corrupted file by overwriting', () => { - const settingsPath = join(TEST_CCW_HOME, '.claude', 'cli-settings.json'); - const claudeDir = join(TEST_CCW_HOME, '.claude'); - - // Create .claude directory if it doesn't exist - if (!existsSync(claudeDir)) { - mkdtempSync(claudeDir); - } - - // Write invalid JSON - writeFileSync(settingsPath, '{invalid json}', 'utf-8'); - - // Setter should fix the file - claudeCliTools.setPromptFormat(testProjectDir, 'yaml'); - - // Should now read correctly - assert.equal(claudeCliTools.getPromptFormat(testProjectDir), 'yaml'); - - // File should be valid JSON - const content = JSON.parse(readFileSync(settingsPath, 'utf-8')); - assert.equal(content.promptFormat, 'yaml'); - }); - }); - - describe('Edge cases', () => { - it('should handle empty string for defaultModel', () => { - claudeCliTools.setDefaultModel(testProjectDir, ''); - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, ''); - }); - - it('should handle very long model names', () => { - const longModelName = 'a'.repeat(1000); - claudeCliTools.setDefaultModel(testProjectDir, longModelName); - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, longModelName); - }); - - it('should handle special characters in model names', () => { - const specialName = 'model-@#$%^&*()_+{}[]|:;<>?,./~`'; - claudeCliTools.setDefaultModel(testProjectDir, specialName); - const retrieved = claudeCliTools.getDefaultModel(testProjectDir); - assert.equal(retrieved, specialName); - }); - }); -});