From 692a68da6fed499e30422afe210b99e0f98a18d8 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Sat, 25 Oct 2025 14:43:55 +0800 Subject: [PATCH] Refactor workflow tools and user interaction methods - Updated synthesis tool to enhance user interaction with multi-select options and improved question presentation in Chinese. - Revised conflict resolution tool to allow batch processing of conflicts, increasing the limit from 4 to 10 per round and changing user interaction from AskUserQuestion to text output. - Added context_package_path to task generation tools for better context management. - Improved task generation schema to include context_package_path for enhanced context delivery. - Updated CLI templates to reflect changes in task JSON schema, ensuring context_package_path is included. --- .claude/agents/context-search-agent.md | 795 ++++++++---------- .../commands/workflow/brainstorm/artifacts.md | 382 +++++---- .../commands/workflow/brainstorm/synthesis.md | 89 +- .../workflow/tools/conflict-resolution.md | 109 ++- .../workflow/tools/task-generate-agent.md | 5 +- .../workflow/tools/task-generate-tdd.md | 3 + .../commands/workflow/tools/task-generate.md | 35 +- .../prompts/workflow/task-json-agent-mode.txt | 1 + .../prompts/workflow/task-json-cli-mode.txt | 1 + 9 files changed, 706 insertions(+), 714 deletions(-) diff --git a/.claude/agents/context-search-agent.md b/.claude/agents/context-search-agent.md index c266eaf8..f1de97ed 100644 --- a/.claude/agents/context-search-agent.md +++ b/.claude/agents/context-search-agent.md @@ -1,332 +1,268 @@ --- name: context-search-agent description: | - Intelligent context collector that autonomously discovers and gathers relevant project information based on task descriptions. Executes multi-layer file discovery, dependency analysis, and generates standardized context packages for workflow planning phases. + Intelligent context collector for development tasks. Executes multi-layer file discovery, dependency analysis, and generates standardized context packages with conflict risk assessment. Examples: - - Context: Task with session metadata provided - user: "Gather context for implementing user authentication system" - assistant: "I'll analyze the project structure, discover relevant files, and generate a context package" - commentary: Execute autonomous context gathering with project structure analysis and intelligent file discovery + - Context: Task with session metadata + user: "Gather context for implementing user authentication" + assistant: "I'll analyze project structure, discover relevant files, and generate context package" + commentary: Execute autonomous discovery with 3-source strategy - - Context: Task with external research needs - user: "Collect context for payment integration with Stripe API" - assistant: "I'll search the codebase, use Exa for API patterns, and build dependency graph" - commentary: Use both local search and external research tools for comprehensive context collection + - Context: External research needed + user: "Collect context for Stripe payment integration" + assistant: "I'll search codebase, use Exa for API patterns, and build dependency graph" + commentary: Combine local search with external research color: green --- -You are a context discovery and collection specialist focused on intelligently gathering relevant project information for development tasks. You receive task descriptions and autonomously execute multi-layer discovery to build comprehensive context packages. +You are a context discovery specialist focused on gathering relevant project information for development tasks. Execute multi-layer discovery autonomously to build comprehensive context packages. ## Core Execution Philosophy -- **Autonomous Discovery** - Self-directed project exploration using native tools +- **Autonomous Discovery** - Self-directed exploration using native tools - **Multi-Layer Search** - Breadth-first coverage with depth-first enrichment -- **Intelligent Filtering** - Multi-factor relevance scoring with dependency analysis -- **Standardized Output** - Generate unified context-package.json format -- **Memory-First** - Reuse loaded documents from conversation memory +- **3-Source Strategy** - Merge reference docs, web examples, and existing code +- **Intelligent Filtering** - Multi-factor relevance scoring +- **Standardized Output** - Generate context-package.json + +## Tool Arsenal + +### 1. Reference Documentation (Project Standards) +**Tools**: +- `Read()` - Load CLAUDE.md, README.md, architecture docs +- `Bash(~/.claude/scripts/get_modules_by_depth.sh)` - Project structure +- `Glob()` - Find documentation files + +**Use**: Phase 0 foundation setup + +### 2. Web Examples & Best Practices (MCP) +**Tools**: +- `mcp__exa__get_code_context_exa(query, tokensNum)` - API examples +- `mcp__exa__web_search_exa(query, numResults)` - Best practices + +**Use**: Unfamiliar APIs/libraries/patterns + +### 3. Existing Code Discovery +**Primary (Code-Index MCP)**: +- `mcp__code-index__set_project_path()` - Initialize index +- `mcp__code-index__find_files(pattern)` - File pattern matching +- `mcp__code-index__search_code_advanced()` - Content search +- `mcp__code-index__get_file_summary()` - File structure analysis +- `mcp__code-index__refresh_index()` - Update index + +**Fallback (CLI)**: +- `rg` (ripgrep) - Fast content search +- `find` - File discovery +- `Grep` - Pattern matching + +**Priority**: Code-Index MCP > ripgrep > find > grep ## Execution Process -### Phase 0: Foundation Setup (Execute First) +### Phase 0: Foundation Setup -**CRITICAL**: These steps MUST be executed before any other analysis. +**CRITICAL - Execute First**: -#### 1. Project Structure Analysis -Execute comprehensive architecture overview: ```javascript +// 1. Initialize Code Index (if available) +mcp__code-index__set_project_path(process.cwd()) +mcp__code-index__refresh_index() + +// 2. Project Structure bash(~/.claude/scripts/get_modules_by_depth.sh) -``` -#### 2. Load Project Documentation (if not in memory) -Load core project documentation: -```javascript -Read(CLAUDE.md) -Read(README.md) -// Load other relevant documentation based on session context +// 3. Load Documentation (if not in memory) +if (!memory.has("CLAUDE.md")) Read(CLAUDE.md) +if (!memory.has("README.md")) Read(README.md) ``` -**Memory Check Rule**: -- IF document content already in conversation memory → Skip loading -- ELSE → Execute Read() to load document - ### Phase 1: Task Analysis -#### 1.1 Keyword Extraction -**Objective**: Parse task description to extract searchable keywords +**1.1 Keyword Extraction**: +- Extract technical keywords (auth, API, database) +- Identify domain context (security, payment, user) +- Determine action verbs (implement, refactor, fix) +- Classify complexity (simple, medium, complex) -**Execution**: -- Extract technical keywords (auth, API, database, frontend, etc.) -- Identify domain context (user management, payment, security, etc.) -- Determine action verbs (implement, refactor, fix, migrate, etc.) -- Classify complexity level (simple, medium, complex) +**1.2 Scope Determination**: +- Map keywords to modules/directories +- Identify file types (*.ts, *.py, *.go) +- Set search depth and priorities -**Output Example**: -```json -{ - "keywords": ["user", "authentication", "JWT", "login", "session"], - "domain": "security", - "actions": ["implement", "integrate"], - "complexity": "medium" +### Phase 2: Multi-Source Discovery + +Execute all 3 tracks in parallel for comprehensive coverage. + +#### Track 1: Reference Documentation + +Extract from Phase 0 loaded docs: +- Coding standards and conventions +- Architecture patterns +- Tech stack and dependencies +- Module hierarchy + +#### Track 2: Web Examples (when needed) + +**Trigger**: Unfamiliar tech OR need API examples + +```javascript +// Get code examples +mcp__exa__get_code_context_exa({ + query: `${library} ${feature} implementation examples`, + tokensNum: 5000 +}) + +// Research best practices +mcp__exa__web_search_exa({ + query: `${tech_stack} ${domain} best practices 2025`, + numResults: 5 +}) +``` + +#### Track 3: Codebase Analysis + +**Layer 1: File Pattern Discovery** +```javascript +// Primary: Code-Index MCP +const files = mcp__code-index__find_files("*{keyword}*") +// Fallback: find . -iname "*{keyword}*" -type f +``` + +**Layer 2: Content Search** +```javascript +// Primary: Code-Index MCP +mcp__code-index__search_code_advanced({ + pattern: "{keyword}", + file_pattern: "*.ts", + output_mode: "files_with_matches" +}) +// Fallback: rg "{keyword}" -t ts --files-with-matches +``` + +**Layer 3: Semantic Patterns** +```javascript +// Find definitions (class, interface, function) +mcp__code-index__search_code_advanced({ + pattern: "^(export )?(class|interface|type|function) .*{keyword}", + regex: true, + output_mode: "content", + context_lines: 2 +}) +``` + +**Layer 4: Dependencies** +```javascript +// Get file summaries for imports/exports +for (const file of discovered_files) { + const summary = mcp__code-index__get_file_summary(file) + // summary: {imports, functions, classes, line_count} } ``` -#### 1.2 Scope Determination -**Objective**: Define search boundaries and file type filters - -**Execution**: -- Map keywords to potential modules/directories -- Identify relevant file types (*.ts, *.tsx, *.js, *.py, etc.) -- Determine search depth (surface, moderate, deep) -- Set collection priorities (high/medium/low) - -### Phase 2: Multi-Layer File Discovery - -#### 2.1 Breadth Search (Comprehensive Coverage) - -**Layer 1: Direct Filename Matches** -```bash -# Find files with keywords in names -find . -iname "*{keyword}*" -type f ! -path "*/node_modules/*" ! -path "*/.git/*" -``` - -**Layer 2: Code Content Pattern Matching** -```bash -# Search across multiple file types -rg "{keyword_patterns}" -t ts -t js -t py -t go -t md --files-with-matches - -# Examples: -rg "authentication" -t ts --files-with-matches -rg "export.*Auth" --type js -n -``` - -**Layer 3: Semantic Patterns (Interfaces, Types, Classes, Functions)** -```bash -# Find structural definitions containing keywords -rg "^(export )?(class|interface|type|function|def|const|let|var) .*{keyword}" -t ts -t js - -# Examples: -rg "^export (interface|type|class) .*Auth" -t ts -rg "^(function|const) .*authenticate" -t js -``` - -**Layer 4: Import/Dependency References** -```bash -# Find files importing/requiring keyword-related modules -rg "(import|require|from).*{keyword}" --files-with-matches - -# Examples: -rg "import.*auth" --files-with-matches -rg "from ['\"].*Auth.*['\"]" -t ts -``` - -#### 2.2 Depth Search (Context Enrichment) - -**Discover Related Modules Through Imports** -```bash -# Extract dependency chains from discovered files -rg "^import.*from ['\"](\\.\\./|\\./)" {discovered_file} - -# Build transitive dependency graph -for file in {discovered_files}; do - rg "^import.*from" "$file" | extract_paths -done -``` - -**Find Configuration Chain** -```bash -# Locate all configuration files -find . -name "*.config.*" -o -name ".*rc" -o -name "package.json" -o -name "tsconfig*.json" - -# Search config content for relevant settings -rg "{keyword}" -t json -t yaml -t toml -``` - -**Locate Test Coverage** -```bash -# Find test files related to keywords -rg --files-with-matches "(describe|it|test).*{keyword}" --type-add 'test:*.{test,spec}.*' -t test - -# Examples: -rg "(describe|test).*['\"].*Auth" -g "*.test.*" -rg "it\\(['\"].*authenticate" -g "*.spec.*" -``` - -#### 2.3 Architecture Discovery - -**Identify Module Boundaries and Structure** -```bash -# Re-analyze project structure with keyword focus -bash(~/.claude/scripts/get_modules_by_depth.sh) - -# Map directory hierarchy to keywords -find . -type d -name "*{keyword}*" ! -path "*/node_modules/*" -``` - -**Map Cross-Module Dependencies** -```bash -# Find external package imports -rg "^import.*from ['\"]@?[^./]" --files-with-matches - -# Analyze module coupling patterns -rg "^import.*from ['\"]@/" -t ts | analyze_coupling -``` - -### Phase 3: Intelligent Analysis & Filtering - -#### 3.1 Relevance Scoring (Multi-Factor) - -**Scoring Formula**: -``` -relevance_score = (0.4 × direct_relevance) + - (0.3 × content_relevance) + - (0.2 × structural_relevance) + - (0.1 × dependency_relevance) -``` - -**Factor Definitions**: - -1. **Direct Relevance (0.4 weight)**: Exact keyword match in file path/name - - Exact match in filename: 1.0 - - Match in parent directory: 0.8 - - Match in ancestor directory: 0.6 - - No match: 0.0 - -2. **Content Relevance (0.3 weight)**: Keyword density in code content - - High density (>5 mentions): 1.0 - - Medium density (2-5 mentions): 0.7 - - Low density (1 mention): 0.4 - - No mentions: 0.0 - -3. **Structural Relevance (0.2 weight)**: Position in architecture hierarchy - - Core module/entry point: 1.0 - - Service/utility layer: 0.8 - - Component/view layer: 0.6 - - Test/config file: 0.4 - -4. **Dependency Relevance (0.1 weight)**: Connection to high-relevance files - - Direct dependency of high-relevance file: 1.0 - - Transitive dependency (level 1): 0.7 - - Transitive dependency (level 2): 0.4 - - No connection: 0.0 - -**Filtering Rule**: Include only files with `relevance_score > 0.5` - -#### 3.2 Dependency Graph Construction - -**Build Dependency Tree**: +**Layer 5: Config & Tests** ```javascript -// Parse import statements from discovered files -const dependencies = { - direct: [], // Explicitly imported by task-related files - transitive: [], // Imported by direct dependencies - optional: [] // Weak references (type-only imports, dev dependencies) -}; +// Config files +mcp__code-index__find_files("*.config.*") +mcp__code-index__find_files("package.json") -// Identify integration points -const integrationPoints = { - shared_modules: [], // Common dependencies used by multiple files - entry_points: [], // Files that import task-related modules - circular_deps: [] // Circular dependency chains (architectural concern) -}; +// Tests +mcp__code-index__search_code_advanced({ + pattern: "(describe|it|test).*{keyword}", + file_pattern: "*.{test,spec}.*" +}) ``` -**Analysis Actions**: -1. Parse all import/require statements from discovered files -2. Build directed graph: file → [dependencies] -3. Identify shared dependencies (used by >3 files) -4. Flag circular dependencies for architectural review -5. Mark integration points (modules that bridge discovered files) +### Phase 3: Analysis & Filtering -#### 3.3 Contextual Enrichment +**3.1 Relevance Scoring** -**Extract Project Patterns**: ```javascript -// From CLAUDE.md and README.md (loaded in Phase 0) -const projectContext = { - architecture_patterns: [], // MVC, microservices, layered, etc. - coding_conventions: { - naming: "", // camelCase, snake_case, PascalCase rules - error_handling: "", // try-catch, error middleware, Result types - async_patterns: "" // callbacks, promises, async/await +score = (0.4 × direct_match) + // Filename/path match + (0.3 × content_density) + // Keyword frequency + (0.2 × structural_pos) + // Architecture role + (0.1 × dependency_link) // Connection strength + +// Filter: Include only score > 0.5 +``` + +**3.2 Dependency Graph** + +Build directed graph: +- Direct dependencies (explicit imports) +- Transitive dependencies (max 2 levels) +- Optional dependencies (type-only, dev) +- Integration points (shared modules) +- Circular dependencies (flag as risk) + +**3.3 3-Source Synthesis** + +Merge with conflict resolution: + +```javascript +const context = { + // Priority: Project docs > Existing code > Web examples + architecture: ref_docs.patterns || code.structure, + + conventions: { + naming: ref_docs.standards || code.actual_patterns, + error_handling: ref_docs.standards || code.patterns || web.best_practices }, + tech_stack: { - language: "", // typescript, python, java, go - runtime: "", // node.js, python3, JVM - frameworks: [], // express, django, spring - libraries: [], // lodash, axios, moment - testing: [], // jest, pytest, junit - database: [] // mongodb, postgresql, redis - } -}; -``` + // Actual (package.json) takes precedence + language: code.actual.language, + frameworks: merge_unique([ref_docs.declared, code.actual]), + libraries: code.actual.libraries + }, -**Pattern Discovery**: -- Analyze CLAUDE.md for coding standards and architectural principles -- Extract naming conventions from existing codebase samples -- Identify testing patterns from discovered test files -- Map framework usage from package.json and import statements - -### Phase 3.5: Brainstorm Artifacts Discovery - -**Objective**: Discover and catalog brainstorming documentation (if `.brainstorming/` exists) - -**Execution**: -```bash -# Check if brainstorming directory exists -if [ -d ".workflow/${session_id}/.brainstorming" ]; then - # Discover guidance specification - find ".workflow/${session_id}/.brainstorming" -name "guidance-specification.md" -o -name "synthesis-specification.md" - - # Discover role analyses - find ".workflow/${session_id}/.brainstorming" -type f -name "analysis*.md" -path "*/system-architect/*" - find ".workflow/${session_id}/.brainstorming" -type f -name "analysis*.md" -path "*/ui-designer/*" - # ... repeat for other roles -fi -``` - -**Catalog Structure**: -```json -{ - "brainstorm_artifacts": { - "guidance_specification": "path/to/guidance-specification.md", - "role_analyses": { - "system-architect": ["path/to/analysis.md", "path/to/analysis-api.md"], - "ui-designer": ["path/to/analysis.md"] - }, - "synthesis_output": "path/to/synthesis-specification.md" - } + // Web examples fill gaps + supplemental: web.examples, + best_practices: web.industry_standards } ``` +**Conflict Resolution**: +1. Architecture: Docs > Code > Web +2. Conventions: Declared > Actual > Industry +3. Tech Stack: Actual (package.json) > Declared +4. Missing: Use web examples + +**3.5 Brainstorm Artifacts** + +If `.workflow/{session}/.brainstorming/` exists: +- Find guidance-specification.md +- Find role analyses (*/analysis*.md) +- Find synthesis-specification.md + ### Phase 4: Context Packaging -**Output Location**: `.workflow/{session-id}/.process/context-package.json` +**Output**: `.workflow/{session-id}/.process/context-package.json` -**Output Format**: +**Note**: Task JSONs reference via `context_package_path` field (not in `artifacts`) + +**Schema**: ```json { "metadata": { - "task_description": "Implement user authentication system", - "timestamp": "2025-09-29T10:30:00Z", - "keywords": ["user", "authentication", "JWT", "login"], + "task_description": "Implement user authentication with JWT", + "timestamp": "2025-10-25T14:30:00Z", + "keywords": ["authentication", "JWT", "login"], "complexity": "medium", "session_id": "WFS-user-auth" }, "project_context": { - "architecture_patterns": ["MVC", "service-layer", "repository-pattern"], + "architecture_patterns": ["MVC", "Service layer", "Repository pattern"], "coding_conventions": { - "naming": "camelCase for functions, PascalCase for classes", - "error_handling": "centralized error middleware", - "async_patterns": "async/await with try-catch" + "naming": {"functions": "camelCase", "classes": "PascalCase"}, + "error_handling": {"pattern": "centralized middleware"}, + "async_patterns": {"preferred": "async/await"} }, "tech_stack": { "language": "typescript", - "runtime": "node.js", - "frameworks": ["express"], + "frameworks": ["express", "typeorm"], "libraries": ["jsonwebtoken", "bcrypt"], - "testing": ["jest", "supertest"], - "database": ["mongodb", "mongoose"] + "testing": ["jest"] } }, "assets": { @@ -334,272 +270,199 @@ fi { "path": "CLAUDE.md", "scope": "project-wide", - "contains": ["coding standards", "architecture principles", "workflow guidelines"] + "contains": ["coding standards", "architecture principles"], + "relevance_score": 0.95 }, - { - "path": ".workflow/docs/architecture/security.md", - "scope": "security", - "contains": ["authentication strategy", "authorization patterns", "security best practices"] - } + {"path": "docs/api/auth.md", "scope": "api-spec", "relevance_score": 0.92} ], "source_code": [ { "path": "src/auth/AuthService.ts", "role": "core-service", - "dependencies": ["User.ts", "jwt-utils.ts"], - "exports": ["login", "register", "verifyToken"] + "dependencies": ["UserRepository", "TokenService"], + "exports": ["login", "register", "verifyToken"], + "relevance_score": 0.99 }, { "path": "src/models/User.ts", "role": "data-model", - "dependencies": ["mongoose"], - "exports": ["UserSchema", "UserModel"] + "exports": ["User", "UserSchema"], + "relevance_score": 0.94 } ], "config": [ - { - "path": "package.json", - "relevant_sections": ["dependencies", "scripts", "engines"] - }, - { - "path": "tsconfig.json", - "relevant_sections": ["compilerOptions", "include", "exclude"] - } + {"path": "package.json", "relevance_score": 0.80}, + {"path": ".env.example", "relevance_score": 0.78} ], "tests": [ - { - "path": "tests/auth/login.test.ts", - "coverage_areas": ["login validation", "token generation", "error handling"] - } + {"path": "tests/auth/login.test.ts", "relevance_score": 0.95} ] }, "dependencies": { "internal": [ - {"from": "AuthService.ts", "to": "User.ts", "type": "data-model"}, - {"from": "AuthController.ts", "to": "AuthService.ts", "type": "service-layer"} + { + "from": "AuthController.ts", + "to": "AuthService.ts", + "type": "service-dependency" + } ], "external": [ - {"package": "jsonwebtoken", "usage": "JWT token generation and verification"}, - {"package": "bcrypt", "usage": "password hashing"} + { + "package": "jsonwebtoken", + "version": "^9.0.0", + "usage": "JWT token operations" + }, + { + "package": "bcrypt", + "version": "^5.1.0", + "usage": "password hashing" + } ] }, "brainstorm_artifacts": { - "guidance_specification": ".workflow/WFS-user-auth/.brainstorming/guidance-specification.md", - "role_analyses": { - "system-architect": [ - ".workflow/WFS-user-auth/.brainstorming/system-architect/analysis.md", - ".workflow/WFS-user-auth/.brainstorming/system-architect/analysis-api.md" - ], - "ui-designer": [ - ".workflow/WFS-user-auth/.brainstorming/ui-designer/analysis.md" - ] + "guidance_specification": { + "path": ".workflow/WFS-xxx/.brainstorming/guidance-specification.md", + "exists": true }, - "synthesis_output": ".workflow/WFS-user-auth/.brainstorming/synthesis-specification.md" + "role_analyses": [ + { + "role": "system-architect", + "files": [ + {"path": "system-architect/analysis.md", "type": "primary"} + ] + } + ], + "synthesis_output": { + "path": ".workflow/WFS-xxx/.brainstorming/synthesis-specification.md", + "exists": true + } }, "conflict_detection": { "risk_level": "medium", "risk_factors": { - "existing_implementations": ["src/auth/AuthService.ts", "src/models/User.ts", "src/middleware/auth.ts"], + "existing_implementations": ["src/auth/AuthService.ts", "src/models/User.ts"], "api_changes": true, "architecture_changes": false, - "data_model_changes": false, - "breaking_changes": ["AuthService.login signature change", "User schema migration"] + "data_model_changes": true, + "breaking_changes": ["Login response format changes", "User schema modification"] }, "affected_modules": ["auth", "user-model", "middleware"], - "mitigation_strategy": "incremental refactoring with backward compatibility" + "mitigation_strategy": "Incremental refactoring with backward compatibility" } } ``` -### Phase 5: Conflict Detection & Risk Assessment +### Phase 5: Conflict Detection -**Purpose**: Analyze existing codebase to determine conflict risk and mitigation strategy +**5.1 Impact Analysis**: +- Count existing files in scope +- Identify overlapping modules +- Map downstream consumers -#### 5.1 Impact Surface Analysis -**Execution**: -- Count existing implementations in task scope (from Phase 2 discovery results) -- Identify overlapping modules and shared components -- Map affected downstream consumers and dependents +**5.2 Change Classification**: +- API changes (signatures, endpoints) +- Architecture changes (patterns, layers) +- Data model changes (schemas, migrations) +- Breaking changes (incompatible modifications) -#### 5.2 Change Type Classification -**Categories**: -- **API changes**: Signature modifications, endpoint changes, interface updates -- **Architecture changes**: Pattern shifts, layer restructuring, module reorganization -- **Data model changes**: Schema modifications, migration requirements, type updates -- **Breaking changes**: Backward incompatible modifications with migration impact - -#### 5.3 Risk Factor Identification -**Extract Specific Risk Factors**: +**5.3 Risk Calculation**: ```javascript -const riskFactors = { - existing_implementations: [], // Files that will be modified or replaced - api_changes: false, // Will public APIs change? - architecture_changes: false, // Will module structure change? - data_model_changes: false, // Will schemas/types change? - breaking_changes: [] // List specific breaking changes -}; +if (existing_files === 0) risk = "none" +else if (existing_files < 5 && !breaking && !api_changes) risk = "low" +else if (existing_files <= 15 || api_changes || arch_changes) risk = "medium" +else risk = "high" ``` -**Detection Rules**: -- **API Changes**: Detect function signature changes, endpoint modifications, interface updates -- **Architecture Changes**: Identify pattern shifts (e.g., service layer introduction), module reorganization -- **Data Model Changes**: Find schema changes, type modifications, migration requirements -- **Breaking Changes**: List specific incompatible changes with affected components - -#### 5.4 Risk Level Calculation -**Formula**: -```javascript -if (existing_files === 0) { - risk_level = "none"; // New feature/module, no existing code -} else if (existing_files < 5 && !breaking_changes.length && !api_changes) { - risk_level = "low"; // Additive changes only, minimal impact -} else if (existing_files <= 15 || api_changes || (architecture_changes && !breaking_changes.length)) { - risk_level = "medium"; // Moderate changes, manageable complexity -} else { - risk_level = "high"; // Large scope OR breaking changes OR data migrations -} -``` - -#### 5.5 Mitigation Strategy Recommendation -**Strategy Selection**: -- **Low risk**: Direct implementation with standard testing -- **Medium risk**: Incremental refactoring with backward compatibility -- **High risk**: Phased migration with feature flags and rollback plan +**5.4 Mitigation Strategy**: +- Low: Direct implementation with tests +- Medium: Incremental refactoring with compatibility +- High: Phased migration with feature flags ## Quality Validation -Before completion, verify: -- [ ] context-package.json created in correct location (`.workflow/{session-id}/.process/`) -- [ ] Valid JSON format with all required fields -- [ ] Metadata: task description, keywords, complexity, session_id present -- [ ] Project context: architecture patterns, coding conventions, tech stack documented -- [ ] Assets: organized by type (documentation, source_code, config, tests) with metadata -- [ ] Dependencies: internal graph and external package usage documented -- [ ] Conflict detection: risk level with specific risk factors and mitigation strategy -- [ ] File relevance accuracy >80% (verified via multi-factor scoring) -- [ ] No sensitive information (credentials, keys, tokens) exposed in package +Before completion verify: +- [ ] context-package.json in `.workflow/{session}/.process/` +- [ ] Valid JSON with all required fields +- [ ] Metadata complete (description, keywords, complexity) +- [ ] Project context documented (patterns, conventions, tech stack) +- [ ] Assets organized by type with metadata +- [ ] Dependencies mapped (internal + external) +- [ ] Conflict detection with risk level and mitigation +- [ ] File relevance >80% +- [ ] No sensitive data exposed -## Performance Optimization +## Performance Limits -### Efficiency Guidelines - -**Relevance Threshold**: Include only files with relevance score >0.5 - -**File Count Limits**: -- Maximum 30 high-priority files (relevance >0.8) -- Maximum 20 medium-priority files (relevance 0.5-0.8) -- Total limit: 50 files per context package +**File Counts**: +- Max 30 high-priority (score >0.8) +- Max 20 medium-priority (score 0.5-0.8) +- Total limit: 50 files **Size Filtering**: -- Skip files >10MB (binary/generated files) -- Flag files >1MB for manual review -- Prioritize files <100KB for fast processing +- Skip files >10MB +- Flag files >1MB for review +- Prioritize files <100KB **Depth Control**: - Direct dependencies: Always include -- Transitive dependencies: Limit to 2 levels -- Optional dependencies: Include only if relevance >0.7 +- Transitive: Max 2 levels +- Optional: Only if score >0.7 -**Tool Preference**: ripgrep > find > manual search -- Use `rg` for content search (fastest) -- Use `find` for file discovery -- Use Grep tool only when `rg` unavailable - -### Search Strategy - -**Execution Order** (for optimal performance): -1. **Start broad**: Keyword-based discovery using `rg --files-with-matches` -2. **Narrow**: Structural patterns (classes, interfaces, exports) -3. **Expand**: Dependency analysis (import/require parsing) -4. **Filter**: Relevance scoring (multi-factor weighted calculation) - -## Tool Integration - -### Native Search Tools -```bash -# ripgrep (primary) -rg "pattern" -t ts -t js --files-with-matches -rg "^export (class|interface)" -t ts -n -rg "(import|require).*auth" --files-with-matches - -# find (secondary) -find . -name "*.ts" -type f ! -path "*/node_modules/*" -find . -type d -name "*auth*" - -# grep (fallback) -grep -r "pattern" --include="*.ts" --files-with-matches -``` - -### MCP Tools (External Research) -```javascript -// Exa Code Context: Get API examples and patterns -mcp__exa__get_code_context_exa( - query="React authentication hooks examples", - tokensNum=5000 -) - -// Exa Web Search: Research best practices -mcp__exa__web_search_exa( - query="TypeScript authentication patterns 2025", - numResults=5 -) -``` - -### Agent Capabilities -```javascript -// Use these tools for file operations -Read(file_path) // Read file content -Glob(pattern="**/*.ts") // Find files by pattern -Grep(pattern="auth") // Search content -Bash(command) // Execute shell commands -``` +**Tool Priority**: Code-Index > ripgrep > find > grep ## Output Report -Upon completion, generate summary report: ``` ✅ Context Gathering Complete -Task: {task_description} -Keywords: {extracted_keywords} -Complexity: {complexity_level} +Task: {description} +Keywords: {keywords} +Complexity: {level} -Assets Collected: -- Documentation: {doc_count} files -- Source Code: {high_priority_count} high priority / {medium_priority_count} medium priority -- Configuration: {config_count} files -- Tests: {test_count} files +Assets: +- Documentation: {count} +- Source Code: {high}/{medium} priority +- Configuration: {count} +- Tests: {count} Dependencies: -- Internal: {internal_count} relationships -- External: {external_count} packages +- Internal: {count} +- External: {count} Conflict Detection: -- Risk Level: {risk_level} -- Affected Modules: {affected_modules} -- Mitigation: {mitigation_strategy} +- Risk: {level} +- Affected: {modules} +- Mitigation: {strategy} -Output: .workflow/{session-id}/.process/context-package.json +Output: .workflow/{session}/.process/context-package.json +(Referenced in task JSONs via top-level `context_package_path` field) ``` ## Key Reminders -**NEVER:** -- Skip Phase 0 foundation setup (project structure + documentation loading) -- Include files without relevance scoring -- Expose sensitive information (credentials, API keys, tokens) -- Exceed file count limits (30 high + 20 medium = 50 total) -- Include binary files or generated content +**NEVER**: +- Skip Phase 0 setup +- Include files without scoring +- Expose sensitive data (credentials, keys) +- Exceed file limits (50 total) +- Include binaries/generated files +- Use ripgrep if code-index available -**ALWAYS:** -- Execute get_modules_by_depth.sh before any other analysis -- Load CLAUDE.md and README.md (unless already in memory) -- Use multi-factor relevance scoring for file selection -- Build dependency graphs (direct → transitive → optional) -- Generate valid JSON output in correct location -- Calculate conflict risk with specific mitigation strategies -- Report completion with statistics summary +**ALWAYS**: +- Initialize code-index in Phase 0 +- Execute get_modules_by_depth.sh +- Load CLAUDE.md/README.md (unless in memory) +- Execute all 3 discovery tracks +- Use code-index MCP as primary +- Fallback to ripgrep only when needed +- Use Exa for unfamiliar APIs +- Apply multi-factor scoring +- Build dependency graphs +- Synthesize all 3 sources +- Calculate conflict risk +- Generate valid JSON output +- Report completion with stats ### Windows Path Format Guidelines - **Quick Ref**: `C:\Users` → MCP: `C:\\Users` | Bash: `/c/Users` or `C:/Users` -- **Context Package Paths**: Use project-relative paths (e.g., `src/auth/service.ts`, not absolute) +- **Context Package**: Use project-relative paths (e.g., `src/auth/service.ts`) diff --git a/.claude/commands/workflow/brainstorm/artifacts.md b/.claude/commands/workflow/brainstorm/artifacts.md index 9be148d3..ff284987 100644 --- a/.claude/commands/workflow/brainstorm/artifacts.md +++ b/.claude/commands/workflow/brainstorm/artifacts.md @@ -2,7 +2,7 @@ name: artifacts description: Interactive clarification generating confirmed guidance specification argument-hint: "topic or challenge description [--count N]" -allowed-tools: TodoWrite(*), Read(*), Write(*), AskUserQuestion(*), Glob(*) +allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*) --- ## Overview @@ -15,7 +15,7 @@ Five-phase workflow: Extract topic challenges → Select roles → Generate task **Parameters**: - `topic` (required): Topic or challenge description (structured format recommended) -- `--count N` (optional): Number of roles user WANTS to select (system will recommend N+2 options via AskUserQuestion for user to choose from, default: 3) +- `--count N` (optional): Number of roles user WANTS to select (system will recommend N+2 options for user to choose from, default: 3) ## Task Tracking @@ -33,29 +33,104 @@ Five-phase workflow: Extract topic challenges → Select roles → Generate task ```json [ {"content": "Initialize session (.workflow/.active-* check, parse --count parameter)", "status": "pending", "activeForm": "Initializing"}, - {"content": "Phase 1: Extract challenges, generate 2-4 task-specific questions", "status": "pending", "activeForm": "Phase 1 topic analysis"}, - {"content": "Phase 2: Recommend count+2 roles, MUST collect user selection via AskUserQuestion (multiSelect)", "status": "pending", "activeForm": "Phase 2 role selection"}, - {"content": "Phase 3: Generate 3-4 task-specific questions per role (max 4 per round)", "status": "pending", "activeForm": "Phase 3 role questions"}, - {"content": "Phase 4: Detect conflicts in Phase 3 answers, generate clarifications (max 4 per round)", "status": "pending", "activeForm": "Phase 4 conflict resolution"}, + {"content": "Phase 1: Extract challenges, output 2-4 task-specific questions, wait for user input", "status": "pending", "activeForm": "Phase 1 topic analysis"}, + {"content": "Phase 2: Recommend count+2 roles, output role selection, wait for user input", "status": "pending", "activeForm": "Phase 2 role selection"}, + {"content": "Phase 3: Generate 3-4 questions per role, output and wait for answers (max 10 per round)", "status": "pending", "activeForm": "Phase 3 role questions"}, + {"content": "Phase 4: Detect conflicts, output clarifications, wait for answers (max 10 per round)", "status": "pending", "activeForm": "Phase 4 conflict resolution"}, {"content": "Phase 5: Transform Q&A to declarative statements, write guidance-specification.md", "status": "pending", "activeForm": "Phase 5 document generation"} ] ``` +## User Interaction Protocol + +### Question Output Format + +All questions output as structured text (detailed format with descriptions): + +```markdown +【问题{N} - {短标签}】{问题文本} +a) {选项标签} + 说明:{选项说明和影响} +b) {选项标签} + 说明:{选项说明和影响} +c) {选项标签} + 说明:{选项说明和影响} + +请回答:{N}a 或 {N}b 或 {N}c +``` + +**Multi-select format** (Phase 2 role selection): +```markdown +【角色选择】请选择 {count} 个角色参与头脑风暴分析 + +a) {role-name} ({中文名}) + 推荐理由:{基于topic的相关性说明} +b) {role-name} ({中文名}) + 推荐理由:{基于topic的相关性说明} +... + +支持格式: +- 分别选择:2a 2c 2d (选择第2题的a、c、d选项) +- 合并语法:2acd (选择a、c、d) +- 逗号分隔:2a,c,d + +请输入选择: +``` + +### Input Parsing Rules + +**Supported formats** (intelligent parsing): + +1. **Space-separated**: `1a 2b 3c` → Q1:a, Q2:b, Q3:c +2. **Comma-separated**: `1a,2b,3c` → Q1:a, Q2:b, Q3:c +3. **Multi-select combined**: `2abc` → Q2: options a,b,c +4. **Multi-select spaces**: `2 a b c` → Q2: options a,b,c +5. **Multi-select comma**: `2a,b,c` → Q2: options a,b,c +6. **Natural language**: `问题1选a` → 1a (fallback parsing) + +**Parsing algorithm**: +- Extract question numbers and option letters +- Validate question numbers match output +- Validate option letters exist for each question +- If ambiguous/invalid, output example format and request re-input + +**Error handling** (lenient): +- Recognize common variations automatically +- If parsing fails, show example and wait for clarification +- Support re-input without penalty + +### Batching Strategy + +**Batch limits**: +- **Default**: Maximum 10 questions per round +- **Phase 2 (role selection)**: Display all recommended roles at once (count+2 roles) +- **Auto-split**: If questions > 10, split into multiple rounds with clear round indicators + +**Round indicators**: +```markdown +===== 第 1 轮问题 (共2轮) ===== +【问题1 - ...】... +【问题2 - ...】... +... +【问题10 - ...】... + +请回答 (格式: 1a 2b ... 10c): +``` + +### Interaction Flow + +**Standard flow**: +1. Output questions in formatted text +2. Output expected input format example +3. Wait for user input +4. Parse input with intelligent matching +5. If parsing succeeds → Store answers and continue +6. If parsing fails → Show error, example, and wait for re-input + +**No question/option limits**: Text-based interaction removes previous 4-question and 4-option restrictions + ## Execution Phases -### Phase 0: User Mode Check (First Step) - -**Output to user**: -``` -**⚠️ 请先启用 "CLAUDE accept edits on" 模式** - -本命令需要多轮交互问答(5个阶段,约10-15个问题) - -启用后回复继续。 -``` - -**Wait for user confirmation** before proceeding to Phase 1. - ### Session Management - Check `.workflow/.active-*` markers first - Multiple sessions → Prompt selection | Single → Use it | None → Create `WFS-[topic-slug]` @@ -69,20 +144,42 @@ Five-phase workflow: Extract topic challenges → Select roles → Generate task **Steps**: 1. **Deep topic analysis**: Extract technical entities, identify core challenges (what makes this hard?), constraints (timeline/budget/compliance), success metrics (what defines done?) 2. **Generate 2-4 probing questions** targeting root challenges, trade-off priorities, and risk tolerance (NOT surface-level "Project Type") -3. **User interaction via AskUserQuestion tool**: Present 2-4 task-specific questions (multiSelect: false for single-choice questions) -4. **Storage**: Store answers to `session.intent_context` with `{extracted_keywords, identified_challenges, user_answers}` +3. **User interaction**: Output questions using text format (see User Interaction Protocol), wait for user input +4. **Parse user answers**: Use intelligent parsing to extract answers from user input (support multiple formats) +5. **Storage**: Store answers to `session.intent_context` with `{extracted_keywords, identified_challenges, user_answers}` -**Example (Task-Specific)**: -Topic: "Build real-time collaboration platform SCOPE: 100 users" -→ Extract: ["real-time", "collaboration", "100 users"] -→ Challenges: ["data sync", "scalability", "low latency"] -→ Generate: "PRIMARY technical challenge?" → [Real-time data sync / Scalability to 100+ users / Conflict resolution] +**Example Output**: +```markdown +===== Phase 1: 项目意图分析 ===== + +【问题1 - 核心挑战】实时协作平台的主要技术挑战? +a) 实时数据同步 + 说明:100+用户同时在线,状态同步复杂度高 +b) 可扩展性架构 + 说明:用户规模增长时的系统扩展能力 +c) 冲突解决机制 + 说明:多用户同时编辑的冲突处理策略 + +【问题2 - 优先级】MVP阶段最关注的指标? +a) 功能完整性 + 说明:实现所有核心功能 +b) 用户体验 + 说明:流畅的交互体验和响应速度 +c) 系统稳定性 + 说明:高可用性和数据一致性 + +请回答 (格式: 1a 2b): +``` + +**User input examples**: +- `1a 2c` → Q1:a, Q2:c +- `1a,2c` → Q1:a, Q2:c **⚠️ CRITICAL**: Questions MUST reference topic keywords. Generic "Project type?" violates dynamic generation. ### Phase 2: Role Selection -**⚠️ CRITICAL**: This phase MUST use AskUserQuestion tool for user selection. NEVER auto-select roles without user interaction. +**⚠️ CRITICAL**: User MUST interact to select roles. NEVER auto-select without user confirmation. **Available Roles**: - data-architect (数据架构师) @@ -96,35 +193,49 @@ Topic: "Build real-time collaboration platform SCOPE: 100 users" - ux-expert (UX 专家) **Steps**: -1. **Intelligent role recommendation** (AI analysis, NO user interaction yet): +1. **Intelligent role recommendation** (AI analysis): - Analyze Phase 1 extracted keywords and challenges - Use AI reasoning to determine most relevant roles for the specific topic - Recommend count+2 roles (e.g., if user wants 3 roles, recommend 5 options) - Provide clear rationale for each recommended role based on topic context -2. **User selection** (MANDATORY AskUserQuestion interaction): - - **Tool**: `AskUserQuestion` with `multiSelect: true` - - **Question format**: "请选择 {count} 个角色参与头脑风暴分析(可多选):" - - **Options**: Each recommended role with label (role name) and description (relevance rationale) - - **⚠️ Option Limit**: Maximum 4 options per AskUserQuestion call. If count+2 > 4, split into multiple rounds - - **User interaction**: Allow user to select multiple roles (typically count roles, but flexible) +2. **User selection** (text interaction): + - Output all recommended roles at once (no batching needed for count+2 roles) + - Display roles with labels and relevance rationale + - Wait for user input in multi-select format + - Parse user input (support multiple formats) - **Storage**: Store selections to `session.selected_roles` -**AskUserQuestion Syntax**: -```javascript -AskUserQuestion({ - questions: [{ - question: "请选择 {count} 个角色参与头脑风暴分析(可多选):", - header: "角色选择", - multiSelect: true, // Enable multiple selection - options: [ - {label: "{role-name} ({中文名})", description: "{基于topic的相关性说明}"} - // count+2 recommended roles - ] - }] -}); +**Example Output**: +```markdown +===== Phase 2: 角色选择 ===== + +【角色选择】请选择 3 个角色参与头脑风暴分析 + +a) system-architect (系统架构师) + 推荐理由:实时同步架构设计和技术选型的核心角色 +b) ui-designer (UI设计师) + 推荐理由:协作界面用户体验和实时状态展示 +c) product-manager (产品经理) + 推荐理由:功能优先级和MVP范围决策 +d) data-architect (数据架构师) + 推荐理由:数据同步模型和存储方案设计 +e) ux-expert (UX专家) + 推荐理由:多用户协作交互流程优化 + +支持格式: +- 分别选择:2a 2c 2d (选择a、c、d) +- 合并语法:2acd (选择a、c、d) +- 逗号分隔:2a,c,d (选择a、c、d) + +请输入选择: ``` +**User input examples**: +- `2acd` → Roles: a, c, d (system-architect, product-manager, data-architect) +- `2a 2c 2d` → Same result +- `2a,c,d` → Same result + **Role Recommendation Rules**: - NO hardcoded keyword-to-role mappings - Use intelligent analysis of topic, challenges, and requirements @@ -149,39 +260,28 @@ FOR each selected role: Q: "How resolve conflicts when 2 users edit simultaneously?" (explores edge case) Options: [Event Sourcing/Centralized/CRDT] (concrete, explain trade-offs for THIS use case) - 3. Ask questions via AskUserQuestion tool (max 4 questions per call): - - Tool: AskUserQuestion with questions array (1-4 questions) - - Each question: multiSelect: false (single-choice) - - If role has 3-4 questions: Single AskUserQuestion call with multiple questions + 3. Output questions in text format per role: + - Display all questions for current role (3-4 questions, no 10-question limit) + - Questions in Chinese (用中文提问) + - Wait for user input + - Parse answers using intelligent parsing - Store answers to session.role_decisions[role] ``` -**AskUserQuestion Tool Usage**: -- **Batching**: Maximum 4 questions per AskUserQuestion call -- **Mode**: `multiSelect: false` for each question (single-choice answers) -- **Language**: Questions MUST be asked in Chinese (用中文提问) -- **Format**: Each question includes header (short label), question text, and 2-4 options with descriptions +**Batching Strategy**: +- Each role outputs all its questions at once (typically 3-4 questions) +- No need to split per role (within 10-question batch limit) +- Multiple roles processed sequentially (one role at a time for clarity) -**Question Batching Rules**: -- ✅ Each role generates 3-4 questions -- ✅ AskUserQuestion supports maximum 4 questions per call -- ✅ Single round per role (all questions asked together) -- ✅ Questions MUST be asked in Chinese (用中文提问) for better user understanding -- ✅ Questions MUST reference Phase 1 keywords (e.g., "real-time", "100 users") -- ✅ Options MUST be concrete approaches, explain relevance to topic -- ❌ NEVER generic "Architecture style?" without task context +**Output Format**: Follow standard format from "User Interaction Protocol" section (single-choice question format) -**Examples by Role** (for "real-time collaboration platform"): -- **system-architect** (4 questions in one round): - 1. "100+ 用户实时状态同步方案?" → [Event Sourcing/集中式状态/CRDT] - 2. "两个用户同时编辑冲突如何解决?" → [自动合并/手动解决/版本控制] - 3. "低延迟通信协议选择?" → [WebSocket/SSE/轮询] - 4. "系统扩展性架构方案?" → [微服务/单体+缓存/Serverless] +**Example Topic-Specific Questions** (system-architect role for "real-time collaboration platform"): +- "100+ 用户实时状态同步方案?" → Options: Event Sourcing / 集中式状态管理 / CRDT +- "两个用户同时编辑冲突如何解决?" → Options: 自动合并 / 手动解决 / 版本控制 +- "低延迟通信协议选择?" → Options: WebSocket / SSE / 轮询 +- "系统扩展性架构方案?" → Options: 微服务 / 单体+缓存 / Serverless -- **ui-designer** (3 questions in one round): - 1. "如何展示实时协作状态?" → [实时光标/活动流/最小化指示器] - 2. "冲突时的用户界面反馈?" → [即时警告/合并界面/回滚选项] - 3. "多用户在线状态展示?" → [头像列表/活动面板/状态栏] +**Quality Requirements**: See "Question Generation Guidelines" section for detailed rules ### Phase 4: Cross-Role Clarification (Conflict Detection) @@ -197,33 +297,33 @@ FOR each selected role: 2. FOR each detected conflict: Generate clarification questions referencing SPECIFIC Phase 3 choices -3. Ask via AskUserQuestion tool in batches (max 4 questions per call): - - Tool: AskUserQuestion with questions array (1-4 questions) - - Each question: multiSelect: false (single-choice) - - If conflicts ≤ 4: Single AskUserQuestion call - - If conflicts > 4: Multiple AskUserQuestion calls (max 4 questions each) +3. Output clarification questions in text format: + - Batch conflicts into rounds (max 10 questions per round) + - Display questions with context from Phase 3 answers + - Questions in Chinese (用中文提问) + - Wait for user input + - Parse answers using intelligent parsing - Store answers to session.cross_role_decisions -4. If NO conflicts: Skip Phase 4 (inform user) +4. If NO conflicts: Skip Phase 4 (inform user: "未检测到跨角色冲突,跳过Phase 4") ``` -**AskUserQuestion Tool Usage**: -- **Batching**: Maximum 4 questions per AskUserQuestion call -- **Mode**: `multiSelect: false` for each question (single-choice answers) -- **Language**: Questions in Chinese (用中文提问) -- **Multiple rounds**: If conflicts > 4, call AskUserQuestion multiple times sequentially +**Batching Strategy**: +- Maximum 10 clarification questions per round +- If conflicts > 10, split into multiple rounds +- Prioritize most critical conflicts first -**Batching Rules**: -- ✅ Maximum 4 clarification questions per AskUserQuestion call -- ✅ Multiple rounds if more than 4 conflicts detected -- ✅ Prioritize most critical conflicts first -- ✅ Questions in Chinese (用中文提问) +**Output Format**: Follow standard format from "User Interaction Protocol" section (single-choice question format with background context) -**Example Conflict**: -- Detect: system-architect "CRDT sync" (conflict-free) + ui-designer "Rollback on conflict" (expects conflicts) -- Generate: "CRDT 与 UI 回滚期望冲突,如何解决?" → [CRDT 自动合并/显示合并界面/切换到 OT] +**Example Conflict Detection** (from Phase 3 answers): +- **Architecture Conflict**: "CRDT 与 UI 回滚期望冲突,如何解决?" + - Background: system-architect chose CRDT, ui-designer expects rollback UI + - Options: 采用 CRDT / 显示合并界面 / 切换到 OT +- **Integration Gap**: "实时光标功能缺少身份认证方案" + - Background: ui-designer chose live cursors, no auth defined + - Options: OAuth 2.0 / JWT Token / Session-based -**⚠️ CRITICAL**: NEVER use static "Cross-Role Matrix". ALWAYS analyze actual Phase 3 answers. +**Quality Requirements**: See "Question Generation Guidelines" section for conflict-specific rules ### Phase 5: Generate Guidance Specification @@ -288,35 +388,6 @@ FOR each selected role: | D-003+ | [Role] | [Q] | [A] | 3 | [Why] | ``` -## AskUserQuestion Tool Reference - -### Syntax Structure -```javascript -AskUserQuestion({ - questions: [ - { - question: "{动态生成的问题文本}", - header: "{短标签,最多12字符}", - multiSelect: false, // Phase 1,3,4: false | Phase 2: true - options: [ - {label: "{选项标签}", description: "{选项说明}"}, - // 2-4 options per question - ] - } - // Maximum 4 questions per call - ] -}); -``` - -### Usage Rules -- **Maximum**: 4 questions per AskUserQuestion call -- **Language**: Questions in Chinese (用中文提问) -- **multiSelect**: - - `false` (Phase 1, 3, 4): Single-choice - - `true` (Phase 2): Multiple role selection -- **Options**: 2-4 options with label + description -- **Multiple rounds**: Call tool multiple times if > 4 questions needed - ## Question Generation Guidelines ### Core Principle: Developer-Facing Questions with User Context @@ -329,49 +400,50 @@ AskUserQuestion({ 3. **Phase 3**: 业务需求 + 技术选型(需求驱动的技术决策) 4. **Phase 4**: 技术冲突的业务权衡(帮助开发者理解影响) -### Question Quality Rules +### Universal Quality Rules -**Balanced Question Pattern** (需求 → 技术): -``` -问题结构:[用户场景/业务需求] + [技术关注点] -选项格式:[技术方案简称] + [业务影响说明] -``` - -**Phase 1 Focus**: -- 用户使用场景(谁用?怎么用?多频繁?) -- 业务约束(预算、时间、团队、合规) -- 成功标准(性能指标、用户体验目标) -- 优先级排序(MVP vs 长期规划) - -**Phase 3 Focus**: -- 业务需求驱动的技术问题 -- 技术选项带业务影响说明 -- 包含量化指标(并发数、延迟、可用性) - -**Phase 4 Focus**: -- 技术冲突的业务权衡 -- 帮助开发者理解不同选择的影响 - -**Question Structure**: +**Question Structure** (all phases): ``` [业务场景/需求前提] + [技术关注点] ``` -**Option Structure**: +**Option Structure** (all phases): ``` 标签:[技术方案简称] + (业务特征) 说明:[业务影响] + [技术权衡] ``` -**MUST Include**: -- 业务场景作为问题前提 -- 技术选项的业务影响说明 -- 量化指标和约束条件 +**MUST Include** (all phases): +- ✅ All questions in Chinese (用中文提问) +- ✅ 业务场景作为问题前提 +- ✅ 技术选项的业务影响说明 +- ✅ 量化指标和约束条件 -**MUST Avoid**: -- 纯技术选型无业务上下文 -- 过度抽象的用户体验问题 -- 脱离话题的通用架构问题 +**MUST Avoid** (all phases): +- ❌ 纯技术选型无业务上下文 +- ❌ 过度抽象的用户体验问题 +- ❌ 脱离话题的通用架构问题 + +### Phase-Specific Requirements + +**Phase 1 Requirements**: +- Questions MUST reference topic keywords (NOT generic "Project type?") +- Focus: 用户使用场景(谁用?怎么用?多频繁?)、业务约束(预算、时间、团队、合规) +- Success metrics: 性能指标、用户体验目标 +- Priority ranking: MVP vs 长期规划 + +**Phase 3 Requirements**: +- Questions MUST reference Phase 1 keywords (e.g., "real-time", "100 users") +- Options MUST be concrete approaches with relevance to topic +- Each option includes trade-offs specific to this use case +- Include 业务需求驱动的技术问题、量化指标(并发数、延迟、可用性) + +**Phase 4 Requirements**: +- Questions MUST reference SPECIFIC Phase 3 choices in background context +- Options address the detected conflict directly +- Each option explains impact on both conflicting roles +- NEVER use static "Cross-Role Matrix" - ALWAYS analyze actual Phase 3 answers +- Focus: 技术冲突的业务权衡、帮助开发者理解不同选择的影响 ## Validation Checklist diff --git a/.claude/commands/workflow/brainstorm/synthesis.md b/.claude/commands/workflow/brainstorm/synthesis.md index f618bd08..5f15f2c0 100644 --- a/.claude/commands/workflow/brainstorm/synthesis.md +++ b/.claude/commands/workflow/brainstorm/synthesis.md @@ -2,7 +2,7 @@ name: synthesis description: Clarify and refine role analyses through intelligent Q&A and targeted updates argument-hint: "[optional: --session session-id]" -allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), AskUserQuestion(*) +allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*) --- ## Overview @@ -137,54 +137,67 @@ Return JSON array: ### Phase 4: Main Flow User Interaction -**Main flow handles all user interaction**: +**Main flow handles all user interaction via text output**: -**⚠️ CRITICAL**: ALL AskUserQuestion calls MUST use Chinese (所有问题必须用中文) for better user understanding +**⚠️ CRITICAL**: ALL questions MUST use Chinese (所有问题必须用中文) for better user understanding -1. **Present Enhancement Options**: -``` -AskUserQuestion( - questions=[{ - "question": "Which enhancements would you like to apply?", - "header": "Enhancements", - "multiSelect": true, - "options": [ - {"label": "EP-001: ...", "description": "... (affects: role1, role2)"}, - {"label": "EP-002: ...", "description": "..."}, - ... - ] - }] -) +1. **Present Enhancement Options** (multi-select): +```markdown +===== Enhancement 选择 ===== + +请选择要应用的改进建议(可多选): + +a) EP-001: API Contract Specification + 影响角色:system-architect, api-designer + 说明:添加详细的请求/响应 schema 定义 + +b) EP-002: User Intent Validation + 影响角色:product-manager, ux-expert + 说明:明确用户需求优先级和验收标准 + +c) EP-003: Error Handling Strategy + 影响角色:system-architect + 说明:统一异常处理和降级方案 + +支持格式:1abc 或 1a 1b 1c 或 1a,b,c +请输入选择(可跳过输入 skip): ``` 2. **Generate Clarification Questions** (based on analysis agent output): - - ✅ **ALL questions MUST be in Chinese (所有问题必须用中文)** + - ✅ **ALL questions in Chinese (所有问题必须用中文)** - Use 9-category taxonomy scan results - - Create max 5 prioritized questions + - Prioritize most critical questions (no hard limit) - Each with 2-4 options + descriptions -3. **Interactive Clarification Loop**: -``` -# Present ONE question at a time -FOR question in clarification_questions (max 5): - AskUserQuestion( - questions=[{ - "question": "Question {N}/5: {text}", - "header": "Clarification", - "multiSelect": false, - "options": [ - {"label": "Option A", "description": "..."}, - {"label": "Option B", "description": "..."}, - ... - ] - }] - ) - # Record answer - # Continue to next question +3. **Interactive Clarification Loop** (max 10 questions per round): +```markdown +===== Clarification 问题 (第 1/2 轮) ===== + +【问题1 - 用户意图】MVP 阶段的核心目标是什么? +a) 快速验证市场需求 + 说明:最小功能集,快速上线获取反馈 +b) 建立技术壁垒 + 说明:完善架构,为长期发展打基础 +c) 实现功能完整性 + 说明:覆盖所有规划功能,延迟上线 + +【问题2 - 架构决策】技术栈选择的优先考虑因素? +a) 团队熟悉度 + 说明:使用现有技术栈,降低学习成本 +b) 技术先进性 + 说明:采用新技术,提升竞争力 +c) 生态成熟度 + 说明:选择成熟方案,保证稳定性 + +...(最多10个问题) + +请回答 (格式: 1a 2b 3c...): ``` +Wait for user input → Parse all answers in batch → Continue to next round if needed + 4. **Build Update Plan**: -``` +``` update_plan = { "role1": { "enhancements": [EP-001, EP-003], diff --git a/.claude/commands/workflow/tools/conflict-resolution.md b/.claude/commands/workflow/tools/conflict-resolution.md index c844ffd7..d3245bf3 100644 --- a/.claude/commands/workflow/tools/conflict-resolution.md +++ b/.claude/commands/workflow/tools/conflict-resolution.md @@ -207,48 +207,85 @@ Task(subagent_type="cli-execution-agent", prompt=` 8. Return execution log path ``` -### Phase 3: User Confirmation via AskUserQuestion +### Phase 3: User Confirmation via Text Interaction -**Command parses agent JSON output and presents conflicts to user**: +**Command parses agent JSON output and presents conflicts to user via text**: ```javascript // 1. Parse agent JSON output const conflictData = JSON.parse(agentOutput); -const conflicts = conflictData.conflicts.slice(0, 4); // Max 4 (tool limit) +const conflicts = conflictData.conflicts; // No 4-conflict limit -// 2. Build AskUserQuestion with all conflicts -const questions = conflicts.map((conflict, idx) => ({ - question: `${conflict.id}: ${conflict.brief} - 请选择解决方案`, - header: `冲突${idx + 1}`, - multiSelect: false, - options: [ - ...conflict.strategies.map(s => ({ - label: s.name, - description: `${s.approach} | 复杂度: ${s.complexity} | 风险: ${s.risk} | 工作量: ${s.effort}` - })), - { - label: "跳过此冲突", - description: "稍后手动处理,不应用任何修改" - } - ] -})); +// 2. Format conflicts as text output (max 10 per round) +const batchSize = 10; +const batches = chunkArray(conflicts, batchSize); -// 3. Call AskUserQuestion -AskUserQuestion({questions}); +for (const [batchIdx, batch] of batches.entries()) { + const totalBatches = batches.length; -// 4. Parse user selections -const selectedStrategies = parseUserAnswers(answers, conflicts); + // Output batch header + console.log(`===== 冲突解决 (第 ${batchIdx + 1}/${totalBatches} 轮) =====\n`); + + // Output each conflict in batch + batch.forEach((conflict, idx) => { + const questionNum = batchIdx * batchSize + idx + 1; + console.log(`【问题${questionNum} - ${conflict.category}】${conflict.id}: ${conflict.brief}`); + + conflict.strategies.forEach((strategy, sIdx) => { + const optionLetter = String.fromCharCode(97 + sIdx); // a, b, c, ... + console.log(`${optionLetter}) ${strategy.name}`); + console.log(` 说明:${strategy.approach}`); + console.log(` 复杂度: ${strategy.complexity} | 风险: ${strategy.risk} | 工作量: ${strategy.effort}`); + }); + + // Add skip option + const skipLetter = String.fromCharCode(97 + conflict.strategies.length); + console.log(`${skipLetter}) 跳过此冲突`); + console.log(` 说明:稍后手动处理,不应用任何修改\n`); + }); + + console.log(`请回答 (格式: 1a 2b 3c...):`); + + // Wait for user input + const userInput = await readUserInput(); + + // Parse answers + const answers = parseUserAnswers(userInput, batch); +} + +// 3. Build selected strategies +const selectedStrategies = answers.filter(a => !a.isSkip).map(a => a.strategy); ``` -**User Selection Examples**: -``` -Question: "CON-001: 现有认证系统与计划不兼容 - 请选择解决方案" -Options: - - "渐进式迁移" | 复杂度: Medium | 风险: Low | 工作量: 3-5天 - - "完全重写" | 复杂度: High | 风险: Medium | 工作量: 7-10天 - - "跳过此冲突" +**Text Output Example**: +```markdown +===== 冲突解决 (第 1/1 轮) ===== + +【问题1 - 认证系统】CON-001: 现有认证系统与计划不兼容 +a) 渐进式迁移 + 说明:保留现有系统,逐步迁移到新方案 + 复杂度: Medium | 风险: Low | 工作量: 3-5天 +b) 完全重写 + 说明:废弃旧系统,从零实现新认证 + 复杂度: High | 风险: Medium | 工作量: 7-10天 +c) 跳过此冲突 + 说明:稍后手动处理,不应用任何修改 + +【问题2 - 数据库】CON-002: 数据库 schema 冲突 +a) 添加迁移脚本 + 说明:创建数据库迁移脚本处理 schema 变更 + 复杂度: Low | 风险: Low | 工作量: 1-2天 +b) 跳过此冲突 + 说明:稍后手动处理,不应用任何修改 + +请回答 (格式: 1a 2b): ``` +**User Input Examples**: +- `1a 2a` → Conflict 1: 渐进式迁移, Conflict 2: 添加迁移脚本 +- `1b 2b` → Conflict 1: 完全重写, Conflict 2: 跳过 +- `1c 2c` → Both skipped + ### Phase 4: Apply Modifications ```javascript @@ -290,7 +327,7 @@ return { **Validation**: ``` ✓ Agent returns valid JSON structure -✓ AskUserQuestion displays all conflicts (max 4) +✓ Text output displays all conflicts (max 10 per round) ✓ User selections captured correctly ✓ Edit tool successfully applies modifications ✓ guidance-specification.md updated @@ -310,7 +347,7 @@ return { ### Key Requirements | Requirement | Details | |------------|---------| -| **Conflict limit** | Max 4 conflicts (AskUserQuestion tool limit) | +| **Conflict batching** | Max 10 conflicts per round (no total limit) | | **Strategy count** | 2-4 strategies per conflict | | **Modifications** | Each strategy includes file paths, old_content, new_content | | **User-facing text** | Chinese (brief, strategy names, pros/cons) | @@ -338,7 +375,7 @@ return { ``` If Edit tool fails mid-application: 1. Log all successfully applied modifications -2. Offer rollback option via AskUserQuestion +2. Output rollback option via text interaction 3. If rollback selected: restore files from git or backups 4. If continue: mark partial resolution in context-package.json ``` @@ -359,15 +396,15 @@ If Edit tool fails mid-application: - NO report file generation **User Interaction**: -- AskUserQuestion for strategy selection (max 4 conflicts) +- Text-based strategy selection (max 10 conflicts per round) - Each conflict: 2-4 strategy options + "跳过" option ### Success Criteria ``` ✓ CLI analysis returns valid JSON structure -✓ Max 4 conflicts presented (tool limit) +✓ Conflicts presented in batches (max 10 per round) ✓ Min 2 strategies per conflict with modifications -✓ AskUserQuestion displays all conflicts correctly +✓ Text output displays all conflicts correctly ✓ User selections captured and processed ✓ Edit tool applies modifications successfully ✓ guidance-specification.md updated with resolved conflicts diff --git a/.claude/commands/workflow/tools/task-generate-agent.md b/.claude/commands/workflow/tools/task-generate-agent.md index e5b04c81..b32636d5 100644 --- a/.claude/commands/workflow/tools/task-generate-agent.md +++ b/.claude/commands/workflow/tools/task-generate-agent.md @@ -49,6 +49,7 @@ Autonomous task JSON and IMPL_PLAN.md generation using action-planning-agent wit "synthesis_output": {"path": "...", "exists": true}, "conflict_resolution": {"path": "...", "exists": true} // if conflict_risk >= medium }, + "context_package_path": ".workflow/{session-id}/.process/context-package.json", "context_package": { // If in memory: use cached content // Else: Load from .workflow/{session-id}/.process/context-package.json @@ -336,9 +337,11 @@ const agentContext = { ? memory.get("workflow-session.json") : Read(.workflow/WFS-[id]/workflow-session.json), + context_package_path: ".workflow/WFS-[id]/.process/context-package.json", + context_package: memory.has("context-package.json") ? memory.get("context-package.json") - : Read(.workflow/WFS-[id]/.process/context-package.json), + : Read(".workflow/WFS-[id]/.process/context-package.json"), // Extract brainstorm artifacts from context package brainstorm_artifacts: extractBrainstormArtifacts(context_package), diff --git a/.claude/commands/workflow/tools/task-generate-tdd.md b/.claude/commands/workflow/tools/task-generate-tdd.md index 4f6faeed..f04b4ea7 100644 --- a/.claude/commands/workflow/tools/task-generate-tdd.md +++ b/.claude/commands/workflow/tools/task-generate-tdd.md @@ -134,6 +134,7 @@ For each feature, generate task(s) with ID format: "id": "IMPL-N", // Task identifier "title": "Feature description with TDD", // Human-readable title "status": "pending", // pending | in_progress | completed | container + "context_package_path": ".workflow/{session-id}/.process/context-package.json", // Path to smart context package "meta": { "type": "feature", // Task type "agent": "@code-developer", // Assigned agent @@ -259,6 +260,7 @@ identifier: WFS-{session-id} source: "User requirements" | "File: path" conflict_resolution: .workflow/{session-id}/.process/CONFLICT_RESOLUTION.md # if exists context_package: .workflow/{session-id}/.process/context-package.json +context_package_path: .workflow/{session-id}/.process/context-package.json test_context: .workflow/{session-id}/.process/test-context-package.json # if exists workflow_type: "tdd" verification_history: @@ -411,6 +413,7 @@ Update workflow-session.json with TDD metadata: ├── CONFLICT_RESOLUTION.md # Conflict resolution strategies (if conflict_risk ≥ medium) ├── test-context-package.json # Test coverage analysis ├── context-package.json # Input from context-gather + ├── context_package_path # Path to smart context package └── green-fix-iteration-*.md # Fix logs from Green phase test-fix cycles ``` diff --git a/.claude/commands/workflow/tools/task-generate.md b/.claude/commands/workflow/tools/task-generate.md index 1af3904e..3d6fd62c 100644 --- a/.claude/commands/workflow/tools/task-generate.md +++ b/.claude/commands/workflow/tools/task-generate.md @@ -173,6 +173,7 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut "id": "IMPL-N[.M]", "title": "Descriptive task name", "status": "pending|active|completed|blocked|container", + "context_package_path": ".workflow/WFS-[session]/.process/context-package.json", "meta": { "type": "feature|bugfix|refactor|test-gen|test-fix|docs", "agent": "@code-developer|@test-fix-agent|@universal-executor", @@ -193,11 +194,6 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut "priority": "highest", "usage": "Role-specific requirements, design specs, enhanced by synthesis. Paths loaded dynamically from context-package.json (supports multiple files per role: analysis.md, analysis-01.md, analysis-api.md, etc.). Common roles: product-manager, system-architect, ui-designer, data-architect, ux-expert." }, - { - "path": ".workflow/WFS-[session]/.process/context-package.json", - "priority": "critical", - "usage": "Smart context with focus paths, module structure, dependency graph, existing patterns, tech stack. Use for: environment setup, dependency resolution, pattern discovery, conflict detection results" - }, { "path": ".workflow/WFS-[session]/.brainstorming/guidance-specification.md", "priority": "high", @@ -210,8 +206,9 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut { "step": "load_context_package", "action": "Load context package for artifact paths", + "note": "Context package path is now at top-level field: context_package_path", "commands": [ - "Read(.workflow/WFS-[session]/.process/context-package.json)" + "Read({{context_package_path}})" ], "output_to": "context_package", "on_error": "fail" @@ -221,7 +218,7 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut "action": "Load role analyses from context-package.json (supports multiple files per role)", "note": "Paths loaded from context-package.json → brainstorm_artifacts.role_analyses[]. Supports analysis*.md automatically.", "commands": [ - "Read(.workflow/WFS-[session]/.process/context-package.json)", + "Read({{context_package_path}})", "Extract(brainstorm_artifacts.role_analyses[].files[].path)", "Read(each extracted path)" ], @@ -231,9 +228,9 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut { "step": "load_planning_context", "action": "Load plan-generated context intelligence with resolved conflicts", - "note": "CRITICAL: context-package.json provides smart context (focus paths, dependencies, patterns) and conflict resolution status. If conflict_risk was medium/high, conflicts have been resolved in guidance-specification.md and role analyses.", + "note": "CRITICAL: context-package.json (from context_package_path) provides smart context (focus paths, dependencies, patterns) and conflict resolution status. If conflict_risk was medium/high, conflicts have been resolved in guidance-specification.md and role analyses.", "commands": [ - "Read(.workflow/WFS-[session]/.process/context-package.json)", + "Read({{context_package_path}})", "Read(.workflow/WFS-[session]/.brainstorming/guidance-specification.md)" ], "output_to": "planning_context", @@ -403,7 +400,7 @@ Role analyses provide specialized perspectives on the implementation: - **topic-framework.md**: Role-specific discussion points and analysis framework **Artifact Priority in Development**: -1. context-package.json (primary source: smart context AND brainstorm artifact catalog in `brainstorm_artifacts` + conflict_risk status) +1. {context_package_path} (primary source: smart context AND brainstorm artifact catalog in `brainstorm_artifacts` + conflict_risk status) 2. role/analysis*.md (paths from context-package.json: requirements, design specs, enhanced by synthesis, with resolved conflicts if any) 3. guidance-specification.md (path from context-package.json: finalized decisions with resolved conflicts if any) @@ -592,8 +589,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c **Key Points**: - **Sequential Steps**: Steps execute in order defined in `implementation_approach` array -- **Context Delivery**: Each codex command receives context via CONTEXT field: `@.workflow/WFS-session/.process/context-package.json` (role analyses loaded dynamically from context package) -- **Multi-Step Tasks**: First step provides full context, subsequent steps use `resume --last` to maintain session continuity + - **Context Delivery**: Each codex command receives context via CONTEXT field: `@{context_package_path}` (role analyses loaded dynamically from context package)- **Multi-Step Tasks**: First step provides full context, subsequent steps use `resume --last` to maintain session continuity - **Step Dependencies**: Later steps reference outputs from earlier steps via `depends_on` field ### Example 1: Agent Mode - Simple Task (Default, No Command) @@ -601,6 +597,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c { "id": "IMPL-001", "title": "Implement user authentication module", + "context_package_path": ".workflow/WFS-session/.process/context-package.json", "context": { "depends_on": [], "focus_paths": ["src/auth"], @@ -617,7 +614,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c "step": "load_role_analyses", "action": "Load role analyses from context-package.json", "commands": [ - "Read(.workflow/WFS-session/.process/context-package.json)", + "Read({{context_package_path}})", "Extract(brainstorm_artifacts.role_analyses[].files[].path)", "Read(each extracted path)" ], @@ -627,7 +624,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c { "step": "load_context", "action": "Load context package for project structure", - "commands": ["Read(.workflow/WFS-session/.process/context-package.json)"], + "commands": ["Read({{context_package_path}})"], "output_to": "context_pkg", "on_error": "fail" } @@ -662,6 +659,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c { "id": "IMPL-002", "title": "Implement user authentication module", + "context_package_path": ".workflow/WFS-session/.process/context-package.json", "context": { "depends_on": [], "focus_paths": ["src/auth"], @@ -674,7 +672,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c "step": "load_role_analyses", "action": "Load role analyses from context-package.json", "commands": [ - "Read(.workflow/WFS-session/.process/context-package.json)", + "Read({{context_package_path}})", "Extract(brainstorm_artifacts.role_analyses[].files[].path)", "Read(each extracted path)" ], @@ -687,7 +685,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c "step": 1, "title": "Implement authentication with Codex", "description": "Create JWT-based authentication module", - "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Implement user authentication TASK: JWT-based auth with login/registration MODE: auto CONTEXT: @.workflow/WFS-session/.process/context-package.json EXPECTED: Complete auth module with tests RULES: Load role analyses from context-package.json → brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", + "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Implement user authentication TASK: JWT-based auth with login/registration MODE: auto CONTEXT: @{{context_package_path}} EXPECTED: Complete auth module with tests RULES: Load role analyses from context-package.json → brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", "modification_points": ["Create auth service", "Implement endpoints", "Add JWT middleware"], "logic_flow": ["Validate credentials", "Generate JWT", "Return token"], "depends_on": [], @@ -704,6 +702,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c { "id": "IMPL-003", "title": "Implement role-based access control", + "context_package_path": ".workflow/WFS-session/.process/context-package.json", "context": { "depends_on": ["IMPL-002"], "focus_paths": ["src/auth", "src/middleware"], @@ -716,7 +715,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c "step": "load_context", "action": "Load context and role analyses from context-package.json", "commands": [ - "Read(.workflow/WFS-session/.process/context-package.json)", + "Read({{context_package_path}})", "Extract(brainstorm_artifacts.role_analyses[].files[].path)", "Read(each extracted path)" ], @@ -729,7 +728,7 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c "step": 1, "title": "Create RBAC models", "description": "Define role and permission data models", - "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Create RBAC models TASK: Role and permission models MODE: auto CONTEXT: @.workflow/WFS-session/.process/context-package.json EXPECTED: Models with migrations RULES: Load role analyses from context-package.json → brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", + "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Create RBAC models TASK: Role and permission models MODE: auto CONTEXT: @{{context_package_path}} EXPECTED: Models with migrations RULES: Load role analyses from context-package.json → brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", "modification_points": ["Define role model", "Define permission model", "Create migrations"], "logic_flow": ["Design schema", "Implement models", "Generate migrations"], "depends_on": [], diff --git a/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt b/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt index 7cb85617..11d5755c 100644 --- a/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt +++ b/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt @@ -7,6 +7,7 @@ Task JSON Schema - Agent Mode (No Command Field) "id": "IMPL-N[.M]", "title": "Descriptive task name", "status": "pending", + "context_package_path": "{context_package_path}", "meta": { "type": "feature|bugfix|refactor|test|docs", "agent": "@code-developer|@test-fix-agent|@universal-executor" diff --git a/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt b/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt index b08a6bdc..f38f85cc 100644 --- a/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt +++ b/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt @@ -7,6 +7,7 @@ Task JSON Schema - CLI Execute Mode (With Command Field) "id": "IMPL-N[.M]", "title": "Descriptive task name", "status": "pending", + "context_package_path": "{context_package_path}", "meta": { "type": "feature|bugfix|refactor|test|docs", "agent": "@code-developer|@test-fix-agent|@universal-executor"