mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-05 01:50:27 +08:00
refactor(cli): change from env var injection to direct prompt concatenation
- Replace $PROTO/$TMPL environment variable injection with systemRules/roles direct concatenation - Append rules to END of prompt instead of prepending - Change prompt field name from RULES to CONSTRAINTS in all prompts - Default to universal-rigorous-style template when --rule not specified - Update all .claude documentation, agents, commands, and skills - Add streaming_content type support for Gemini delta messages Breaking: Prompts now use CONSTRAINTS field instead of RULES
This commit is contained in:
@@ -215,7 +215,7 @@ CONTEXT: @**/* | Memory: {ace_context_summary}
|
||||
|
||||
EXPECTED: JSON with feasibility_score, findings, implementation_approaches, technical_concerns, code_locations
|
||||
|
||||
RULES: $PROTO |
|
||||
CONSTRAINTS:
|
||||
- Specific file:line references
|
||||
- Quantify effort estimates
|
||||
- Concrete pros/cons
|
||||
|
||||
@@ -114,10 +114,10 @@ plan → planning/architecture-planning.txt | planning/task-breakdown.txt
|
||||
bug-fix → development/bug-diagnosis.txt
|
||||
```
|
||||
|
||||
**3. RULES Field**:
|
||||
- Use `--rule <template>` option to auto-load protocol + template as `$PROTO` and `$TMPL`
|
||||
**3. CONSTRAINTS Field**:
|
||||
- Use `--rule <template>` option to auto-load protocol + template (appended to prompt)
|
||||
- Template names: `category-function` format (e.g., `analysis-code-patterns`, `development-feature`)
|
||||
- NEVER escape: `\$`, `\"`, `\'` breaks variable expansion
|
||||
- NEVER escape: `\"`, `\'` breaks shell parsing
|
||||
|
||||
**4. Structured Prompt**:
|
||||
```bash
|
||||
@@ -126,7 +126,7 @@ TASK: {specific_task_with_details}
|
||||
MODE: {analysis|write|auto}
|
||||
CONTEXT: {structured_file_references}
|
||||
EXPECTED: {clear_output_expectations}
|
||||
RULES: $PROTO $TMPL | {constraints}
|
||||
CONSTRAINTS: {constraints}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -157,7 +157,7 @@ TASK: {task}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: {output}
|
||||
RULES: $PROTO $TMPL
|
||||
CONSTRAINTS: {constraints}
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {dir}
|
||||
|
||||
# Qwen fallback: Replace '--tool gemini' with '--tool qwen'
|
||||
|
||||
@@ -106,7 +106,7 @@ EXPECTED:
|
||||
## Time Estimate
|
||||
**Total**: [time]
|
||||
|
||||
RULES: $PROTO $TMPL |
|
||||
CONSTRAINTS:
|
||||
- Follow schema structure from {schema_path}
|
||||
- Acceptance/verification must be quantified
|
||||
- Dependencies use task IDs
|
||||
|
||||
@@ -127,7 +127,7 @@ EXPECTED: Structured fix strategy with:
|
||||
- Fix approach ensuring business logic correctness (not just test passage)
|
||||
- Expected outcome and verification steps
|
||||
- Impact assessment: Will this fix potentially mask other issues?
|
||||
RULES: $PROTO $TMPL |
|
||||
CONSTRAINTS:
|
||||
- For {test_type} tests: {layer_specific_guidance}
|
||||
- Avoid 'surgical fixes' that mask underlying issues
|
||||
- Provide specific line numbers for modifications
|
||||
|
||||
@@ -105,7 +105,7 @@ TASK: • Analyze error pattern • Identify potential root causes • Suggest t
|
||||
MODE: analysis
|
||||
CONTEXT: @{affected_files}
|
||||
EXPECTED: Structured hypothesis list with priority ranking
|
||||
RULES: $PROTO $TMPL | Focus on testable conditions
|
||||
CONSTRAINTS: Focus on testable conditions
|
||||
" --tool gemini --mode analysis --cd {project_root}
|
||||
```
|
||||
|
||||
@@ -213,7 +213,7 @@ EXPECTED:
|
||||
- Evidence summary
|
||||
- Root cause identification (if confirmed)
|
||||
- Next steps (if inconclusive)
|
||||
RULES: $PROTO $TMPL | Evidence-based reasoning only
|
||||
CONSTRAINTS: Evidence-based reasoning only
|
||||
" --tool gemini --mode analysis
|
||||
```
|
||||
|
||||
@@ -271,7 +271,7 @@ TASK:
|
||||
MODE: write
|
||||
CONTEXT: @{affected_files}
|
||||
EXPECTED: Working fix that addresses root cause
|
||||
RULES: $PROTO $TMPL | Minimal changes only
|
||||
CONSTRAINTS: Minimal changes only
|
||||
" --tool codex --mode write --cd {project_root}
|
||||
```
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ The agent supports **two execution modes** based on task JSON's `meta.cli_execut
|
||||
CONTEXT: @**/* ./src/modules/auth|code|code:5|dirs:2
|
||||
./src/modules/api|code|code:3|dirs:0
|
||||
EXPECTED: Documentation files in .workflow/docs/my_project/src/modules/
|
||||
RULES: $PROTO $TMPL | Mirror source structure
|
||||
CONSTRAINTS: Mirror source structure
|
||||
" --tool gemini --mode write --rule documentation-module --cd src/modules
|
||||
```
|
||||
|
||||
@@ -216,7 +216,7 @@ Before completion, verify:
|
||||
{
|
||||
"step": "analyze_module_structure",
|
||||
"action": "Deep analysis of module structure and API",
|
||||
"command": "ccw cli -p \"PURPOSE: Document module comprehensively\nTASK: Extract module purpose, architecture, public API, dependencies\nMODE: analysis\nCONTEXT: @**/* System: [system_context]\nEXPECTED: Complete module analysis for documentation\nRULES: $PROTO $TMPL\" --tool gemini --mode analysis --rule documentation-module --cd src/auth",
|
||||
"command": "ccw cli -p \"PURPOSE: Document module comprehensively\nTASK: Extract module purpose, architecture, public API, dependencies\nMODE: analysis\nCONTEXT: @**/* System: [system_context]\nEXPECTED: Complete module analysis for documentation\nCONSTRAINTS: Mirror source structure\" --tool gemini --mode analysis --rule documentation-module --cd src/auth",
|
||||
"output_to": "module_analysis",
|
||||
"on_error": "fail"
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ TASK: • Detect file conflicts (same file modified by multiple solutions)
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/issues/solutions/**/*.jsonl | Solution data: \${SOLUTIONS_JSON}
|
||||
EXPECTED: JSON array of conflicts with type, severity, solutions, recommended_order
|
||||
RULES: $PROTO | Severity: high (API/data) > medium (file/dependency) > low (architecture)
|
||||
CONSTRAINTS: Severity: high (API/data) > medium (file/dependency) > low (architecture)
|
||||
" --tool gemini --mode analysis --cd .workflow/issues
|
||||
```
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ TASK: • [step 1] • [step 2] • [step 3]
|
||||
MODE: review
|
||||
CONTEXT: [review target description] | Memory: [relevant context]
|
||||
EXPECTED: [deliverable format] + [quality criteria]
|
||||
RULES: $PROTO $TMPL | [focus constraints]
|
||||
CONSTRAINTS: [focus constraints]
|
||||
```
|
||||
|
||||
## EXECUTION INSTRUCTIONS - START HERE
|
||||
@@ -137,7 +137,7 @@ TASK: • Review code correctness and logic errors • Check coding standards an
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Project conventions from CLAUDE.md
|
||||
EXPECTED: Structured review report with: severity levels (Critical/High/Medium/Low), file:line references, specific improvement suggestions, priority ranking
|
||||
RULES: $PROTO $TMPL | Focus on actionable feedback
|
||||
CONSTRAINTS: Focus on actionable feedback
|
||||
```
|
||||
|
||||
**Security Focus Prompt:**
|
||||
@@ -147,7 +147,7 @@ TASK: • Scan for injection vulnerabilities (SQL, XSS, command) • Check authe
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Security best practices, OWASP Top 10
|
||||
EXPECTED: Security report with: vulnerability classification, CVE references where applicable, remediation code snippets, risk severity matrix
|
||||
RULES: $PROTO $TMPL | Security-first analysis | Flag all potential vulnerabilities
|
||||
CONSTRAINTS: Security-first analysis | Flag all potential vulnerabilities
|
||||
```
|
||||
|
||||
**Performance Focus Prompt:**
|
||||
@@ -157,7 +157,7 @@ TASK: • Analyze algorithmic complexity (Big-O) • Identify memory allocation
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Performance patterns and anti-patterns
|
||||
EXPECTED: Performance report with: complexity analysis, bottleneck identification, optimization suggestions with expected impact, benchmark recommendations
|
||||
RULES: $PROTO $TMPL | Performance optimization focus
|
||||
CONSTRAINTS: Performance optimization focus
|
||||
```
|
||||
|
||||
**Code Quality Focus Prompt:**
|
||||
@@ -167,7 +167,7 @@ TASK: • Assess SOLID principles adherence • Identify code duplication and ab
|
||||
MODE: review
|
||||
CONTEXT: {target_description} | Memory: Project coding standards
|
||||
EXPECTED: Quality report with: principle violations, refactoring suggestions, naming improvements, maintainability score
|
||||
RULES: $PROTO $TMPL | Code quality and maintainability focus
|
||||
CONSTRAINTS: Code quality and maintainability focus
|
||||
```
|
||||
|
||||
**3.2 Build Target Description**
|
||||
@@ -226,7 +226,7 @@ TASK: • Review correctness and logic • Check standards compliance • Identi
|
||||
MODE: review
|
||||
CONTEXT: Reviewing uncommitted changes | Memory: Project conventions
|
||||
EXPECTED: Structured report with severity levels, file:line refs, improvement suggestions
|
||||
RULES: $PROTO $TMPL | Actionable feedback
|
||||
CONSTRAINTS: Actionable feedback
|
||||
" --tool codex --mode review --uncommitted --rule analysis-review-code-quality
|
||||
```
|
||||
|
||||
|
||||
@@ -267,7 +267,7 @@ EXPECTED: JSON exploration plan following exploration-plan-schema.json:
|
||||
"estimated_iterations": N,
|
||||
"termination_conditions": [...]
|
||||
}
|
||||
RULES: $PROTO | Use ACE context to inform targets | Focus on actionable plan
|
||||
CONSTRAINTS: Use ACE context to inform targets | Focus on actionable plan
|
||||
`;
|
||||
|
||||
// Step 3: Execute Gemini planning
|
||||
|
||||
@@ -131,7 +131,7 @@ TASK: • Analyze issue titles/tags semantically • Identify functional/archite
|
||||
MODE: analysis
|
||||
CONTEXT: Issue metadata only
|
||||
EXPECTED: JSON with groups array, each containing max 4 issue_ids, theme, rationale
|
||||
RULES: $PROTO | Each issue in exactly one group | Max 4 issues per group | Balance group sizes
|
||||
CONSTRAINTS: Each issue in exactly one group | Max 4 issues per group | Balance group sizes
|
||||
|
||||
INPUT:
|
||||
${JSON.stringify(issueSummaries, null, 2)}
|
||||
|
||||
@@ -223,7 +223,7 @@ TASK:
|
||||
MODE: analysis
|
||||
CONTEXT: @src/**/*.controller.ts @src/**/*.routes.ts @src/**/*.dto.ts @src/**/middleware/**/*
|
||||
EXPECTED: JSON format API structure analysis report with modules, endpoints, security schemes, and error codes
|
||||
RULES: $PROTO | Strict RESTful standards | Identify all public endpoints | Document output language: {lang}
|
||||
CONSTRAINTS: Strict RESTful standards | Identify all public endpoints | Document output language: {lang}
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {project_root}
|
||||
```
|
||||
|
||||
@@ -387,7 +387,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
"step": 1,
|
||||
"title": "Generate OpenAPI spec file",
|
||||
"description": "Create complete swagger.yaml specification file",
|
||||
"cli_prompt": "PURPOSE: Generate OpenAPI 3.0.3 specification file from analyzed API structure\nTASK:\n• Define openapi version: 3.0.3\n• Define info: title, description, version, contact, license\n• Define servers: development, staging, production environments\n• Define tags: organized by business modules\n• Define paths: all API endpoints with complete specifications\n• Define components: schemas, securitySchemes, parameters, responses\nMODE: write\nCONTEXT: @[api_analysis]\nEXPECTED: Complete swagger.yaml file following OpenAPI 3.0.3 specification\nRULES: $PROTO $TMPL | Use {lang} for all descriptions | Strict RESTful standards\n--rule documentation-swagger-api",
|
||||
"cli_prompt": "PURPOSE: Generate OpenAPI 3.0.3 specification file from analyzed API structure\nTASK:\n• Define openapi version: 3.0.3\n• Define info: title, description, version, contact, license\n• Define servers: development, staging, production environments\n• Define tags: organized by business modules\n• Define paths: all API endpoints with complete specifications\n• Define components: schemas, securitySchemes, parameters, responses\nMODE: write\nCONTEXT: @[api_analysis]\nEXPECTED: Complete swagger.yaml file following OpenAPI 3.0.3 specification\nCONSTRAINTS: Use {lang} for all descriptions | Strict RESTful standards\n--rule documentation-swagger-api",
|
||||
"output": "swagger.yaml"
|
||||
}
|
||||
],
|
||||
@@ -429,7 +429,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate authentication documentation",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive authentication documentation for API security\nTASK:\n• Document authentication mechanism: JWT Bearer Token\n• Explain header format: Authorization: Bearer <token>\n• Describe token lifecycle: acquisition, refresh, expiration handling\n• Define permission levels: public, user, admin, super_admin\n• Document authentication failure responses: 401/403 error handling\nMODE: write\nCONTEXT: @[auth_patterns] @src/**/auth/**/* @src/**/guard/**/*\nEXPECTED: Complete authentication guide in {lang}\nRULES: $PROTO | Include code examples | Clear step-by-step instructions\n--rule development-feature",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive authentication documentation for API security\nTASK:\n• Document authentication mechanism: JWT Bearer Token\n• Explain header format: Authorization: Bearer <token>\n• Describe token lifecycle: acquisition, refresh, expiration handling\n• Define permission levels: public, user, admin, super_admin\n• Document authentication failure responses: 401/403 error handling\nMODE: write\nCONTEXT: @[auth_patterns] @src/**/auth/**/* @src/**/guard/**/*\nEXPECTED: Complete authentication guide in {lang}\nCONSTRAINTS: Include code examples | Clear step-by-step instructions\n--rule development-feature",
|
||||
"output": "{auth_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -464,7 +464,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate error code specification document",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive error code specification for consistent API error handling\nTASK:\n• Define error response format: {code, message, details, timestamp}\n• Document authentication errors (AUTH_xxx): 401/403 series\n• Document parameter errors (PARAM_xxx): 400 series\n• Document business errors (BIZ_xxx): business logic errors\n• Document system errors (SYS_xxx): 500 series\n• For each error code: HTTP status, error message, possible causes, resolution suggestions\nMODE: write\nCONTEXT: @src/**/*.exception.ts @src/**/*.filter.ts\nEXPECTED: Complete error code specification in {lang} with tables and examples\nRULES: $PROTO | Include response examples | Clear categorization\n--rule development-feature",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive error code specification for consistent API error handling\nTASK:\n• Define error response format: {code, message, details, timestamp}\n• Document authentication errors (AUTH_xxx): 401/403 series\n• Document parameter errors (PARAM_xxx): 400 series\n• Document business errors (BIZ_xxx): business logic errors\n• Document system errors (SYS_xxx): 500 series\n• For each error code: HTTP status, error message, possible causes, resolution suggestions\nMODE: write\nCONTEXT: @src/**/*.exception.ts @src/**/*.filter.ts\nEXPECTED: Complete error code specification in {lang} with tables and examples\nCONSTRAINTS: Include response examples | Clear categorization\n--rule development-feature",
|
||||
"output": "{error_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -523,7 +523,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
"step": 1,
|
||||
"title": "Generate module API documentation",
|
||||
"description": "Generate complete API documentation for ${module_name}",
|
||||
"cli_prompt": "PURPOSE: Generate complete RESTful API documentation for ${module_name} module\nTASK:\n• Create module overview: purpose, use cases, prerequisites\n• Generate endpoint index: grouped by functionality\n• For each endpoint document:\n - Functional description: purpose and business context\n - Request method: GET/POST/PUT/DELETE\n - URL path: complete API path\n - Request headers: Authorization and other required headers\n - Path parameters: {id} and other path variables\n - Query parameters: pagination, filters, etc.\n - Request body: JSON Schema format\n - Response body: success and error responses\n - Field description table: type, required, example, description\n• Add usage examples: cURL, JavaScript, Python\n• Add version info: v1.0.0, last updated date\nMODE: write\nCONTEXT: @[module_endpoints] @[source_code]\nEXPECTED: Complete module API documentation in {lang} with all endpoints fully documented\nRULES: $PROTO $TMPL | RESTful standards | Include all response codes\n--rule documentation-swagger-api",
|
||||
"cli_prompt": "PURPOSE: Generate complete RESTful API documentation for ${module_name} module\nTASK:\n• Create module overview: purpose, use cases, prerequisites\n• Generate endpoint index: grouped by functionality\n• For each endpoint document:\n - Functional description: purpose and business context\n - Request method: GET/POST/PUT/DELETE\n - URL path: complete API path\n - Request headers: Authorization and other required headers\n - Path parameters: {id} and other path variables\n - Query parameters: pagination, filters, etc.\n - Request body: JSON Schema format\n - Response body: success and error responses\n - Field description table: type, required, example, description\n• Add usage examples: cURL, JavaScript, Python\n• Add version info: v1.0.0, last updated date\nMODE: write\nCONTEXT: @[module_endpoints] @[source_code]\nEXPECTED: Complete module API documentation in {lang} with all endpoints fully documented\nCONSTRAINTS: RESTful standards | Include all response codes\n--rule documentation-swagger-api",
|
||||
"output": "${module_doc_name}"
|
||||
}
|
||||
],
|
||||
@@ -559,7 +559,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate API overview",
|
||||
"cli_prompt": "PURPOSE: Generate API overview document with navigation and quick start guide\nTASK:\n• Create introduction: system features, tech stack, version\n• Write quick start guide: authentication, first request example\n• Build module navigation: categorized links to all modules\n• Document environment configuration: development, staging, production\n• List SDKs and tools: client libraries, Postman collection\nMODE: write\nCONTEXT: @[all_module_docs] @.workflow/docs/${project_name}/api/swagger.yaml\nEXPECTED: Complete API overview in {lang} with navigation links\nRULES: $PROTO | Clear structure | Quick start focus\n--rule development-feature",
|
||||
"cli_prompt": "PURPOSE: Generate API overview document with navigation and quick start guide\nTASK:\n• Create introduction: system features, tech stack, version\n• Write quick start guide: authentication, first request example\n• Build module navigation: categorized links to all modules\n• Document environment configuration: development, staging, production\n• List SDKs and tools: client libraries, Postman collection\nMODE: write\nCONTEXT: @[all_module_docs] @.workflow/docs/${project_name}/api/swagger.yaml\nEXPECTED: Complete API overview in {lang} with navigation links\nCONSTRAINTS: Clear structure | Quick start focus\n--rule development-feature",
|
||||
"output": "README.md"
|
||||
}
|
||||
],
|
||||
@@ -602,7 +602,7 @@ bash(cat ${session_dir}/.process/swagger-planning-data.json | jq -r '.api_struct
|
||||
{
|
||||
"step": 1,
|
||||
"title": "Generate test report",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive API test validation report\nTASK:\n• Document test environment configuration\n• Calculate endpoint coverage statistics\n• Report test results: pass/fail counts\n• Document boundary tests: parameter limits, null values, special characters\n• Document exception tests: auth failures, permission denied, resource not found\n• List issues found with recommendations\nMODE: write\nCONTEXT: @[swagger_spec]\nEXPECTED: Complete test report in {lang} with detailed results\nRULES: $PROTO | Include test cases | Clear pass/fail status\n--rule development-tests",
|
||||
"cli_prompt": "PURPOSE: Generate comprehensive API test validation report\nTASK:\n• Document test environment configuration\n• Calculate endpoint coverage statistics\n• Report test results: pass/fail counts\n• Document boundary tests: parameter limits, null values, special characters\n• Document exception tests: auth failures, permission denied, resource not found\n• List issues found with recommendations\nMODE: write\nCONTEXT: @[swagger_spec]\nEXPECTED: Complete test report in {lang} with detailed results\nCONSTRAINTS: Include test cases | Clear pass/fail status\n--rule development-tests",
|
||||
"output": "{test_doc_name}"
|
||||
}
|
||||
],
|
||||
|
||||
@@ -486,7 +486,7 @@ TASK: • Verify plan acceptance criteria fulfillment • Analyze code quality
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* @{plan.json} [@{exploration.json}] | Memory: Review lite-execute changes against plan requirements
|
||||
EXPECTED: Quality assessment with acceptance criteria verification, issue identification, and recommendations. Explicitly check each acceptance criterion from plan.json tasks.
|
||||
RULES: $PROTO $TMPL | Focus on plan acceptance criteria and plan adherence | analysis=READ-ONLY
|
||||
CONSTRAINTS: Focus on plan acceptance criteria and plan adherence | analysis=READ-ONLY
|
||||
```
|
||||
|
||||
**Tool-Specific Execution** (Apply shared prompt template above):
|
||||
|
||||
@@ -167,7 +167,7 @@ TASK: ${tasks.map(t => `• ${t}`).join(' ')}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: ${expected}
|
||||
RULES: $PROTO | ${rules}
|
||||
CONSTRAINTS: ${rules}
|
||||
`
|
||||
}
|
||||
|
||||
@@ -373,7 +373,7 @@ TASK: ${extractedTasks.join(' • ')}
|
||||
MODE: write
|
||||
CONTEXT: @${affectedFiles.join(' @')}
|
||||
EXPECTED: Working implementation with all changes applied
|
||||
RULES: $PROTO
|
||||
CONSTRAINTS: Follow existing patterns
|
||||
" --tool ${executionTool.name} --mode write`,
|
||||
run_in_background: false
|
||||
})
|
||||
|
||||
@@ -154,7 +154,7 @@ Task(subagent_type="cli-execution-agent", run_in_background=false, prompt=`
|
||||
- Validation of exploration conflict_indicators
|
||||
- ModuleOverlap conflicts with overlap_analysis
|
||||
- Targeted clarification questions
|
||||
RULES: $PROTO $TMPL | Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
|
||||
CONSTRAINTS: Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd {project_root}
|
||||
|
||||
Fallback: Qwen (same prompt) → Claude (manual analysis)
|
||||
|
||||
@@ -304,14 +304,14 @@ async function runWithTool(tool, context) {
|
||||
### 引用协议模板
|
||||
|
||||
```bash
|
||||
# 分析模式 - 使用 --rule 自动加载协议和模板
|
||||
# Analysis mode - use --rule to auto-load protocol and template (appended to prompt)
|
||||
ccw cli -p "
|
||||
RULES: $PROTO $TMPL | ...
|
||||
CONSTRAINTS: ...
|
||||
..." --tool gemini --mode analysis --rule analysis-code-patterns
|
||||
|
||||
# 写入模式 - 使用 --rule 自动加载协议和模板
|
||||
# Write mode - use --rule to auto-load protocol and template (appended to prompt)
|
||||
ccw cli -p "
|
||||
RULES: $PROTO $TMPL | ...
|
||||
CONSTRAINTS: ...
|
||||
..." --tool codex --mode write --rule development-feature
|
||||
```
|
||||
|
||||
@@ -319,11 +319,7 @@ RULES: $PROTO $TMPL | ...
|
||||
|
||||
```javascript
|
||||
function buildPrompt(config) {
|
||||
const { purpose, task, mode, context, expected, template } = config;
|
||||
|
||||
const protocolPath = mode === 'write'
|
||||
? '~/.claude/workflows/cli-templates/protocols/write-protocol.md'
|
||||
: '~/.claude/workflows/cli-templates/protocols/analysis-protocol.md';
|
||||
const { purpose, task, mode, context, expected, constraints } = config;
|
||||
|
||||
return `
|
||||
PURPOSE: ${purpose}
|
||||
@@ -331,8 +327,8 @@ TASK: ${task.map(t => `• ${t}`).join('\n')}
|
||||
MODE: ${mode}
|
||||
CONTEXT: ${context}
|
||||
EXPECTED: ${expected}
|
||||
RULES: $PROTO $TMPL
|
||||
`; // Use --rule option to specify template
|
||||
CONSTRAINTS: ${constraints || ''}
|
||||
`; // Use --rule option to auto-append protocol + template
|
||||
}
|
||||
```
|
||||
|
||||
@@ -433,11 +429,11 @@ CLI 调用 (Bash + ccw cli):
|
||||
- 相关任务使用 `--resume` 保持上下文
|
||||
- 独立任务不使用 `--resume`
|
||||
|
||||
### 4. 提示词规范
|
||||
### 4. Prompt Specification
|
||||
|
||||
- 始终使用 PURPOSE/TASK/MODE/CONTEXT/EXPECTED/RULES 结构
|
||||
- 使用 `--rule <template>` 自动加载协议和模板(`$PROTO` 和 `$TMPL`)
|
||||
- 模板名格式: `category-function` (如 `analysis-code-patterns`)
|
||||
- Always use PURPOSE/TASK/MODE/CONTEXT/EXPECTED/CONSTRAINTS structure
|
||||
- Use `--rule <template>` to auto-append protocol + template to prompt
|
||||
- Template name format: `category-function` (e.g., `analysis-code-patterns`)
|
||||
|
||||
### 5. 结果处理
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ TASK: • Extract conflicts from IMPL_PLAN and lessons • Group by type (archit
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/.archives/*/IMPL_PLAN.md @.workflow/.archives/manifest.json
|
||||
EXPECTED: Conflict patterns with frequency and resolution
|
||||
RULES: $PROTO $TMPL | analysis=READ-ONLY
|
||||
CONSTRAINTS: analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule workflow-skill-aggregation --cd .workflow/.archives
|
||||
```
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ TASK: • Group successes by functional domain • Categorize challenges by seve
|
||||
MODE: analysis
|
||||
CONTEXT: @.workflow/.archives/manifest.json
|
||||
EXPECTED: Aggregated lessons with frequency counts
|
||||
RULES: $PROTO $TMPL | analysis=READ-ONLY
|
||||
CONSTRAINTS: analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule workflow-skill-aggregation --cd .workflow/.archives
|
||||
```
|
||||
|
||||
|
||||
@@ -111,14 +111,13 @@ When primary tool fails or is unavailable:
|
||||
### Universal Prompt Template
|
||||
|
||||
```bash
|
||||
# Use --rule to auto-load protocol and template as $PROTO and $TMPL
|
||||
ccw cli -p "
|
||||
PURPOSE: [what] + [why] + [success criteria] + [constraints/scope]
|
||||
TASK: • [step 1: specific action] • [step 2: specific action] • [step 3: specific action]
|
||||
MODE: [analysis|write]
|
||||
CONTEXT: @[file patterns] | Memory: [session/tech/module context]
|
||||
EXPECTED: [deliverable format] + [quality criteria] + [structure requirements]
|
||||
RULES: $PROTO $TMPL | [domain constraints]
|
||||
CONSTRAINTS: [domain constraints]
|
||||
" --tool <tool-id> --mode <analysis|write> --rule <category-template>
|
||||
```
|
||||
|
||||
@@ -168,11 +167,11 @@ Every command MUST include these fields:
|
||||
- Bad Example: "Report"
|
||||
- Good Example: "Markdown report with: severity levels (Critical/High/Medium/Low), file:line references, remediation code snippets, priority ranking"
|
||||
|
||||
- **RULES**
|
||||
- Purpose: Protocol + template + constraints
|
||||
- Components: $PROTO + $TMPL + domain rules (variables loaded beforehand)
|
||||
- Bad Example: (missing)
|
||||
- Good Example: "$PROTO $TMPL | Focus on authentication | Ignore test files" (where PROTO and TMPL are pre-loaded variables)
|
||||
- **CONSTRAINTS**
|
||||
- Purpose: Domain-specific constraints
|
||||
- Components: Scope limits, special requirements, focus areas
|
||||
- Bad Example: (missing or too vague)
|
||||
- Good Example: "Focus on authentication | Ignore test files | No breaking changes"
|
||||
|
||||
### CONTEXT Configuration
|
||||
|
||||
@@ -221,27 +220,24 @@ CONTEXT: @components/Auth.tsx @types/auth.d.ts | Memory: Previous type refactori
|
||||
ccw cli -p "..." --tool <tool-id> --mode analysis --cd src
|
||||
```
|
||||
|
||||
### RULES Configuration
|
||||
### --rule Configuration
|
||||
|
||||
**Use `--rule` option to auto-load templates**:
|
||||
|
||||
```bash
|
||||
ccw cli -p "... RULES: \$PROTO \$TMPL | constraints" --tool gemini --mode analysis --rule analysis-review-architecture
|
||||
ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture
|
||||
```
|
||||
|
||||
**`--rule` How It Works**:
|
||||
1. Auto-discovers templates from `~/.claude/workflows/cli-templates/prompts/`
|
||||
2. Auto-loads corresponding protocol based on `--mode` (analysis-protocol.md or write-protocol.md)
|
||||
3. Sets environment variables `$PROTO` (protocol) and `$TMPL` (template) for subprocess
|
||||
4. Reference `$PROTO` and `$TMPL` in prompt
|
||||
|
||||
> **Important**: `$PROTO` is required and must be included in RULES. `$TMPL` is optional.
|
||||
3. Appends protocol and template content to the end of your prompt
|
||||
|
||||
### Mode Protocol References
|
||||
|
||||
**`--rule` auto-handles Protocol**:
|
||||
- `--mode analysis` → `$PROTO` = analysis-protocol.md
|
||||
- `--mode write` → `$PROTO` = write-protocol.md
|
||||
**`--rule` auto-loads Protocol based on mode**:
|
||||
- `--mode analysis` → analysis-protocol.md
|
||||
- `--mode write` → write-protocol.md
|
||||
|
||||
**Protocol Mapping**:
|
||||
|
||||
@@ -336,9 +332,9 @@ ccw cli -p "... RULES: \$PROTO \$TMPL | constraints" --tool gemini --mode analys
|
||||
- Default: -
|
||||
|
||||
- **`--rule <template>`**
|
||||
- Description: 模板名称,自动加载 protocol + template 为 $PROTO 和 $TMPL 环境变量
|
||||
- Default: none
|
||||
- 根据 --mode 自动选择 protocol
|
||||
- Description: Template name, auto-loads protocol + template appended to prompt
|
||||
- Default: universal-rigorous-style
|
||||
- Auto-selects protocol based on --mode
|
||||
|
||||
### Directory Configuration
|
||||
|
||||
@@ -407,7 +403,7 @@ TASK: • Scan for injection flaws (SQL, command, LDAP) • Check authentication
|
||||
MODE: analysis
|
||||
CONTEXT: @src/auth/**/* @src/middleware/auth.ts | Memory: Using bcrypt for passwords, JWT for sessions
|
||||
EXPECTED: Security report with: severity matrix, file:line references, CVE mappings where applicable, remediation code snippets prioritized by risk
|
||||
RULES: \$PROTO \$TMPL | Focus on authentication | Ignore test files
|
||||
CONSTRAINTS: Focus on authentication | Ignore test files
|
||||
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd src/auth
|
||||
```
|
||||
|
||||
@@ -419,7 +415,7 @@ TASK: • Create rate limiter middleware with sliding window • Implement per-r
|
||||
MODE: write
|
||||
CONTEXT: @src/middleware/**/* @src/config/**/* | Memory: Using Express.js, Redis already configured, existing middleware pattern in auth.ts
|
||||
EXPECTED: Production-ready code with: TypeScript types, unit tests, integration test, configuration example, migration guide
|
||||
RULES: \$PROTO \$TMPL | Follow existing middleware patterns | No breaking changes
|
||||
CONSTRAINTS: Follow existing middleware patterns | No breaking changes
|
||||
" --tool gemini --mode write --rule development-implement-feature
|
||||
```
|
||||
|
||||
@@ -431,7 +427,7 @@ TASK: • Trace connection lifecycle from open to close • Identify event liste
|
||||
MODE: analysis
|
||||
CONTEXT: @src/websocket/**/* @src/services/connection-manager.ts | Memory: Using ws library, ~5000 concurrent connections in production
|
||||
EXPECTED: Root cause analysis with: memory profile, leak source (file:line), fix recommendation with code, verification steps
|
||||
RULES: \$PROTO \$TMPL | Focus on resource cleanup
|
||||
CONSTRAINTS: Focus on resource cleanup
|
||||
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd src
|
||||
```
|
||||
|
||||
@@ -443,7 +439,7 @@ TASK: • Extract gateway interface from current implementation • Create strat
|
||||
MODE: write
|
||||
CONTEXT: @src/payments/**/* @src/types/payment.ts | Memory: Currently only Stripe, adding PayPal next sprint, must support future gateways
|
||||
EXPECTED: Refactored code with: strategy interface, concrete implementations, factory class, updated tests, migration checklist
|
||||
RULES: \$PROTO \$TMPL | Preserve all existing behavior | Tests must pass
|
||||
CONSTRAINTS: Preserve all existing behavior | Tests must pass
|
||||
" --tool gemini --mode write --rule development-refactor-codebase
|
||||
```
|
||||
|
||||
@@ -481,15 +477,15 @@ ccw cli -p "Check for breaking changes in API contracts and backward compatibili
|
||||
- **Use tools early and often** - Tools are faster and more thorough
|
||||
- **Unified CLI** - Always use `ccw cli -p` for consistent parameter handling
|
||||
- **Default mode is analysis** - Omit `--mode` for read-only operations, explicitly use `--mode write` for file modifications
|
||||
- **Use `--rule` for templates** - 自动加载 protocol + template 为 `$PROTO` 和 `$TMPL` 环境变量
|
||||
- **Use `--rule` for templates** - Auto-loads protocol + template appended to prompt
|
||||
- **Write protection** - Require EXPLICIT `--mode write` for file operations
|
||||
|
||||
### Workflow Principles
|
||||
|
||||
- **Use CCW unified interface** for all executions
|
||||
- **Always include template** - 使用 `--rule <template-name>` 加载模板
|
||||
- **Always include template** - Use `--rule <template-name>` to load templates
|
||||
- **Be specific** - Clear PURPOSE, TASK, EXPECTED fields
|
||||
- **Include constraints** - File patterns, scope in RULES
|
||||
- **Include constraints** - File patterns, scope in CONSTRAINTS
|
||||
- **Leverage memory context** when building on previous work
|
||||
- **Discover patterns first** - Use rg/MCP before CLI execution
|
||||
- **Default to full context** - Use `@**/*` unless specific files needed
|
||||
@@ -501,8 +497,8 @@ ccw cli -p "Check for breaking changes in API contracts and backward compatibili
|
||||
- [ ] **Context gathered** - File references + memory (default `@**/*`)
|
||||
- [ ] **Directory navigation** - `--cd` and/or `--includeDirs`
|
||||
- [ ] **Tool selected** - Explicit `--tool` or tag-based auto-selection
|
||||
- [ ] **Rule template** - `--rule <template-name>` 自动加载 protocol + template
|
||||
- [ ] **Constraints specified** - Scope, requirements
|
||||
- [ ] **Rule template** - `--rule <template-name>` loads template
|
||||
- [ ] **Constraints** - Domain constraints in CONSTRAINTS field
|
||||
|
||||
### Execution Workflow
|
||||
|
||||
|
||||
@@ -551,6 +551,8 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
}
|
||||
|
||||
// Priority: 1. --file, 2. --prompt/-p option, 3. positional argument
|
||||
// Note: On Windows, quoted arguments like -p "say hello" may be split into
|
||||
// -p "say" and positional "hello". We merge them back together.
|
||||
let finalPrompt: string | undefined;
|
||||
|
||||
if (file) {
|
||||
@@ -569,7 +571,8 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
}
|
||||
} else if (optionPrompt) {
|
||||
// Use --prompt/-p option (preferred for multi-line)
|
||||
finalPrompt = optionPrompt;
|
||||
// Merge with positional argument if Windows split the quoted string
|
||||
finalPrompt = positionalPrompt ? `${optionPrompt} ${positionalPrompt}` : optionPrompt;
|
||||
} else {
|
||||
// Fall back to positional argument
|
||||
finalPrompt = positionalPrompt;
|
||||
@@ -586,20 +589,21 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
|
||||
const prompt_to_use = finalPrompt || '';
|
||||
|
||||
// Load rules templates (will be passed as env vars)
|
||||
// Load rules templates (concatenation mode - directly prepend to prompt)
|
||||
// Default to universal-rigorous-style if --rule not specified
|
||||
const effectiveRule = rule || 'universal-rigorous-style';
|
||||
let rulesEnv: { PROTO?: string; TMPL?: string } = {};
|
||||
let systemRules = ''; // Protocol content
|
||||
let roles = ''; // Template content
|
||||
try {
|
||||
const { loadProtocol, loadTemplate } = await import('../tools/template-discovery.js');
|
||||
const proto = loadProtocol(mode);
|
||||
const tmpl = loadTemplate(effectiveRule);
|
||||
if (proto) rulesEnv.PROTO = proto;
|
||||
if (tmpl) rulesEnv.TMPL = tmpl;
|
||||
if (proto) systemRules = proto;
|
||||
if (tmpl) roles = tmpl;
|
||||
if (debug) {
|
||||
console.log(chalk.gray(` Rule loaded: ${effectiveRule}${!rule ? ' (default)' : ''}`));
|
||||
console.log(chalk.gray(` PROTO(${proto ? proto.length : 0} chars) + TMPL(${tmpl ? tmpl.length : 0} chars)`));
|
||||
console.log(chalk.gray(` Use $PROTO and $TMPL in your prompt to reference them`));
|
||||
console.log(chalk.gray(` systemRules(${systemRules.length} chars) + roles(${roles.length} chars)`));
|
||||
console.log(chalk.gray(` Rules will be prepended to prompt automatically`));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error loading rule template: ${error instanceof Error ? error.message : error}`));
|
||||
@@ -728,6 +732,24 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
}
|
||||
}
|
||||
|
||||
// Concatenate systemRules and roles to the end of prompt (if loaded)
|
||||
// Format: [USER_PROMPT]\n[SYSTEM_RULES]\n[ROLES]
|
||||
if (systemRules || roles) {
|
||||
const parts: string[] = [actualPrompt];
|
||||
if (systemRules) {
|
||||
parts.push(`=== SYSTEM RULES ===\n${systemRules}`);
|
||||
}
|
||||
if (roles) {
|
||||
parts.push(`=== ROLES ===\n${roles}`);
|
||||
}
|
||||
actualPrompt = parts.join('\n\n');
|
||||
|
||||
if (debug) {
|
||||
console.log(chalk.gray(` Prompt structure: USER_PROMPT(${prompt_to_use.length}) + SYSTEM_RULES(${systemRules.length}) + ROLES(${roles.length})`));
|
||||
console.log(chalk.gray(` Total prompt length: ${actualPrompt.length} chars`));
|
||||
}
|
||||
}
|
||||
|
||||
// Parse resume IDs for merge scenario
|
||||
const resumeIds = resume && typeof resume === 'string' ? resume.split(',').map(s => s.trim()).filter(Boolean) : [];
|
||||
const isMerge = resumeIds.length > 1;
|
||||
@@ -835,6 +857,7 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
switch (unit.type) {
|
||||
case 'stdout':
|
||||
case 'code':
|
||||
case 'streaming_content': // Show streaming delta content in real-time
|
||||
process.stdout.write(typeof unit.content === 'string' ? unit.content : JSON.stringify(unit.content));
|
||||
break;
|
||||
case 'stderr':
|
||||
@@ -879,9 +902,8 @@ async function execAction(positionalPrompt: string | undefined, options: CliExec
|
||||
uncommitted,
|
||||
base,
|
||||
commit,
|
||||
title,
|
||||
// Rules env vars (PROTO, TMPL)
|
||||
rulesEnv: Object.keys(rulesEnv).length > 0 ? rulesEnv : undefined
|
||||
title
|
||||
// Rules are now concatenated directly into prompt (no env vars)
|
||||
}, onOutput); // Always pass onOutput for real-time dashboard streaming
|
||||
|
||||
if (elapsedInterval) clearInterval(elapsedInterval);
|
||||
@@ -1228,7 +1250,15 @@ export async function cliCommand(
|
||||
|
||||
if (hasPromptOption || hasFileOption || hasResume || subcommandIsPrompt) {
|
||||
// Treat as exec: use subcommand as positional prompt if no -p/-f option
|
||||
const positionalPrompt = subcommandIsPrompt ? subcommand : undefined;
|
||||
let positionalPrompt = subcommandIsPrompt ? subcommand : undefined;
|
||||
|
||||
// On Windows, quoted arguments like -p "a b c" may be split across argsArray
|
||||
// Merge them back together to reconstruct the full prompt
|
||||
if (argsArray.length > 0 && hasPromptOption) {
|
||||
const extraArgs = argsArray.join(' ');
|
||||
positionalPrompt = positionalPrompt ? `${positionalPrompt} ${extraArgs}` : extraArgs;
|
||||
}
|
||||
|
||||
await execAction(positionalPrompt, execOptions);
|
||||
} else {
|
||||
// Show help
|
||||
|
||||
@@ -1149,7 +1149,7 @@ async function executeCliTool(
|
||||
duration_ms: duration,
|
||||
output: newTurnOutput,
|
||||
parsedOutput: flattenOutputUnits(allOutputUnits, {
|
||||
excludeTypes: ['stderr', 'progress', 'metadata', 'system', 'tool_call']
|
||||
excludeTypes: ['stderr', 'progress', 'metadata', 'system', 'tool_call', 'thought']
|
||||
})
|
||||
};
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ export type CliOutputUnitType =
|
||||
| 'progress' // Progress updates
|
||||
| 'metadata' // Session/execution metadata
|
||||
| 'system' // System events/messages
|
||||
| 'tool_call'; // Tool invocation/result (Gemini tool_use/tool_result)
|
||||
| 'tool_call' // Tool invocation/result (Gemini tool_use/tool_result)
|
||||
| 'streaming_content'; // Streaming delta content (only last one used in final output)
|
||||
|
||||
/**
|
||||
* Intermediate Representation unit
|
||||
@@ -292,9 +293,9 @@ export class JsonLinesParser implements IOutputParser {
|
||||
if (json.type === 'message' && json.role) {
|
||||
// Gemini assistant/user message
|
||||
if (json.role === 'assistant') {
|
||||
// Delta messages are incremental streaming chunks - treat as progress (filtered from final output)
|
||||
// Only non-delta messages are final content
|
||||
const outputType = json.delta === true ? 'progress' : 'stdout';
|
||||
// Delta messages use 'streaming_content' type - only last one is used in final output
|
||||
// Non-delta (final) messages use 'stdout' type
|
||||
const outputType = json.delta === true ? 'streaming_content' : 'stdout';
|
||||
return {
|
||||
type: outputType,
|
||||
content: json.content || '',
|
||||
@@ -1125,8 +1126,26 @@ export function flattenOutputUnits(
|
||||
separator = '\n'
|
||||
} = options || {};
|
||||
|
||||
// Special handling for streaming_content: concatenate all into a single stdout unit
|
||||
// Gemini delta messages are incremental (each contains partial content to append)
|
||||
let processedUnits = units;
|
||||
const streamingUnits = units.filter(u => u.type === 'streaming_content');
|
||||
if (streamingUnits.length > 0) {
|
||||
// Concatenate all streaming_content into one
|
||||
const concatenatedContent = streamingUnits
|
||||
.map(u => typeof u.content === 'string' ? u.content : '')
|
||||
.join('');
|
||||
processedUnits = units.filter(u => u.type !== 'streaming_content');
|
||||
// Add concatenated content as stdout type for inclusion
|
||||
processedUnits.push({
|
||||
type: 'stdout',
|
||||
content: concatenatedContent,
|
||||
timestamp: streamingUnits[streamingUnits.length - 1].timestamp
|
||||
});
|
||||
}
|
||||
|
||||
// Filter units by type
|
||||
let filtered = units;
|
||||
let filtered = processedUnits;
|
||||
if (includeTypes && includeTypes.length > 0) {
|
||||
filtered = filtered.filter(u => includeTypes.includes(u.type));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user