claude-code-workflow 6.3.48 → 6.3.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/CLAUDE.md +6 -8
- package/.claude/agents/action-planning-agent.md +28 -45
- package/.claude/agents/cli-lite-planning-agent.md +93 -1
- package/.claude/agents/code-developer.md +144 -27
- package/.claude/commands/ccw-coordinator.md +175 -21
- package/.claude/commands/ccw-debug.md +832 -0
- package/.claude/commands/ccw.md +90 -9
- package/.claude/commands/cli/cli-init.md +1 -0
- package/.claude/commands/issue/convert-to-plan.md +718 -0
- package/.claude/commands/issue/from-brainstorm.md +382 -0
- package/.claude/commands/memory/tips.md +332 -0
- package/.claude/commands/workflow/analyze-with-file.md +804 -0
- package/.claude/commands/workflow/brainstorm/auto-parallel.md +18 -43
- package/.claude/commands/workflow/brainstorm/role-analysis.md +705 -0
- package/.claude/commands/workflow/brainstorm-with-file.md +1153 -0
- package/.claude/commands/workflow/debug-with-file.md +7 -5
- package/.claude/commands/workflow/execute.md +6 -4
- package/.claude/commands/workflow/lite-plan.md +2 -2
- package/.claude/commands/workflow/plan-verify.md +162 -327
- package/.claude/commands/workflow/plan.md +162 -26
- package/.claude/commands/workflow/replan.md +78 -2
- package/.claude/commands/workflow/{review-fix.md → review-cycle-fix.md} +6 -6
- package/.claude/commands/workflow/review-module-cycle.md +2 -2
- package/.claude/commands/workflow/review-session-cycle.md +2 -2
- package/.claude/commands/workflow/tools/conflict-resolution.md +16 -26
- package/.claude/commands/workflow/tools/context-gather.md +81 -118
- package/.claude/commands/workflow/tools/task-generate-agent.md +94 -10
- package/.claude/skills/ccw-help/command.json +4 -4
- package/.claude/skills/lite-skill-generator/SKILL.md +650 -0
- package/.claude/skills/lite-skill-generator/templates/simple-skill.md +68 -0
- package/.claude/skills/lite-skill-generator/templates/style-guide.md +64 -0
- package/.claude/skills/skill-generator/SKILL.md +277 -85
- package/.claude/skills/skill-generator/phases/01-requirements-discovery.md +4 -15
- package/.claude/skills/skill-generator/phases/02-structure-generation.md +72 -17
- package/.claude/skills/skill-generator/phases/03-phase-generation.md +218 -51
- package/.claude/skills/skill-generator/phases/04-specs-templates.md +111 -41
- package/.claude/skills/skill-generator/phases/05-validation.md +139 -56
- package/.claude/skills/skill-generator/templates/autonomous-action.md +78 -268
- package/.claude/skills/skill-generator/templates/autonomous-orchestrator.md +14 -0
- package/.claude/skills/skill-generator/templates/code-analysis-action.md +12 -0
- package/.claude/skills/skill-generator/templates/llm-action.md +12 -0
- package/.claude/skills/skill-generator/templates/script-template.md +368 -0
- package/.claude/skills/skill-generator/templates/sequential-phase.md +14 -0
- package/.claude/skills/skill-generator/templates/skill-md.md +14 -0
- package/.claude/skills/skill-tuning/SKILL.md +130 -266
- package/.claude/skills/skill-tuning/phases/orchestrator.md +95 -283
- package/.claude/skills/skill-tuning/specs/problem-taxonomy.md +90 -198
- package/.claude/skills/skill-tuning/specs/tuning-strategies.md +193 -1345
- package/.claude/workflows/cli-templates/schemas/plan-verify-agent-schema.json +47 -0
- package/.claude/workflows/cli-templates/schemas/verify-json-schema.json +158 -0
- package/.claude/workflows/cli-tools-usage.md +1 -1
- package/.codex/AGENTS.md +1 -3
- package/.codex/prompts/analyze-with-file.md +607 -0
- package/.codex/prompts/brainstorm-to-cycle.md +455 -0
- package/.codex/prompts/brainstorm-with-file.md +933 -0
- package/.codex/prompts/debug-with-file.md +15 -20
- package/.codex/skills/ccw-cli-tools/SKILL.md +559 -0
- package/ccw/dist/commands/cli.d.ts.map +1 -1
- package/ccw/dist/commands/cli.js +29 -5
- package/ccw/dist/commands/cli.js.map +1 -1
- package/ccw/dist/commands/issue.d.ts +2 -0
- package/ccw/dist/commands/issue.d.ts.map +1 -1
- package/ccw/dist/commands/issue.js +62 -20
- package/ccw/dist/commands/issue.js.map +1 -1
- package/ccw/dist/config/litellm-api-config-manager.d.ts.map +1 -1
- package/ccw/dist/config/litellm-api-config-manager.js +5 -3
- package/ccw/dist/config/litellm-api-config-manager.js.map +1 -1
- package/ccw/dist/config/litellm-provider-models.d.ts +73 -0
- package/ccw/dist/config/litellm-provider-models.d.ts.map +1 -0
- package/ccw/dist/config/litellm-provider-models.js +172 -0
- package/ccw/dist/config/litellm-provider-models.js.map +1 -0
- package/ccw/dist/config/provider-models.d.ts +25 -51
- package/ccw/dist/config/provider-models.d.ts.map +1 -1
- package/ccw/dist/config/provider-models.js +84 -149
- package/ccw/dist/config/provider-models.js.map +1 -1
- package/ccw/dist/config/storage-paths.d.ts.map +1 -1
- package/ccw/dist/config/storage-paths.js +23 -5
- package/ccw/dist/config/storage-paths.js.map +1 -1
- package/ccw/dist/core/auth/csrf-middleware.js +3 -3
- package/ccw/dist/core/auth/csrf-middleware.js.map +1 -1
- package/ccw/dist/core/dashboard-generator.d.ts.map +1 -1
- package/ccw/dist/core/dashboard-generator.js +3 -1
- package/ccw/dist/core/dashboard-generator.js.map +1 -1
- package/ccw/dist/core/routes/claude-routes.d.ts.map +1 -1
- package/ccw/dist/core/routes/claude-routes.js +206 -14
- package/ccw/dist/core/routes/claude-routes.js.map +1 -1
- package/ccw/dist/core/routes/cli-routes.d.ts.map +1 -1
- package/ccw/dist/core/routes/cli-routes.js.map +1 -1
- package/ccw/dist/core/routes/commands-routes.d.ts +7 -0
- package/ccw/dist/core/routes/commands-routes.d.ts.map +1 -0
- package/ccw/dist/core/routes/commands-routes.js +480 -0
- package/ccw/dist/core/routes/commands-routes.js.map +1 -0
- package/ccw/dist/core/routes/model-routes.d.ts +11 -0
- package/ccw/dist/core/routes/model-routes.d.ts.map +1 -0
- package/ccw/dist/core/routes/model-routes.js +112 -0
- package/ccw/dist/core/routes/model-routes.js.map +1 -0
- package/ccw/dist/core/routes/nav-status-routes.d.ts.map +1 -1
- package/ccw/dist/core/routes/nav-status-routes.js +84 -1
- package/ccw/dist/core/routes/nav-status-routes.js.map +1 -1
- package/ccw/dist/core/routes/provider-routes.d.ts +11 -0
- package/ccw/dist/core/routes/provider-routes.d.ts.map +1 -0
- package/ccw/dist/core/routes/provider-routes.js +67 -0
- package/ccw/dist/core/routes/provider-routes.js.map +1 -0
- package/ccw/dist/core/routes/skills-routes.d.ts.map +1 -1
- package/ccw/dist/core/routes/skills-routes.js +219 -7
- package/ccw/dist/core/routes/skills-routes.js.map +1 -1
- package/ccw/dist/core/routes/system-routes.d.ts.map +1 -1
- package/ccw/dist/core/routes/system-routes.js +58 -6
- package/ccw/dist/core/routes/system-routes.js.map +1 -1
- package/ccw/dist/core/server.d.ts.map +1 -1
- package/ccw/dist/core/server.js +13 -0
- package/ccw/dist/core/server.js.map +1 -1
- package/ccw/dist/mcp-server/index.js +2 -2
- package/ccw/dist/mcp-server/index.js.map +1 -1
- package/ccw/dist/tools/claude-cli-tools.d.ts +48 -11
- package/ccw/dist/tools/claude-cli-tools.d.ts.map +1 -1
- package/ccw/dist/tools/claude-cli-tools.js +146 -50
- package/ccw/dist/tools/claude-cli-tools.js.map +1 -1
- package/ccw/dist/tools/cli-config-manager.d.ts +1 -13
- package/ccw/dist/tools/cli-config-manager.d.ts.map +1 -1
- package/ccw/dist/tools/cli-config-manager.js +3 -27
- package/ccw/dist/tools/cli-config-manager.js.map +1 -1
- package/ccw/dist/tools/cli-executor-core.d.ts.map +1 -1
- package/ccw/dist/tools/cli-executor-core.js +7 -2
- package/ccw/dist/tools/cli-executor-core.js.map +1 -1
- package/ccw/dist/tools/cli-executor-state.d.ts.map +1 -1
- package/ccw/dist/tools/cli-history-store.d.ts +11 -0
- package/ccw/dist/tools/cli-history-store.d.ts.map +1 -1
- package/ccw/dist/tools/cli-history-store.js +82 -2
- package/ccw/dist/tools/cli-history-store.js.map +1 -1
- package/ccw/dist/tools/command-registry.d.ts +7 -0
- package/ccw/dist/tools/command-registry.d.ts.map +1 -1
- package/ccw/dist/tools/command-registry.js +14 -1
- package/ccw/dist/tools/command-registry.js.map +1 -1
- package/ccw/dist/tools/generate-module-docs.d.ts.map +1 -1
- package/ccw/dist/tools/generate-module-docs.js +11 -7
- package/ccw/dist/tools/generate-module-docs.js.map +1 -1
- package/ccw/dist/tools/litellm-executor.d.ts +1 -0
- package/ccw/dist/tools/litellm-executor.d.ts.map +1 -1
- package/ccw/dist/tools/litellm-executor.js +11 -9
- package/ccw/dist/tools/litellm-executor.js.map +1 -1
- package/ccw/dist/types/skill-types.d.ts +97 -0
- package/ccw/dist/types/skill-types.d.ts.map +1 -0
- package/ccw/dist/types/skill-types.js +6 -0
- package/ccw/dist/types/skill-types.js.map +1 -0
- package/ccw/src/commands/cli.ts +36 -5
- package/ccw/src/commands/issue.ts +81 -26
- package/ccw/src/config/litellm-api-config-manager.ts +5 -3
- package/ccw/src/config/litellm-provider-models.ts +222 -0
- package/ccw/src/config/provider-models.ts +91 -190
- package/ccw/src/config/storage-paths.ts +20 -5
- package/ccw/src/core/auth/csrf-middleware.ts +3 -3
- package/ccw/src/core/dashboard-generator.ts +3 -1
- package/ccw/src/core/routes/claude-routes.ts +233 -15
- package/ccw/src/core/routes/cli-routes.ts +2 -3
- package/ccw/src/core/routes/commands-routes.ts +620 -0
- package/ccw/src/core/routes/nav-status-routes.ts +95 -1
- package/ccw/src/core/routes/provider-routes.ts +78 -0
- package/ccw/src/core/routes/skills-routes.ts +266 -45
- package/ccw/src/core/routes/system-routes.ts +102 -50
- package/ccw/src/core/server.ts +13 -0
- package/ccw/src/mcp-server/index.ts +2 -2
- package/ccw/src/templates/dashboard-css/18-cli-settings.css +35 -0
- package/ccw/src/templates/dashboard-css/37-commands.css +193 -0
- package/ccw/src/templates/dashboard-js/components/navigation.js +4 -0
- package/ccw/src/templates/dashboard-js/i18n.js +116 -0
- package/ccw/src/templates/dashboard-js/views/cli-manager.js +249 -4
- package/ccw/src/templates/dashboard-js/views/commands-manager.js +503 -0
- package/ccw/src/templates/dashboard-js/views/issue-manager.js +7 -7
- package/ccw/src/templates/dashboard-js/views/mcp-manager.js +2 -7
- package/ccw/src/templates/dashboard-js/views/skills-manager.js +164 -23
- package/ccw/src/templates/dashboard.html +7 -0
- package/ccw/src/tools/claude-cli-tools.ts +170 -56
- package/ccw/src/tools/cli-config-manager.ts +2 -33
- package/ccw/src/tools/cli-executor-core.ts +8 -2
- package/ccw/src/tools/cli-history-store.ts +92 -2
- package/ccw/src/tools/command-registry.ts +16 -1
- package/ccw/src/tools/generate-module-docs.ts +11 -7
- package/ccw/src/tools/litellm-executor.ts +13 -9
- package/ccw/src/types/skill-types.ts +99 -0
- package/package.json +1 -1
- package/.claude/commands/enhance-prompt.md +0 -93
- package/.claude/commands/memory/code-map-memory.md +0 -687
- package/.claude/commands/memory/docs.md +0 -615
- package/.claude/commands/memory/load-skill-memory.md +0 -182
- package/.claude/commands/memory/skill-memory.md +0 -525
- package/.claude/commands/memory/swagger-docs.md +0 -773
- package/.claude/commands/memory/tech-research-rules.md +0 -310
- package/.claude/commands/memory/workflow-skill-memory.md +0 -517
- package/.claude/commands/task/breakdown.md +0 -208
- package/.claude/commands/task/create.md +0 -152
- package/.claude/commands/task/execute.md +0 -270
- package/.claude/commands/task/replan.md +0 -441
- package/.claude/commands/version.md +0 -254
- package/.claude/commands/workflow/action-plan-verify.md +0 -485
- package/.claude/commands/workflow/brainstorm/api-designer.md +0 -587
- package/.claude/commands/workflow/brainstorm/data-architect.md +0 -220
- package/.claude/commands/workflow/brainstorm/product-manager.md +0 -200
- package/.claude/commands/workflow/brainstorm/product-owner.md +0 -200
- package/.claude/commands/workflow/brainstorm/scrum-master.md +0 -200
- package/.claude/commands/workflow/brainstorm/subject-matter-expert.md +0 -200
- package/.claude/commands/workflow/brainstorm/system-architect.md +0 -389
- package/.claude/commands/workflow/brainstorm/ui-designer.md +0 -221
- package/.claude/commands/workflow/brainstorm/ux-expert.md +0 -221
- package/.claude/commands/workflow/debug.md +0 -331
- package/.claude/commands/workflow/develop-with-file.md +0 -1044
- package/.claude/skills/ccw-loop/README.md +0 -303
- package/.claude/skills/skill-generator/templates/script-bash.md +0 -277
- package/.claude/skills/skill-generator/templates/script-python.md +0 -198
- package/.codex/prompts/debug.md +0 -318
- package/ccw/src/core/routes/mcp-routes.ts.backup +0 -549
|
@@ -1,295 +1,160 @@
|
|
|
1
1
|
# Tuning Strategies
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Fix strategies for each problem category. Implementation patterns + verification methods.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Usage Context
|
|
6
6
|
|
|
7
|
-
| Phase | Usage |
|
|
8
|
-
|
|
9
|
-
| action-propose-fixes | Strategy selection
|
|
10
|
-
| action-apply-fix |
|
|
11
|
-
| action-verify |
|
|
7
|
+
| Phase | Usage |
|
|
8
|
+
|-------|-------|
|
|
9
|
+
| action-propose-fixes | Strategy selection + implementation guidance |
|
|
10
|
+
| action-apply-fix | Apply implementation pattern |
|
|
11
|
+
| action-verify | Run verification method |
|
|
12
12
|
|
|
13
13
|
---
|
|
14
14
|
|
|
15
|
-
##
|
|
15
|
+
## Selection Decision Tree
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
```
|
|
18
|
+
Context Explosion?
|
|
19
|
+
├── history grows unbounded? → sliding_window
|
|
20
|
+
├── full content in prompts? → path_reference
|
|
21
|
+
├── no summarization? → context_summarization
|
|
22
|
+
└── text-based context? → structured_state
|
|
18
23
|
|
|
19
|
-
|
|
24
|
+
Long-tail Forgetting?
|
|
25
|
+
├── constraints not in phases? → constraint_injection
|
|
26
|
+
├── no requirements in state? → state_constraints_field
|
|
27
|
+
├── no recovery points? → checkpoint_restore
|
|
28
|
+
└── goal drift risk? → goal_embedding
|
|
20
29
|
|
|
21
|
-
|
|
30
|
+
Data Flow?
|
|
31
|
+
├── multiple state files? → state_centralization
|
|
32
|
+
├── no validation? → schema_enforcement
|
|
33
|
+
└── inconsistent names? → field_normalization
|
|
22
34
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const step1 = await analyze();
|
|
28
|
-
Write(`${workDir}/step1.json`, JSON.stringify(step1));
|
|
35
|
+
Agent Coordination?
|
|
36
|
+
├── no error handling? → error_wrapping
|
|
37
|
+
├── no result validation? → result_validation
|
|
38
|
+
└── nested agent calls? → flatten_nesting
|
|
29
39
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
Authoring Violation?
|
|
41
|
+
├── intermediate files? → eliminate_intermediate_files
|
|
42
|
+
├── state bloat (>15 fields)? → minimize_state
|
|
43
|
+
├── write→read relay? → context_passing
|
|
44
|
+
└── duplicate storage? → deduplicate_storage
|
|
33
45
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
46
|
+
Token Consumption?
|
|
47
|
+
├── verbose prompts? → prompt_compression
|
|
48
|
+
├── full content passing? → lazy_loading
|
|
49
|
+
├── verbose output? → output_minimization
|
|
50
|
+
├── bloated state? → state_field_reduction
|
|
51
|
+
└── multiple output files? → in_memory_consolidation
|
|
37
52
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return finalize(step2); // 只返回最终结果
|
|
43
|
-
}
|
|
53
|
+
Documentation?
|
|
54
|
+
├── repeated definitions? → consolidate_to_ssot
|
|
55
|
+
├── hardcoded configs? → centralize_mapping_config
|
|
56
|
+
└── conflicting values? → reconcile_conflicting_definitions
|
|
44
57
|
```
|
|
45
58
|
|
|
46
|
-
**Risk**: Low
|
|
47
|
-
**Verification**: `ls ${workDir}` 无 temp/intermediate 文件
|
|
48
|
-
|
|
49
59
|
---
|
|
50
60
|
|
|
51
|
-
|
|
61
|
+
## Authoring Principles Strategies (P0)
|
|
52
62
|
|
|
53
|
-
**
|
|
63
|
+
> **Core Principle**: Simplicity → Remove intermediate files → Context passing
|
|
54
64
|
|
|
55
|
-
|
|
56
|
-
```typescript
|
|
57
|
-
// Before: 膨胀的 State
|
|
58
|
-
interface State {
|
|
59
|
-
status: string;
|
|
60
|
-
target: TargetInfo;
|
|
61
|
-
user_input: string;
|
|
62
|
-
parsed_input: ParsedInput; // 删除 - 只在处理时用
|
|
63
|
-
intermediate_result: any; // 删除 - 中间结果
|
|
64
|
-
debug_info: DebugInfo; // 删除 - 调试信息
|
|
65
|
-
analysis_cache: any; // 删除 - 缓存
|
|
66
|
-
full_history: HistoryEntry[]; // 删除 - 无限增长
|
|
67
|
-
step1_output: any; // 删除 - 中间输出
|
|
68
|
-
step2_output: any; // 删除 - 中间输出
|
|
69
|
-
final_result: FinalResult;
|
|
70
|
-
}
|
|
65
|
+
### eliminate_intermediate_files
|
|
71
66
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
67
|
+
```javascript
|
|
68
|
+
// Before: File relay between steps
|
|
69
|
+
const step1 = await analyze();
|
|
70
|
+
Write(`${workDir}/step1.json`, JSON.stringify(step1));
|
|
71
|
+
const step1Data = JSON.parse(Read(`${workDir}/step1.json`));
|
|
72
|
+
const step2 = await transform(step1Data);
|
|
73
|
+
|
|
74
|
+
// After: Direct context passing
|
|
75
|
+
const step1 = await analyze();
|
|
76
|
+
const step2 = await transform(step1); // No file
|
|
77
|
+
return finalize(step2); // Only final result persisted
|
|
79
78
|
```
|
|
80
79
|
|
|
81
|
-
**
|
|
82
|
-
- State 字段 ≤ 15 个
|
|
83
|
-
- 删除所有 `debug_*`, `*_cache`, `*_temp` 字段
|
|
84
|
-
- `*_history` 数组设置上限或改用滚动窗口
|
|
80
|
+
**Verification**: `ls ${workDir}` — no temp/intermediate files
|
|
85
81
|
|
|
86
|
-
|
|
87
|
-
**Verification**: Count state fields ≤ 15
|
|
82
|
+
### minimize_state
|
|
88
83
|
|
|
89
|
-
|
|
84
|
+
**Rules**: ≤15 fields, delete `debug_*`, `*_cache`, `*_temp`, apply sliding window to `*_history`.
|
|
90
85
|
|
|
91
|
-
|
|
86
|
+
```typescript
|
|
87
|
+
// Before: Bloated
|
|
88
|
+
interface State { status; target; user_input; parsed_input; intermediate_result; debug_info; analysis_cache; full_history; step1_output; step2_output; final_result; ... }
|
|
92
89
|
|
|
93
|
-
|
|
90
|
+
// After: Minimal
|
|
91
|
+
interface State {
|
|
92
|
+
status: 'pending'|'running'|'completed'|'failed';
|
|
93
|
+
target: { name: string; path: string };
|
|
94
|
+
result_path: string;
|
|
95
|
+
error?: string;
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### context_passing
|
|
94
100
|
|
|
95
|
-
**Implementation**:
|
|
96
101
|
```javascript
|
|
97
|
-
// 上下文流转模式
|
|
98
102
|
async function executeWorkflow(initialContext) {
|
|
99
103
|
let ctx = initialContext;
|
|
100
|
-
|
|
101
|
-
//
|
|
102
|
-
ctx = await executePhase1(ctx);
|
|
103
|
-
|
|
104
|
-
// Phase 2: 继续传递
|
|
105
|
-
ctx = await executePhase2(ctx);
|
|
106
|
-
|
|
107
|
-
// Phase 3: 最终处理
|
|
104
|
+
ctx = await executePhase1(ctx); // Pass context directly
|
|
105
|
+
ctx = await executePhase2(ctx); // Continue passing
|
|
108
106
|
const result = await executePhase3(ctx);
|
|
109
|
-
|
|
110
|
-
// 只存最终结果
|
|
111
|
-
Write(`${ctx.workDir}/result.json`, JSON.stringify(result));
|
|
112
|
-
|
|
107
|
+
Write(`${ctx.workDir}/result.json`, JSON.stringify(result)); // Only final
|
|
113
108
|
return result;
|
|
114
109
|
}
|
|
115
|
-
|
|
116
|
-
// Phase 函数模板
|
|
117
|
-
async function executePhaseN(ctx) {
|
|
118
|
-
const { previousResult, constraints } = ctx;
|
|
119
|
-
|
|
120
|
-
const result = await Task({
|
|
121
|
-
prompt: `
|
|
122
|
-
[CONTEXT]
|
|
123
|
-
${JSON.stringify(previousResult)}
|
|
124
|
-
|
|
125
|
-
[TASK]
|
|
126
|
-
Process and return result.
|
|
127
|
-
`
|
|
128
|
-
});
|
|
129
|
-
|
|
130
|
-
// 返回更新后的上下文,不写文件
|
|
131
|
-
return {
|
|
132
|
-
...ctx,
|
|
133
|
-
previousResult: result,
|
|
134
|
-
completed: [...ctx.completed, 'phase-n']
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
110
|
```
|
|
138
111
|
|
|
139
|
-
|
|
140
|
-
**Verification**: 无 Write→Read 紧邻模式
|
|
112
|
+
### deduplicate_storage
|
|
141
113
|
|
|
142
|
-
---
|
|
143
|
-
|
|
144
|
-
### Strategy: deduplicate_storage
|
|
145
|
-
|
|
146
|
-
**Purpose**: 消除重复数据存储。
|
|
147
|
-
|
|
148
|
-
**Implementation**:
|
|
149
114
|
```javascript
|
|
150
|
-
// Before:
|
|
151
|
-
state.
|
|
152
|
-
state.original_request = userInput;
|
|
153
|
-
state.input_text = userInput;
|
|
154
|
-
|
|
155
|
-
// After: 单一来源
|
|
156
|
-
state.input = userInput; // 唯一存储点
|
|
115
|
+
// Before: state.user_request = state.original_request = state.input_text = input
|
|
116
|
+
// After: state.input = input; // Single source
|
|
157
117
|
```
|
|
158
118
|
|
|
159
|
-
**Risk**: Low
|
|
160
|
-
**Verification**: 无相同数据多字段存储
|
|
161
|
-
|
|
162
119
|
---
|
|
163
120
|
|
|
164
121
|
## Context Explosion Strategies
|
|
165
122
|
|
|
166
|
-
###
|
|
167
|
-
|
|
168
|
-
**Purpose**: Limit context history to most recent N items.
|
|
123
|
+
### sliding_window
|
|
169
124
|
|
|
170
|
-
**Implementation**:
|
|
171
125
|
```javascript
|
|
172
|
-
|
|
173
|
-
const MAX_HISTORY_ITEMS = 5;
|
|
174
|
-
|
|
126
|
+
const MAX_HISTORY = 5;
|
|
175
127
|
function updateHistory(state, newItem) {
|
|
176
|
-
|
|
177
|
-
const updated = [...history, newItem].slice(-MAX_HISTORY_ITEMS);
|
|
178
|
-
return { ...state, history: updated };
|
|
128
|
+
return { ...state, history: [...(state.history || []), newItem].slice(-MAX_HISTORY) };
|
|
179
129
|
}
|
|
180
130
|
```
|
|
181
131
|
|
|
182
|
-
|
|
183
|
-
- `phases/orchestrator.md` - Add history management
|
|
184
|
-
- `phases/state-schema.md` - Document history limit
|
|
132
|
+
### path_reference
|
|
185
133
|
|
|
186
|
-
**Risk**: Low
|
|
187
|
-
**Verification**:
|
|
188
|
-
- Run skill for 10+ iterations
|
|
189
|
-
- Verify history.length never exceeds MAX_HISTORY_ITEMS
|
|
190
|
-
|
|
191
|
-
---
|
|
192
|
-
|
|
193
|
-
### Strategy: path_reference
|
|
194
|
-
|
|
195
|
-
**Purpose**: Pass file paths instead of full content.
|
|
196
|
-
|
|
197
|
-
**Implementation**:
|
|
198
134
|
```javascript
|
|
199
|
-
// Before
|
|
200
|
-
const
|
|
201
|
-
const prompt = `Analyze: ${content}`;
|
|
202
|
-
|
|
203
|
-
// After
|
|
204
|
-
const dataPath = `${workDir}/data.json`;
|
|
205
|
-
const prompt = `Analyze file at: ${dataPath}. Read it first.`;
|
|
135
|
+
// Before: const prompt = `Analyze: ${Read('data.json')}`;
|
|
136
|
+
// After: const prompt = `Analyze file at: ${dataPath}. Read it first.`;
|
|
206
137
|
```
|
|
207
138
|
|
|
208
|
-
|
|
209
|
-
- All phase files with `${content}` in prompts
|
|
139
|
+
### context_summarization
|
|
210
140
|
|
|
211
|
-
**Risk**: Low
|
|
212
|
-
**Verification**:
|
|
213
|
-
- Verify agents can still access required data
|
|
214
|
-
- Check token count reduced
|
|
215
|
-
|
|
216
|
-
---
|
|
217
|
-
|
|
218
|
-
### Strategy: context_summarization
|
|
219
|
-
|
|
220
|
-
**Purpose**: Add summarization step before passing to next phase.
|
|
221
|
-
|
|
222
|
-
**Implementation**:
|
|
223
141
|
```javascript
|
|
224
|
-
// Add summarization
|
|
225
|
-
const
|
|
142
|
+
// Add summarization before passing to next phase
|
|
143
|
+
const summary = await Task({
|
|
226
144
|
subagent_type: 'universal-executor',
|
|
227
|
-
prompt: `
|
|
228
|
-
Summarize the following in <100 words, preserving key facts:
|
|
229
|
-
${fullContent}
|
|
230
|
-
|
|
231
|
-
Return JSON: { summary: "...", key_points: [...] }
|
|
232
|
-
`
|
|
145
|
+
prompt: `Summarize in <100 words: ${fullContent}\nReturn JSON: { summary, key_points[] }`
|
|
233
146
|
});
|
|
234
|
-
|
|
235
|
-
// Pass summary instead of full content
|
|
236
|
-
nextPhasePrompt = `Previous phase summary: ${summarizeResult.summary}`;
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
**Files to Modify**:
|
|
240
|
-
- Phase transition points
|
|
241
|
-
- Orchestrator (if autonomous)
|
|
242
|
-
|
|
243
|
-
**Risk**: Low
|
|
244
|
-
**Verification**:
|
|
245
|
-
- Compare output quality with/without summarization
|
|
246
|
-
- Verify key information preserved
|
|
247
|
-
|
|
248
|
-
---
|
|
249
|
-
|
|
250
|
-
### Strategy: structured_state
|
|
251
|
-
|
|
252
|
-
**Purpose**: Replace text-based context with structured JSON state.
|
|
253
|
-
|
|
254
|
-
**Implementation**:
|
|
255
|
-
```javascript
|
|
256
|
-
// Before: Text-based context passing
|
|
257
|
-
const context = `
|
|
258
|
-
User requested: ${userRequest}
|
|
259
|
-
Previous output: ${previousOutput}
|
|
260
|
-
Current status: ${status}
|
|
261
|
-
`;
|
|
262
|
-
|
|
263
|
-
// After: Structured state
|
|
264
|
-
const state = {
|
|
265
|
-
original_request: userRequest,
|
|
266
|
-
previous_output_path: `${workDir}/output.md`,
|
|
267
|
-
previous_output_summary: "...",
|
|
268
|
-
status: status,
|
|
269
|
-
key_decisions: [...]
|
|
270
|
-
};
|
|
147
|
+
nextPhasePrompt = `Previous summary: ${summary.summary}`;
|
|
271
148
|
```
|
|
272
149
|
|
|
273
|
-
**Files to Modify**:
|
|
274
|
-
- `phases/state-schema.md` - Define structure
|
|
275
|
-
- All phases - Use structured fields
|
|
276
|
-
|
|
277
|
-
**Risk**: Medium (requires refactoring)
|
|
278
|
-
**Verification**:
|
|
279
|
-
- Verify all phases can access required state fields
|
|
280
|
-
- Check backward compatibility
|
|
281
|
-
|
|
282
150
|
---
|
|
283
151
|
|
|
284
152
|
## Long-tail Forgetting Strategies
|
|
285
153
|
|
|
286
|
-
###
|
|
154
|
+
### constraint_injection
|
|
287
155
|
|
|
288
|
-
**Purpose**: Inject original constraints into every phase prompt.
|
|
289
|
-
|
|
290
|
-
**Implementation**:
|
|
291
156
|
```javascript
|
|
292
|
-
// Add to
|
|
157
|
+
// Add to EVERY phase prompt
|
|
293
158
|
const phasePrompt = `
|
|
294
159
|
[CONSTRAINTS - FROM ORIGINAL REQUEST]
|
|
295
160
|
${state.original_requirements.map(r => `- ${r}`).join('\n')}
|
|
@@ -297,1241 +162,224 @@ ${state.original_requirements.map(r => `- ${r}`).join('\n')}
|
|
|
297
162
|
[CURRENT TASK]
|
|
298
163
|
${taskDescription}
|
|
299
164
|
|
|
300
|
-
[REMINDER]
|
|
301
|
-
Output MUST satisfy all constraints listed above.
|
|
165
|
+
[REMINDER] Output MUST satisfy all constraints above.
|
|
302
166
|
`;
|
|
303
167
|
```
|
|
304
168
|
|
|
305
|
-
|
|
306
|
-
- All `phases/*.md` files
|
|
307
|
-
- `templates/agent-base.md` (if exists)
|
|
308
|
-
|
|
309
|
-
**Risk**: Low
|
|
310
|
-
**Verification**:
|
|
311
|
-
- Verify constraints visible in each phase
|
|
312
|
-
- Test with specific constraint, verify output respects it
|
|
313
|
-
|
|
314
|
-
---
|
|
169
|
+
### state_constraints_field
|
|
315
170
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
**Purpose**: Add dedicated field in state schema for requirements.
|
|
319
|
-
|
|
320
|
-
**Implementation**:
|
|
321
|
-
```typescript
|
|
322
|
-
// In state-schema.md
|
|
323
|
-
interface State {
|
|
324
|
-
// Add these fields
|
|
325
|
-
original_requirements: string[]; // User's original constraints
|
|
326
|
-
goal_summary: string; // One-line goal statement
|
|
327
|
-
constraint_violations: string[]; // Track any violations
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// In action-init.md
|
|
331
|
-
function initState(userInput) {
|
|
332
|
-
return {
|
|
333
|
-
original_requirements: extractRequirements(userInput),
|
|
334
|
-
goal_summary: summarizeGoal(userInput),
|
|
335
|
-
constraint_violations: []
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
**Files to Modify**:
|
|
341
|
-
- `phases/state-schema.md`
|
|
342
|
-
- `phases/actions/action-init.md`
|
|
343
|
-
|
|
344
|
-
**Risk**: Low
|
|
345
|
-
**Verification**:
|
|
346
|
-
- Verify state.json contains requirements after init
|
|
347
|
-
- Check requirements persist through all phases
|
|
348
|
-
|
|
349
|
-
---
|
|
350
|
-
|
|
351
|
-
### Strategy: checkpoint_restore
|
|
352
|
-
|
|
353
|
-
**Purpose**: Save state at key milestones for recovery and verification.
|
|
354
|
-
|
|
355
|
-
**Implementation**:
|
|
171
|
+
Add to state-schema + action-init:
|
|
356
172
|
```javascript
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const checkpointPath = `${workDir}/checkpoints/${checkpointName}.json`;
|
|
360
|
-
Write(checkpointPath, JSON.stringify({
|
|
361
|
-
state: state,
|
|
362
|
-
timestamp: new Date().toISOString(),
|
|
363
|
-
name: checkpointName
|
|
364
|
-
}, null, 2));
|
|
365
|
-
return checkpointPath;
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// Use at key points
|
|
369
|
-
await executePhase2();
|
|
370
|
-
createCheckpoint(state, workDir, 'after-phase-2');
|
|
173
|
+
state.original_requirements = extractRequirements(userInput);
|
|
174
|
+
state.goal_summary = summarizeGoal(userInput);
|
|
371
175
|
```
|
|
372
176
|
|
|
373
|
-
|
|
374
|
-
- `phases/orchestrator.md`
|
|
375
|
-
- Key phase files
|
|
177
|
+
### checkpoint_restore
|
|
376
178
|
|
|
377
|
-
**Risk**: Low
|
|
378
|
-
**Verification**:
|
|
379
|
-
- Verify checkpoints created at expected points
|
|
380
|
-
- Test restore from checkpoint
|
|
381
|
-
|
|
382
|
-
---
|
|
383
|
-
|
|
384
|
-
### Strategy: goal_embedding
|
|
385
|
-
|
|
386
|
-
**Purpose**: Track semantic similarity to original goal throughout execution.
|
|
387
|
-
|
|
388
|
-
**Implementation**:
|
|
389
179
|
```javascript
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
const currentPlanEmbedding = await embed(currentPlan);
|
|
395
|
-
const similarity = cosineSimilarity(state.goal_embedding, currentPlanEmbedding);
|
|
396
|
-
|
|
397
|
-
if (similarity < 0.7) {
|
|
398
|
-
console.warn('Goal drift detected! Similarity:', similarity);
|
|
399
|
-
// Trigger re-alignment
|
|
180
|
+
function createCheckpoint(state, workDir, name) {
|
|
181
|
+
Write(`${workDir}/checkpoints/${name}.json`, JSON.stringify({
|
|
182
|
+
state, timestamp: new Date().toISOString(), name
|
|
183
|
+
}));
|
|
400
184
|
}
|
|
185
|
+
// Use at key phase boundaries
|
|
401
186
|
```
|
|
402
187
|
|
|
403
|
-
**Files to Modify**:
|
|
404
|
-
- State schema (add embedding field)
|
|
405
|
-
- Orchestrator (add similarity check)
|
|
406
|
-
|
|
407
|
-
**Risk**: Medium (requires embedding infrastructure)
|
|
408
|
-
**Verification**:
|
|
409
|
-
- Test with intentional drift, verify detection
|
|
410
|
-
- Verify false positive rate acceptable
|
|
411
|
-
|
|
412
188
|
---
|
|
413
189
|
|
|
414
190
|
## Data Flow Strategies
|
|
415
191
|
|
|
416
|
-
###
|
|
417
|
-
|
|
418
|
-
**Purpose**: Use single state.json for all persistent data.
|
|
192
|
+
### state_centralization
|
|
419
193
|
|
|
420
|
-
**Implementation**:
|
|
421
194
|
```javascript
|
|
422
|
-
//
|
|
195
|
+
// Single state manager — replace all direct writes
|
|
423
196
|
const StateManager = {
|
|
424
|
-
read: (
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const next = { ...current, ...updates, updated_at: new Date().toISOString() };
|
|
429
|
-
Write(`${workDir}/state.json`, JSON.stringify(next, null, 2));
|
|
197
|
+
read: (dir) => JSON.parse(Read(`${dir}/state.json`)),
|
|
198
|
+
update: (dir, updates) => {
|
|
199
|
+
const next = { ...StateManager.read(dir), ...updates, updated_at: Date.now() };
|
|
200
|
+
Write(`${dir}/state.json`, JSON.stringify(next, null, 2));
|
|
430
201
|
return next;
|
|
431
|
-
},
|
|
432
|
-
|
|
433
|
-
get: (workDir, path) => {
|
|
434
|
-
const state = StateManager.read(workDir);
|
|
435
|
-
return path.split('.').reduce((obj, key) => obj?.[key], state);
|
|
436
202
|
}
|
|
437
203
|
};
|
|
438
|
-
|
|
439
|
-
// Replace direct writes
|
|
440
|
-
// Before: Write(`${workDir}/config.json`, config);
|
|
441
|
-
// After: StateManager.update(workDir, { config });
|
|
442
204
|
```
|
|
443
205
|
|
|
444
|
-
|
|
445
|
-
- All phases that write state
|
|
446
|
-
- Create shared state manager
|
|
206
|
+
### schema_enforcement
|
|
447
207
|
|
|
448
|
-
**Risk**: Medium (significant refactoring)
|
|
449
|
-
**Verification**:
|
|
450
|
-
- Verify single state.json after full run
|
|
451
|
-
- Check no orphan state files
|
|
452
|
-
|
|
453
|
-
---
|
|
454
|
-
|
|
455
|
-
### Strategy: schema_enforcement
|
|
456
|
-
|
|
457
|
-
**Purpose**: Add runtime validation using Zod or similar.
|
|
458
|
-
|
|
459
|
-
**Implementation**:
|
|
460
208
|
```javascript
|
|
461
|
-
// Define schema (in state-schema.md)
|
|
462
|
-
const StateSchema = {
|
|
463
|
-
status: ['pending', 'running', 'completed', 'failed'],
|
|
464
|
-
target_skill: {
|
|
465
|
-
name: 'string',
|
|
466
|
-
path: 'string'
|
|
467
|
-
},
|
|
468
|
-
// ... full schema
|
|
469
|
-
};
|
|
470
|
-
|
|
471
209
|
function validateState(state) {
|
|
472
210
|
const errors = [];
|
|
473
|
-
|
|
474
|
-
if (!StateSchema.status.includes(state.status)) {
|
|
211
|
+
if (!['pending','running','completed','failed'].includes(state.status))
|
|
475
212
|
errors.push(`Invalid status: ${state.status}`);
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
if (typeof state.target_skill?.name !== 'string') {
|
|
213
|
+
if (typeof state.target_skill?.name !== 'string')
|
|
479
214
|
errors.push('target_skill.name must be string');
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
if (errors.length > 0) {
|
|
483
|
-
throw new Error(`State validation failed:\n${errors.join('\n')}`);
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
return true;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// Use before state write
|
|
490
|
-
function updateState(workDir, updates) {
|
|
491
|
-
const newState = { ...currentState, ...updates };
|
|
492
|
-
validateState(newState); // Throws if invalid
|
|
493
|
-
Write(`${workDir}/state.json`, JSON.stringify(newState, null, 2));
|
|
215
|
+
if (errors.length) throw new Error(`Validation failed:\n${errors.join('\n')}`);
|
|
494
216
|
}
|
|
217
|
+
// Call before every state write
|
|
495
218
|
```
|
|
496
219
|
|
|
497
|
-
|
|
498
|
-
- `phases/state-schema.md` - Add validation function
|
|
499
|
-
- All state write locations
|
|
500
|
-
|
|
501
|
-
**Risk**: Low
|
|
502
|
-
**Verification**:
|
|
503
|
-
- Test with invalid state, verify rejection
|
|
504
|
-
- Verify valid state accepted
|
|
505
|
-
|
|
506
|
-
---
|
|
507
|
-
|
|
508
|
-
### Strategy: field_normalization
|
|
509
|
-
|
|
510
|
-
**Purpose**: Normalize field names across all phases.
|
|
220
|
+
### field_normalization
|
|
511
221
|
|
|
512
|
-
**Implementation**:
|
|
513
222
|
```javascript
|
|
514
|
-
|
|
515
|
-
const FIELD_NORMALIZATIONS = {
|
|
516
|
-
'title': 'name',
|
|
517
|
-
'identifier': 'id',
|
|
518
|
-
'state': 'status',
|
|
519
|
-
'error': 'errors'
|
|
520
|
-
};
|
|
521
|
-
|
|
223
|
+
const NORMALIZATIONS = { 'title': 'name', 'identifier': 'id', 'state': 'status' };
|
|
522
224
|
function normalizeData(data) {
|
|
523
|
-
if (typeof data !== 'object' || data
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
const normalizedKey = FIELD_NORMALIZATIONS[key] || key;
|
|
528
|
-
normalized[normalizedKey] = normalizeData(value);
|
|
529
|
-
}
|
|
530
|
-
return normalized;
|
|
225
|
+
if (typeof data !== 'object' || !data) return data;
|
|
226
|
+
return Object.fromEntries(
|
|
227
|
+
Object.entries(data).map(([k, v]) => [NORMALIZATIONS[k] || k, normalizeData(v)])
|
|
228
|
+
);
|
|
531
229
|
}
|
|
532
|
-
|
|
533
|
-
// Apply when reading external data
|
|
534
|
-
const rawData = JSON.parse(Read(filePath));
|
|
535
|
-
const normalizedData = normalizeData(rawData);
|
|
536
230
|
```
|
|
537
231
|
|
|
538
|
-
**Files to Modify**:
|
|
539
|
-
- Data ingestion points
|
|
540
|
-
- State update functions
|
|
541
|
-
|
|
542
|
-
**Risk**: Low
|
|
543
|
-
**Verification**:
|
|
544
|
-
- Verify consistent field names in state
|
|
545
|
-
- Check no data loss during normalization
|
|
546
|
-
|
|
547
232
|
---
|
|
548
233
|
|
|
549
234
|
## Agent Coordination Strategies
|
|
550
235
|
|
|
551
|
-
###
|
|
236
|
+
### error_wrapping
|
|
552
237
|
|
|
553
|
-
**Purpose**: Add try-catch to all Task calls.
|
|
554
|
-
|
|
555
|
-
**Implementation**:
|
|
556
238
|
```javascript
|
|
557
|
-
// Wrapper function
|
|
558
239
|
async function safeTask(config, state, updateState) {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
240
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
562
241
|
try {
|
|
563
242
|
const result = await Task(config);
|
|
564
|
-
|
|
565
|
-
// Validate result
|
|
566
|
-
if (!result) throw new Error('Empty result from agent');
|
|
567
|
-
|
|
243
|
+
if (!result) throw new Error('Empty result');
|
|
568
244
|
return result;
|
|
569
245
|
} catch (error) {
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
if (attempt === maxRetries) {
|
|
573
|
-
updateState({
|
|
574
|
-
errors: [...state.errors, {
|
|
575
|
-
action: config.subagent_type,
|
|
576
|
-
message: error.message,
|
|
577
|
-
timestamp: new Date().toISOString()
|
|
578
|
-
}],
|
|
579
|
-
error_count: state.error_count + 1
|
|
580
|
-
});
|
|
246
|
+
if (attempt === 3) {
|
|
247
|
+
updateState({ error_count: state.error_count + 1 });
|
|
581
248
|
throw error;
|
|
582
249
|
}
|
|
583
|
-
|
|
584
|
-
// Wait before retry
|
|
585
250
|
await new Promise(r => setTimeout(r, 1000 * attempt));
|
|
586
251
|
}
|
|
587
252
|
}
|
|
588
253
|
}
|
|
589
254
|
```
|
|
590
255
|
|
|
591
|
-
|
|
592
|
-
- All files with Task calls
|
|
593
|
-
|
|
594
|
-
**Risk**: Low
|
|
595
|
-
**Verification**:
|
|
596
|
-
- Simulate agent failure, verify graceful handling
|
|
597
|
-
- Verify retry logic works
|
|
598
|
-
|
|
599
|
-
---
|
|
600
|
-
|
|
601
|
-
### Strategy: result_validation
|
|
256
|
+
### result_validation
|
|
602
257
|
|
|
603
|
-
**Purpose**: Validate agent returns before use.
|
|
604
|
-
|
|
605
|
-
**Implementation**:
|
|
606
258
|
```javascript
|
|
607
|
-
function validateAgentResult(result,
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
parsed = typeof result === 'string' ? JSON.parse(result) : result;
|
|
612
|
-
} catch (e) {
|
|
613
|
-
throw new Error(`Agent result is not valid JSON: ${result.slice(0, 100)}`);
|
|
259
|
+
function validateAgentResult(result, requiredFields) {
|
|
260
|
+
const parsed = typeof result === 'string' ? JSON.parse(result) : result;
|
|
261
|
+
for (const field of requiredFields) {
|
|
262
|
+
if (!(field in parsed)) throw new Error(`Missing: ${field}`);
|
|
614
263
|
}
|
|
615
|
-
|
|
616
|
-
// Check required fields
|
|
617
|
-
for (const field of expectedSchema.required || []) {
|
|
618
|
-
if (!(field in parsed)) {
|
|
619
|
-
throw new Error(`Missing required field: ${field}`);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
|
|
623
264
|
return parsed;
|
|
624
265
|
}
|
|
625
|
-
|
|
626
|
-
// Usage
|
|
627
|
-
const rawResult = await Task({...});
|
|
628
|
-
const validResult = validateAgentResult(rawResult, {
|
|
629
|
-
required: ['status', 'output_file']
|
|
630
|
-
});
|
|
631
266
|
```
|
|
632
267
|
|
|
633
|
-
|
|
634
|
-
- All locations where agent results are used
|
|
635
|
-
|
|
636
|
-
**Risk**: Low
|
|
637
|
-
**Verification**:
|
|
638
|
-
- Test with invalid agent output
|
|
639
|
-
- Verify proper error messages
|
|
640
|
-
|
|
641
|
-
---
|
|
642
|
-
|
|
643
|
-
### Strategy: flatten_nesting
|
|
644
|
-
|
|
645
|
-
**Purpose**: Remove nested agent calls, use orchestrator coordination.
|
|
268
|
+
### flatten_nesting
|
|
646
269
|
|
|
647
|
-
**Implementation**:
|
|
648
270
|
```javascript
|
|
649
|
-
// Before: Agent A
|
|
650
|
-
// Agent A prompt: "... then call Task({subagent_type: 'B', ...}) ..."
|
|
651
|
-
|
|
271
|
+
// Before: Agent A's prompt tells it to call Task({subagent_type: 'B'})
|
|
652
272
|
// After: Agent A returns signal, orchestrator handles
|
|
653
|
-
// Agent A
|
|
654
|
-
|
|
655
|
-
// Orchestrator handles:
|
|
656
|
-
const resultA = await Task({ subagent_type: 'A', ... });
|
|
657
|
-
const parsedA = JSON.parse(resultA);
|
|
658
|
-
|
|
273
|
+
// Agent A: return { needs_agent_b: true, context: {...} }
|
|
274
|
+
// Orchestrator:
|
|
659
275
|
if (parsedA.needs_agent_b) {
|
|
660
|
-
|
|
661
|
-
subagent_type: 'B',
|
|
662
|
-
prompt: `Continue analysis with context: ${JSON.stringify(parsedA.context)}`
|
|
663
|
-
});
|
|
664
|
-
}
|
|
665
|
-
```
|
|
666
|
-
|
|
667
|
-
**Files to Modify**:
|
|
668
|
-
- Phase files with nested Task calls
|
|
669
|
-
- Orchestrator decision logic
|
|
670
|
-
|
|
671
|
-
**Risk**: Medium (may change agent behavior)
|
|
672
|
-
**Verification**:
|
|
673
|
-
- Verify no nested Task patterns
|
|
674
|
-
- Test agent chain via orchestrator
|
|
675
|
-
|
|
676
|
-
---
|
|
677
|
-
|
|
678
|
-
## Documentation Strategies
|
|
679
|
-
|
|
680
|
-
文档去重和冲突解决策略。
|
|
681
|
-
|
|
682
|
-
---
|
|
683
|
-
|
|
684
|
-
### Strategy: consolidate_to_ssot
|
|
685
|
-
|
|
686
|
-
**Purpose**: 将重复定义合并到单一真相来源 (Single Source of Truth)。
|
|
687
|
-
|
|
688
|
-
**Implementation**:
|
|
689
|
-
```javascript
|
|
690
|
-
// 合并流程
|
|
691
|
-
async function consolidateToSSOT(state, duplicates) {
|
|
692
|
-
// 1. 识别最完整的定义位置
|
|
693
|
-
const canonical = selectCanonicalSource(duplicates);
|
|
694
|
-
|
|
695
|
-
// 2. 确保规范位置包含完整定义
|
|
696
|
-
const fullDefinition = mergeDefinitions(duplicates);
|
|
697
|
-
Write(canonical.file, fullDefinition);
|
|
698
|
-
|
|
699
|
-
// 3. 替换其他位置为引用
|
|
700
|
-
for (const dup of duplicates.filter(d => d.file !== canonical.file)) {
|
|
701
|
-
const reference = generateReference(canonical.file, dup.type);
|
|
702
|
-
// 例如: "详见 [state-schema.md](phases/state-schema.md)"
|
|
703
|
-
replaceWithReference(dup.file, dup.location, reference);
|
|
704
|
-
}
|
|
705
|
-
|
|
706
|
-
return { canonical: canonical.file, removed: duplicates.length - 1 };
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
function selectCanonicalSource(duplicates) {
|
|
710
|
-
// 优先级: specs/ > phases/ > SKILL.md
|
|
711
|
-
const priority = ['specs/', 'phases/', 'SKILL.md'];
|
|
712
|
-
return duplicates.sort((a, b) => {
|
|
713
|
-
const aIdx = priority.findIndex(p => a.file.includes(p));
|
|
714
|
-
const bIdx = priority.findIndex(p => b.file.includes(p));
|
|
715
|
-
return aIdx - bIdx;
|
|
716
|
-
})[0];
|
|
717
|
-
}
|
|
718
|
-
```
|
|
719
|
-
|
|
720
|
-
**Risk**: Low
|
|
721
|
-
**Verification**:
|
|
722
|
-
- 确认只有一处包含完整定义
|
|
723
|
-
- 其他位置包含有效引用链接
|
|
724
|
-
|
|
725
|
-
---
|
|
726
|
-
|
|
727
|
-
### Strategy: centralize_mapping_config
|
|
728
|
-
|
|
729
|
-
**Purpose**: 将硬编码配置提取到集中的 JSON 文件,代码改为加载配置。
|
|
730
|
-
|
|
731
|
-
**Implementation**:
|
|
732
|
-
```javascript
|
|
733
|
-
// 1. 创建集中配置文件
|
|
734
|
-
const config = {
|
|
735
|
-
version: "1.0.0",
|
|
736
|
-
categories: {
|
|
737
|
-
context_explosion: {
|
|
738
|
-
pattern_ids: ["CTX-001", "CTX-002"],
|
|
739
|
-
strategies: ["sliding_window", "path_reference"]
|
|
740
|
-
}
|
|
741
|
-
// ... 从硬编码中提取
|
|
742
|
-
}
|
|
743
|
-
};
|
|
744
|
-
Write('specs/category-mappings.json', JSON.stringify(config, null, 2));
|
|
745
|
-
|
|
746
|
-
// 2. 重构代码加载配置
|
|
747
|
-
// Before:
|
|
748
|
-
function findTaxonomyMatch(category) {
|
|
749
|
-
const patternMapping = {
|
|
750
|
-
'context_explosion': { category: 'context_explosion', pattern_ids: [...] }
|
|
751
|
-
// 硬编码
|
|
752
|
-
};
|
|
753
|
-
return patternMapping[category];
|
|
276
|
+
resultB = await Task({ subagent_type: 'B', prompt: `Context: ${parsedA.context}` });
|
|
754
277
|
}
|
|
755
|
-
|
|
756
|
-
// After:
|
|
757
|
-
function findTaxonomyMatch(category) {
|
|
758
|
-
const mappings = JSON.parse(Read('specs/category-mappings.json'));
|
|
759
|
-
const config = mappings.categories[category];
|
|
760
|
-
if (!config) return null;
|
|
761
|
-
return { category, pattern_ids: config.pattern_ids, severity_hint: config.severity_hint };
|
|
762
|
-
}
|
|
763
|
-
```
|
|
764
|
-
|
|
765
|
-
**Risk**: Medium (需要测试配置加载逻辑)
|
|
766
|
-
**Verification**:
|
|
767
|
-
- JSON 文件语法正确
|
|
768
|
-
- 所有原硬编码的值都已迁移
|
|
769
|
-
- 功能行为不变
|
|
770
|
-
|
|
771
|
-
---
|
|
772
|
-
|
|
773
|
-
### Strategy: reconcile_conflicting_definitions
|
|
774
|
-
|
|
775
|
-
**Purpose**: 调和冲突的定义,由用户选择正确版本后统一更新。
|
|
776
|
-
|
|
777
|
-
**Implementation**:
|
|
778
|
-
```javascript
|
|
779
|
-
async function reconcileConflicts(conflicts) {
|
|
780
|
-
for (const conflict of conflicts) {
|
|
781
|
-
// 1. 展示冲突给用户
|
|
782
|
-
const options = conflict.definitions.map(def => ({
|
|
783
|
-
label: `${def.file}: ${def.value}`,
|
|
784
|
-
description: `来自 ${def.file}`
|
|
785
|
-
}));
|
|
786
|
-
|
|
787
|
-
const choice = await AskUserQuestion({
|
|
788
|
-
questions: [{
|
|
789
|
-
question: `发现冲突定义: "${conflict.key}",请选择正确版本`,
|
|
790
|
-
header: '冲突解决',
|
|
791
|
-
options: options,
|
|
792
|
-
multiSelect: false
|
|
793
|
-
}]
|
|
794
|
-
});
|
|
795
|
-
|
|
796
|
-
// 2. 更新所有文件为选中的版本
|
|
797
|
-
const selected = conflict.definitions[choice.index];
|
|
798
|
-
for (const def of conflict.definitions) {
|
|
799
|
-
if (def.file !== selected.file) {
|
|
800
|
-
updateDefinition(def.file, conflict.key, selected.value);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
return { resolved: conflicts.length };
|
|
806
|
-
}
|
|
807
|
-
```
|
|
808
|
-
|
|
809
|
-
**Risk**: Low (用户确认后执行)
|
|
810
|
-
**Verification**:
|
|
811
|
-
- 所有位置的定义一致
|
|
812
|
-
- 无新冲突产生
|
|
813
|
-
|
|
814
|
-
---
|
|
815
|
-
|
|
816
|
-
## Strategy Selection Guide
|
|
817
|
-
|
|
818
|
-
```
|
|
819
|
-
Issue Type: Context Explosion
|
|
820
|
-
├── history grows unbounded? → sliding_window
|
|
821
|
-
├── full content in prompts? → path_reference
|
|
822
|
-
├── no summarization? → context_summarization
|
|
823
|
-
└── text-based context? → structured_state
|
|
824
|
-
|
|
825
|
-
Issue Type: Long-tail Forgetting
|
|
826
|
-
├── constraints not in phases? → constraint_injection
|
|
827
|
-
├── no requirements in state? → state_constraints_field
|
|
828
|
-
├── no recovery points? → checkpoint_restore
|
|
829
|
-
└── goal drift risk? → goal_embedding
|
|
830
|
-
|
|
831
|
-
Issue Type: Data Flow
|
|
832
|
-
├── multiple state files? → state_centralization
|
|
833
|
-
├── no validation? → schema_enforcement
|
|
834
|
-
└── inconsistent names? → field_normalization
|
|
835
|
-
|
|
836
|
-
Issue Type: Agent Coordination
|
|
837
|
-
├── no error handling? → error_wrapping
|
|
838
|
-
├── no result validation? → result_validation
|
|
839
|
-
└── nested agent calls? → flatten_nesting
|
|
840
|
-
|
|
841
|
-
Issue Type: Prompt Engineering
|
|
842
|
-
├── vague instructions? → structured_prompt
|
|
843
|
-
├── inconsistent output? → output_schema
|
|
844
|
-
├── hallucination risk? → grounding_context
|
|
845
|
-
└── format drift? → format_enforcement
|
|
846
|
-
|
|
847
|
-
Issue Type: Architecture
|
|
848
|
-
├── unclear responsibilities? → phase_decomposition
|
|
849
|
-
├── tight coupling? → interface_contracts
|
|
850
|
-
├── poor extensibility? → plugin_architecture
|
|
851
|
-
└── complex flow? → state_machine
|
|
852
|
-
|
|
853
|
-
Issue Type: Performance
|
|
854
|
-
├── high token usage? → token_budgeting
|
|
855
|
-
├── slow execution? → parallel_execution
|
|
856
|
-
├── redundant computation? → result_caching
|
|
857
|
-
└── large files? → lazy_loading
|
|
858
|
-
|
|
859
|
-
Issue Type: Error Handling
|
|
860
|
-
├── no recovery? → graceful_degradation
|
|
861
|
-
├── silent failures? → error_propagation
|
|
862
|
-
├── no logging? → structured_logging
|
|
863
|
-
└── unclear errors? → error_context
|
|
864
|
-
|
|
865
|
-
Issue Type: Output Quality
|
|
866
|
-
├── inconsistent quality? → quality_gates
|
|
867
|
-
├── no verification? → output_validation
|
|
868
|
-
├── format issues? → template_enforcement
|
|
869
|
-
└── incomplete output? → completeness_check
|
|
870
|
-
|
|
871
|
-
Issue Type: User Experience
|
|
872
|
-
├── no progress? → progress_tracking
|
|
873
|
-
├── unclear status? → status_communication
|
|
874
|
-
├── no feedback? → interactive_checkpoints
|
|
875
|
-
└── confusing flow? → guided_workflow
|
|
876
|
-
|
|
877
|
-
Issue Type: Documentation Redundancy
|
|
878
|
-
├── 核心定义重复? → consolidate_to_ssot
|
|
879
|
-
└── 硬编码配置重复? → centralize_mapping_config
|
|
880
|
-
|
|
881
|
-
Issue Type: Documentation Conflict
|
|
882
|
-
└── 定义不一致? → reconcile_conflicting_definitions
|
|
883
278
|
```
|
|
884
279
|
|
|
885
280
|
---
|
|
886
281
|
|
|
887
|
-
##
|
|
888
|
-
|
|
889
|
-
以下策略针对更通用的优化场景,通常需要 Gemini CLI 进行深度分析后生成具体实现。
|
|
890
|
-
|
|
891
|
-
---
|
|
892
|
-
|
|
893
|
-
### Prompt Engineering Strategies
|
|
894
|
-
|
|
895
|
-
#### Strategy: structured_prompt
|
|
282
|
+
## Token Consumption Strategies
|
|
896
283
|
|
|
897
|
-
|
|
284
|
+
### prompt_compression
|
|
898
285
|
|
|
899
|
-
**Implementation**:
|
|
900
286
|
```javascript
|
|
901
|
-
// Before:
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
const prompt = `
|
|
906
|
-
[ROLE]
|
|
907
|
-
You are a code analysis expert specializing in ${domain}.
|
|
908
|
-
|
|
909
|
-
[TASK]
|
|
910
|
-
Analyze the provided code for:
|
|
911
|
-
1. Code quality issues
|
|
912
|
-
2. Performance bottlenecks
|
|
913
|
-
3. Security vulnerabilities
|
|
914
|
-
|
|
915
|
-
[INPUT]
|
|
916
|
-
File: ${filePath}
|
|
917
|
-
Context: ${context}
|
|
918
|
-
|
|
919
|
-
[OUTPUT FORMAT]
|
|
920
|
-
Return JSON:
|
|
921
|
-
{
|
|
922
|
-
"issues": [{ "type": "...", "severity": "...", "location": "...", "suggestion": "..." }],
|
|
923
|
-
"summary": "..."
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
[CONSTRAINTS]
|
|
927
|
-
- Focus on actionable issues only
|
|
928
|
-
- Limit to top 10 findings
|
|
929
|
-
`;
|
|
287
|
+
// Before: Long inline prompt with role, detailed instructions, full code
|
|
288
|
+
// After: Key instructions only
|
|
289
|
+
const prompt = `Analyze ${codePath} for: patterns, security, performance.
|
|
290
|
+
Return JSON: { issues: [], severity: string }`;
|
|
930
291
|
```
|
|
931
292
|
|
|
932
|
-
|
|
933
|
-
**Verification**: Check output consistency across multiple runs
|
|
934
|
-
|
|
935
|
-
---
|
|
936
|
-
|
|
937
|
-
#### Strategy: output_schema
|
|
938
|
-
|
|
939
|
-
**Purpose**: 强制 LLM 输出符合特定 schema。
|
|
293
|
+
### lazy_loading
|
|
940
294
|
|
|
941
|
-
**Implementation**:
|
|
942
295
|
```javascript
|
|
943
|
-
//
|
|
944
|
-
const
|
|
945
|
-
type: 'object',
|
|
946
|
-
required: ['status', 'result'],
|
|
947
|
-
properties: {
|
|
948
|
-
status: { enum: ['success', 'error', 'partial'] },
|
|
949
|
-
result: { type: 'object' },
|
|
950
|
-
errors: { type: 'array' }
|
|
951
|
-
}
|
|
952
|
-
};
|
|
953
|
-
|
|
954
|
-
// Include in prompt
|
|
955
|
-
const prompt = `
|
|
956
|
-
...task description...
|
|
957
|
-
|
|
958
|
-
[OUTPUT SCHEMA]
|
|
959
|
-
Your response MUST be valid JSON matching this schema:
|
|
960
|
-
${JSON.stringify(outputSchema, null, 2)}
|
|
961
|
-
|
|
962
|
-
[VALIDATION]
|
|
963
|
-
Before returning, verify your output:
|
|
964
|
-
1. Is it valid JSON?
|
|
965
|
-
2. Does it have all required fields?
|
|
966
|
-
3. Are field types correct?
|
|
967
|
-
`;
|
|
296
|
+
// Before: const prompt = `Analyze:\n${Read(filePath)}`;
|
|
297
|
+
// After: const prompt = `Analyze file at: ${filePath}\n(Read if needed)\nReturn: { summary, issues[] }`;
|
|
968
298
|
```
|
|
969
299
|
|
|
970
|
-
|
|
971
|
-
**Verification**: JSON.parse + schema validation
|
|
300
|
+
### output_minimization
|
|
972
301
|
|
|
973
|
-
---
|
|
974
|
-
|
|
975
|
-
#### Strategy: grounding_context
|
|
976
|
-
|
|
977
|
-
**Purpose**: 提供足够上下文减少幻觉。
|
|
978
|
-
|
|
979
|
-
**Implementation**:
|
|
980
302
|
```javascript
|
|
981
|
-
// Gather grounding context
|
|
982
|
-
const groundingContext = {
|
|
983
|
-
codebase_patterns: await analyzePatterns(skillPath),
|
|
984
|
-
existing_examples: await findSimilarImplementations(taskType),
|
|
985
|
-
constraints: state.original_requirements
|
|
986
|
-
};
|
|
987
|
-
|
|
988
303
|
const prompt = `
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
Similar implementations exist at:
|
|
994
|
-
${groundingContext.existing_examples.map(e => `- ${e.path}`).join('\n')}
|
|
995
|
-
|
|
996
|
-
[TASK]
|
|
997
|
-
${taskDescription}
|
|
998
|
-
|
|
999
|
-
[IMPORTANT]
|
|
1000
|
-
- Only suggest patterns that exist in the codebase
|
|
1001
|
-
- Reference specific files when making suggestions
|
|
1002
|
-
- If unsure, indicate uncertainty level
|
|
304
|
+
Analyze the code. Return ONLY this JSON:
|
|
305
|
+
{ "status": "pass|review|fail", "issues": [{"id","severity","file","line"}], "summary": "one sentence" }
|
|
306
|
+
Do not include explanations.
|
|
1003
307
|
`;
|
|
1004
308
|
```
|
|
1005
309
|
|
|
1006
|
-
|
|
1007
|
-
**Verification**: Check suggestions match existing patterns
|
|
1008
|
-
|
|
1009
|
-
---
|
|
1010
|
-
|
|
1011
|
-
### Architecture Strategies
|
|
1012
|
-
|
|
1013
|
-
#### Strategy: phase_decomposition
|
|
1014
|
-
|
|
1015
|
-
**Purpose**: 重新划分阶段以清晰化职责。
|
|
1016
|
-
|
|
1017
|
-
**Analysis via Gemini**:
|
|
1018
|
-
```bash
|
|
1019
|
-
ccw cli -p "
|
|
1020
|
-
PURPOSE: Analyze phase decomposition for skill at ${skillPath}
|
|
1021
|
-
TASK: • Map current phase responsibilities • Identify overlapping concerns • Suggest cleaner boundaries
|
|
1022
|
-
MODE: analysis
|
|
1023
|
-
CONTEXT: @phases/**/*.md
|
|
1024
|
-
EXPECTED: { current_phases: [], overlaps: [], recommended_structure: [] }
|
|
1025
|
-
" --tool gemini --mode analysis
|
|
1026
|
-
```
|
|
1027
|
-
|
|
1028
|
-
**Implementation Pattern**:
|
|
1029
|
-
```
|
|
1030
|
-
Before: Monolithic phases
|
|
1031
|
-
Phase1: Collect + Analyze + Transform + Output
|
|
1032
|
-
|
|
1033
|
-
After: Single-responsibility phases
|
|
1034
|
-
Phase1: Collect (input gathering)
|
|
1035
|
-
Phase2: Analyze (processing)
|
|
1036
|
-
Phase3: Transform (conversion)
|
|
1037
|
-
Phase4: Output (delivery)
|
|
1038
|
-
```
|
|
1039
|
-
|
|
1040
|
-
---
|
|
1041
|
-
|
|
1042
|
-
#### Strategy: interface_contracts
|
|
1043
|
-
|
|
1044
|
-
**Purpose**: 定义阶段间的数据契约。
|
|
1045
|
-
|
|
1046
|
-
**Implementation**:
|
|
1047
|
-
```typescript
|
|
1048
|
-
// Define contracts in state-schema.md
|
|
1049
|
-
interface PhaseContract {
|
|
1050
|
-
input: {
|
|
1051
|
-
required: string[];
|
|
1052
|
-
optional: string[];
|
|
1053
|
-
schema: object;
|
|
1054
|
-
};
|
|
1055
|
-
output: {
|
|
1056
|
-
guarantees: string[];
|
|
1057
|
-
schema: object;
|
|
1058
|
-
};
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
// Phase 1 output contract
|
|
1062
|
-
const phase1Contract: PhaseContract = {
|
|
1063
|
-
input: {
|
|
1064
|
-
required: ['user_request'],
|
|
1065
|
-
optional: ['preferences'],
|
|
1066
|
-
schema: { /* ... */ }
|
|
1067
|
-
},
|
|
1068
|
-
output: {
|
|
1069
|
-
guarantees: ['parsed_requirements', 'validation_status'],
|
|
1070
|
-
schema: { /* ... */ }
|
|
1071
|
-
}
|
|
1072
|
-
};
|
|
1073
|
-
```
|
|
1074
|
-
|
|
1075
|
-
---
|
|
1076
|
-
|
|
1077
|
-
### Performance Strategies
|
|
1078
|
-
|
|
1079
|
-
#### Strategy: token_budgeting
|
|
1080
|
-
|
|
1081
|
-
**Purpose**: 为每个阶段设置 Token 预算。
|
|
1082
|
-
|
|
1083
|
-
**Implementation**:
|
|
1084
|
-
```javascript
|
|
1085
|
-
const TOKEN_BUDGETS = {
|
|
1086
|
-
'phase-collect': 2000,
|
|
1087
|
-
'phase-analyze': 5000,
|
|
1088
|
-
'phase-generate': 8000,
|
|
1089
|
-
total: 15000
|
|
1090
|
-
};
|
|
1091
|
-
|
|
1092
|
-
function checkBudget(phase, estimatedTokens) {
|
|
1093
|
-
if (estimatedTokens > TOKEN_BUDGETS[phase]) {
|
|
1094
|
-
console.warn(`Phase ${phase} exceeds budget: ${estimatedTokens} > ${TOKEN_BUDGETS[phase]}`);
|
|
1095
|
-
// Trigger summarization or truncation
|
|
1096
|
-
return false;
|
|
1097
|
-
}
|
|
1098
|
-
return true;
|
|
1099
|
-
}
|
|
1100
|
-
```
|
|
1101
|
-
|
|
1102
|
-
---
|
|
1103
|
-
|
|
1104
|
-
#### Strategy: parallel_execution
|
|
1105
|
-
|
|
1106
|
-
**Purpose**: 并行执行独立任务。
|
|
1107
|
-
|
|
1108
|
-
**Implementation**:
|
|
1109
|
-
```javascript
|
|
1110
|
-
// Before: Sequential
|
|
1111
|
-
const result1 = await Task({ subagent_type: 'analyzer', prompt: prompt1 });
|
|
1112
|
-
const result2 = await Task({ subagent_type: 'analyzer', prompt: prompt2 });
|
|
1113
|
-
const result3 = await Task({ subagent_type: 'analyzer', prompt: prompt3 });
|
|
1114
|
-
|
|
1115
|
-
// After: Parallel (when independent)
|
|
1116
|
-
const [result1, result2, result3] = await Promise.all([
|
|
1117
|
-
Task({ subagent_type: 'analyzer', prompt: prompt1, run_in_background: true }),
|
|
1118
|
-
Task({ subagent_type: 'analyzer', prompt: prompt2, run_in_background: true }),
|
|
1119
|
-
Task({ subagent_type: 'analyzer', prompt: prompt3, run_in_background: true })
|
|
1120
|
-
]);
|
|
1121
|
-
```
|
|
1122
|
-
|
|
1123
|
-
---
|
|
1124
|
-
|
|
1125
|
-
#### Strategy: result_caching
|
|
1126
|
-
|
|
1127
|
-
**Purpose**: 缓存中间结果避免重复计算。
|
|
1128
|
-
|
|
1129
|
-
**Implementation**:
|
|
1130
|
-
```javascript
|
|
1131
|
-
const cache = {};
|
|
1132
|
-
|
|
1133
|
-
async function cachedAnalysis(key, analysisFunc) {
|
|
1134
|
-
if (cache[key]) {
|
|
1135
|
-
console.log(`Cache hit: ${key}`);
|
|
1136
|
-
return cache[key];
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
const result = await analysisFunc();
|
|
1140
|
-
cache[key] = result;
|
|
1141
|
-
|
|
1142
|
-
// Persist to disk for cross-session caching
|
|
1143
|
-
Write(`${workDir}/cache/${key}.json`, JSON.stringify(result));
|
|
1144
|
-
|
|
1145
|
-
return result;
|
|
1146
|
-
}
|
|
1147
|
-
```
|
|
1148
|
-
|
|
1149
|
-
---
|
|
1150
|
-
|
|
1151
|
-
### Error Handling Strategies
|
|
1152
|
-
|
|
1153
|
-
#### Strategy: graceful_degradation
|
|
1154
|
-
|
|
1155
|
-
**Purpose**: 失败时降级而非崩溃。
|
|
1156
|
-
|
|
1157
|
-
**Implementation**:
|
|
1158
|
-
```javascript
|
|
1159
|
-
async function executeWithDegradation(primaryTask, fallbackTask) {
|
|
1160
|
-
try {
|
|
1161
|
-
return await primaryTask();
|
|
1162
|
-
} catch (error) {
|
|
1163
|
-
console.warn(`Primary task failed: ${error.message}, using fallback`);
|
|
1164
|
-
|
|
1165
|
-
try {
|
|
1166
|
-
return await fallbackTask();
|
|
1167
|
-
} catch (fallbackError) {
|
|
1168
|
-
console.error(`Fallback also failed: ${fallbackError.message}`);
|
|
1169
|
-
return {
|
|
1170
|
-
status: 'degraded',
|
|
1171
|
-
partial_result: null,
|
|
1172
|
-
error: fallbackError.message
|
|
1173
|
-
};
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
}
|
|
1177
|
-
```
|
|
1178
|
-
|
|
1179
|
-
---
|
|
1180
|
-
|
|
1181
|
-
#### Strategy: structured_logging
|
|
1182
|
-
|
|
1183
|
-
**Purpose**: 添加结构化日志便于调试。
|
|
310
|
+
### state_field_reduction
|
|
1184
311
|
|
|
1185
|
-
|
|
312
|
+
Audit checklist:
|
|
1186
313
|
```javascript
|
|
1187
|
-
function
|
|
1188
|
-
const
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
};
|
|
1194
|
-
|
|
1195
|
-
// Append to log file
|
|
1196
|
-
const logPath = `${workDir}/execution.log`;
|
|
1197
|
-
const existing = Read(logPath) || '';
|
|
1198
|
-
Write(logPath, existing + JSON.stringify(entry) + '\n');
|
|
1199
|
-
|
|
1200
|
-
// Console output
|
|
1201
|
-
console.log(`[${level}] ${action}:`, JSON.stringify(data));
|
|
314
|
+
function auditStateFields(schema) {
|
|
315
|
+
const candidates = Object.keys(schema).filter(k =>
|
|
316
|
+
k.startsWith('debug_') || k.endsWith('_cache') ||
|
|
317
|
+
k.endsWith('_temp') || k.includes('intermediate')
|
|
318
|
+
);
|
|
319
|
+
return { total: Object.keys(schema).length, removable: candidates };
|
|
1202
320
|
}
|
|
1203
|
-
|
|
1204
|
-
// Usage
|
|
1205
|
-
log('INFO', 'phase_start', { phase: 'analyze', input_size: 1000 });
|
|
1206
|
-
log('ERROR', 'agent_failure', { agent: 'universal-executor', error: err.message });
|
|
1207
321
|
```
|
|
1208
322
|
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
### Output Quality Strategies
|
|
323
|
+
### in_memory_consolidation
|
|
1212
324
|
|
|
1213
|
-
#### Strategy: quality_gates
|
|
1214
|
-
|
|
1215
|
-
**Purpose**: 输出前进行质量检查。
|
|
1216
|
-
|
|
1217
|
-
**Implementation**:
|
|
1218
325
|
```javascript
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
message: 'Output must have at least 3 sections'
|
|
1224
|
-
},
|
|
1225
|
-
{
|
|
1226
|
-
name: 'format',
|
|
1227
|
-
check: (output) => /^#\s/.test(output.content),
|
|
1228
|
-
message: 'Output must start with markdown heading'
|
|
1229
|
-
},
|
|
1230
|
-
{
|
|
1231
|
-
name: 'length',
|
|
1232
|
-
check: (output) => output.content?.length >= 500,
|
|
1233
|
-
message: 'Output must be at least 500 characters'
|
|
1234
|
-
}
|
|
1235
|
-
];
|
|
1236
|
-
|
|
1237
|
-
function validateOutput(output) {
|
|
1238
|
-
const failures = qualityGates
|
|
1239
|
-
.filter(gate => !gate.check(output))
|
|
1240
|
-
.map(gate => gate.message);
|
|
1241
|
-
|
|
1242
|
-
if (failures.length > 0) {
|
|
1243
|
-
throw new Error(`Quality gate failures:\n${failures.join('\n')}`);
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
return true;
|
|
1247
|
-
}
|
|
326
|
+
// Before: Multiple files — diagnosis-report.md, summary.json, tuning-report.md
|
|
327
|
+
// After: Single state.json with final_report rendered on demand
|
|
328
|
+
const consolidated = { ...state, final_report: { summary, generated_at: Date.now() } };
|
|
329
|
+
Write(`${workDir}/state.json`, JSON.stringify(consolidated, null, 2));
|
|
1248
330
|
```
|
|
1249
331
|
|
|
1250
332
|
---
|
|
1251
333
|
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
#### Strategy: progress_tracking
|
|
1255
|
-
|
|
1256
|
-
**Purpose**: 显示执行进度。
|
|
1257
|
-
|
|
1258
|
-
**Implementation**:
|
|
1259
|
-
```javascript
|
|
1260
|
-
function updateProgress(current, total, description) {
|
|
1261
|
-
const percentage = Math.round((current / total) * 100);
|
|
1262
|
-
const progressBar = '█'.repeat(percentage / 5) + '░'.repeat(20 - percentage / 5);
|
|
1263
|
-
|
|
1264
|
-
console.log(`[${progressBar}] ${percentage}% - ${description}`);
|
|
1265
|
-
|
|
1266
|
-
// Update state for UI
|
|
1267
|
-
updateState({
|
|
1268
|
-
progress: {
|
|
1269
|
-
current,
|
|
1270
|
-
total,
|
|
1271
|
-
percentage,
|
|
1272
|
-
description
|
|
1273
|
-
}
|
|
1274
|
-
});
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
// Usage
|
|
1278
|
-
updateProgress(1, 5, 'Initializing tuning session...');
|
|
1279
|
-
updateProgress(2, 5, 'Running context diagnosis...');
|
|
1280
|
-
```
|
|
1281
|
-
|
|
1282
|
-
---
|
|
1283
|
-
|
|
1284
|
-
#### Strategy: interactive_checkpoints
|
|
1285
|
-
|
|
1286
|
-
**Purpose**: 在关键点暂停获取用户确认。
|
|
1287
|
-
|
|
1288
|
-
**Implementation**:
|
|
1289
|
-
```javascript
|
|
1290
|
-
async function checkpoint(name, summary, options) {
|
|
1291
|
-
console.log(`\n=== Checkpoint: ${name} ===`);
|
|
1292
|
-
console.log(summary);
|
|
1293
|
-
|
|
1294
|
-
const response = await AskUserQuestion({
|
|
1295
|
-
questions: [{
|
|
1296
|
-
question: `Review ${name} results. How to proceed?`,
|
|
1297
|
-
header: 'Checkpoint',
|
|
1298
|
-
options: options || [
|
|
1299
|
-
{ label: 'Continue', description: 'Proceed with next step' },
|
|
1300
|
-
{ label: 'Modify', description: 'Adjust parameters and retry' },
|
|
1301
|
-
{ label: 'Skip', description: 'Skip this step' },
|
|
1302
|
-
{ label: 'Abort', description: 'Stop the workflow' }
|
|
1303
|
-
],
|
|
1304
|
-
multiSelect: false
|
|
1305
|
-
}]
|
|
1306
|
-
});
|
|
1307
|
-
|
|
1308
|
-
return response;
|
|
1309
|
-
}
|
|
1310
|
-
```
|
|
1311
|
-
|
|
1312
|
-
---
|
|
1313
|
-
|
|
1314
|
-
## Token Consumption Strategies
|
|
1315
|
-
|
|
1316
|
-
Strategies for reducing token usage and simplifying skill outputs.
|
|
1317
|
-
|
|
1318
|
-
---
|
|
1319
|
-
|
|
1320
|
-
### Strategy: prompt_compression
|
|
334
|
+
## Documentation Strategies
|
|
1321
335
|
|
|
1322
|
-
|
|
336
|
+
### consolidate_to_ssot
|
|
1323
337
|
|
|
1324
|
-
**Implementation**:
|
|
1325
338
|
```javascript
|
|
1326
|
-
//
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
Please follow these detailed instructions carefully:
|
|
1331
|
-
1. Read the code thoroughly
|
|
1332
|
-
2. Identify any anti-patterns
|
|
1333
|
-
3. Check for security vulnerabilities
|
|
1334
|
-
... (continues for many lines)
|
|
1335
|
-
|
|
1336
|
-
Code to analyze:
|
|
1337
|
-
${fullCodeContent}
|
|
1338
|
-
`;
|
|
1339
|
-
|
|
1340
|
-
// After: Compressed with template reference
|
|
1341
|
-
const PROMPT_TEMPLATE_PATH = 'templates/analyzer-prompt.md';
|
|
1342
|
-
|
|
1343
|
-
const prompt = `
|
|
1344
|
-
[TEMPLATE: ${PROMPT_TEMPLATE_PATH}]
|
|
1345
|
-
[CODE_PATH: ${codePath}]
|
|
1346
|
-
[FOCUS: patterns, security]
|
|
1347
|
-
`;
|
|
1348
|
-
|
|
1349
|
-
// Or use key instructions only
|
|
1350
|
-
const prompt = `
|
|
1351
|
-
Analyze ${codePath} for: patterns, security, performance.
|
|
1352
|
-
Return JSON: { issues: [], severity: string }
|
|
1353
|
-
`;
|
|
339
|
+
// 1. Identify canonical source (priority: specs/ > phases/ > SKILL.md)
|
|
340
|
+
// 2. Ensure canonical has full definition
|
|
341
|
+
// 3. Replace other locations with reference links
|
|
342
|
+
// e.g., "See [state-schema.md](phases/state-schema.md)"
|
|
1354
343
|
```
|
|
1355
344
|
|
|
1356
|
-
|
|
1357
|
-
**Verification**: Compare token count before/after compression
|
|
1358
|
-
|
|
1359
|
-
---
|
|
1360
|
-
|
|
1361
|
-
### Strategy: lazy_loading
|
|
345
|
+
### centralize_mapping_config
|
|
1362
346
|
|
|
1363
|
-
**Purpose**: Pass file paths instead of full content, let consumers load if needed.
|
|
1364
|
-
|
|
1365
|
-
**Implementation**:
|
|
1366
347
|
```javascript
|
|
1367
|
-
//
|
|
1368
|
-
const
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
// After: Path reference with lazy loading instruction
|
|
1372
|
-
const prompt = `
|
|
1373
|
-
Analyze file at: ${filePath}
|
|
1374
|
-
(Read the file content if you need to examine it)
|
|
1375
|
-
Return: { summary: string, issues: [] }
|
|
1376
|
-
`;
|
|
1377
|
-
|
|
1378
|
-
// For agent calls
|
|
1379
|
-
const result = await Task({
|
|
1380
|
-
subagent_type: 'universal-executor',
|
|
1381
|
-
prompt: `
|
|
1382
|
-
[FILE_PATH]: ${dataPath}
|
|
1383
|
-
[TASK]: Analyze the file and extract key metrics.
|
|
1384
|
-
[NOTE]: Read the file only if needed for your analysis.
|
|
1385
|
-
`
|
|
1386
|
-
});
|
|
348
|
+
// 1. Extract hardcoded mappings → specs/category-mappings.json
|
|
349
|
+
// 2. Runtime loads config: const map = JSON.parse(Read('specs/category-mappings.json'));
|
|
350
|
+
// 3. Replace all inline definitions with config lookup
|
|
1387
351
|
```
|
|
1388
352
|
|
|
1389
|
-
|
|
1390
|
-
**Verification**: Verify agents can still access required data
|
|
1391
|
-
|
|
1392
|
-
---
|
|
1393
|
-
|
|
1394
|
-
### Strategy: output_minimization
|
|
353
|
+
### reconcile_conflicting_definitions
|
|
1395
354
|
|
|
1396
|
-
**Purpose**: Configure agents to return minimal, structured output instead of verbose text.
|
|
1397
|
-
|
|
1398
|
-
**Implementation**:
|
|
1399
355
|
```javascript
|
|
1400
|
-
//
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
- Executive summary
|
|
1404
|
-
- Detailed findings with explanations
|
|
1405
|
-
- Code examples for each issue
|
|
1406
|
-
- Recommendations with rationale
|
|
1407
|
-
...
|
|
1408
|
-
`;
|
|
1409
|
-
|
|
1410
|
-
// After: Minimal structured output
|
|
1411
|
-
const prompt = `
|
|
1412
|
-
Analyze the code. Return ONLY this JSON:
|
|
1413
|
-
{
|
|
1414
|
-
"status": "pass|review|fail",
|
|
1415
|
-
"issues": [{ "id": string, "severity": string, "file": string, "line": number }],
|
|
1416
|
-
"summary": "one sentence"
|
|
1417
|
-
}
|
|
1418
|
-
Do not include explanations or code examples.
|
|
1419
|
-
`;
|
|
1420
|
-
|
|
1421
|
-
// Validation
|
|
1422
|
-
const result = JSON.parse(agentOutput);
|
|
1423
|
-
if (!result.status || !Array.isArray(result.issues)) {
|
|
1424
|
-
throw new Error('Invalid output format');
|
|
1425
|
-
}
|
|
356
|
+
// 1. Present conflict to user via AskUserQuestion
|
|
357
|
+
// 2. Apply chosen version across all files
|
|
358
|
+
// 3. Verify no remaining conflicts
|
|
1426
359
|
```
|
|
1427
360
|
|
|
1428
|
-
**Risk**: Low
|
|
1429
|
-
**Verification**: JSON.parse succeeds, output size reduced
|
|
1430
|
-
|
|
1431
361
|
---
|
|
1432
362
|
|
|
1433
|
-
|
|
363
|
+
## General Optimization Areas (via Gemini CLI)
|
|
1434
364
|
|
|
1435
|
-
|
|
365
|
+
For issues in these categories, use Gemini CLI for custom analysis:
|
|
1436
366
|
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
intermediate_result: any; // Remove - not persisted
|
|
1446
|
-
debug_info: DebugInfo; // Remove - debugging only
|
|
1447
|
-
analysis_cache: any; // Remove - session cache
|
|
1448
|
-
full_history: HistoryEntry[]; // Remove - unbounded
|
|
1449
|
-
step1_output: any; // Remove - intermediate
|
|
1450
|
-
step2_output: any; // Remove - intermediate
|
|
1451
|
-
step3_output: any; // Remove - intermediate
|
|
1452
|
-
final_result: FinalResult;
|
|
1453
|
-
error_log: string[]; // Remove - debugging
|
|
1454
|
-
metrics: Metrics; // Remove - optional
|
|
1455
|
-
}
|
|
367
|
+
| Category | Issues | Gemini Analysis |
|
|
368
|
+
|----------|--------|-----------------|
|
|
369
|
+
| Prompt Engineering | Vague instructions, format drift | prompt optimization, structured output |
|
|
370
|
+
| Architecture | Phase overlap, tight coupling | phase_decomposition, interface_contracts |
|
|
371
|
+
| Performance | Slow execution, high tokens | token_budgeting, parallel_execution |
|
|
372
|
+
| Error Handling | Silent failures, no degradation | graceful_degradation, error_propagation |
|
|
373
|
+
| Output Quality | Inconsistent results | quality_gates, output_validation |
|
|
374
|
+
| User Experience | No progress visibility | progress_tracking, interactive_checkpoints |
|
|
1456
375
|
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
```
|
|
1467
|
-
|
|
1468
|
-
**Audit Checklist**:
|
|
1469
|
-
```javascript
|
|
1470
|
-
function auditStateFields(stateSchema) {
|
|
1471
|
-
const removeCandidates = [];
|
|
1472
|
-
|
|
1473
|
-
for (const [key, type] of Object.entries(stateSchema)) {
|
|
1474
|
-
// Identify removal candidates
|
|
1475
|
-
if (key.startsWith('debug_')) removeCandidates.push(key);
|
|
1476
|
-
if (key.endsWith('_cache')) removeCandidates.push(key);
|
|
1477
|
-
if (key.endsWith('_temp')) removeCandidates.push(key);
|
|
1478
|
-
if (key.includes('intermediate')) removeCandidates.push(key);
|
|
1479
|
-
if (key.includes('step') && key.includes('output')) removeCandidates.push(key);
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
return {
|
|
1483
|
-
total_fields: Object.keys(stateSchema).length,
|
|
1484
|
-
remove_candidates: removeCandidates,
|
|
1485
|
-
estimated_reduction: removeCandidates.length
|
|
1486
|
-
};
|
|
1487
|
-
}
|
|
1488
|
-
```
|
|
1489
|
-
|
|
1490
|
-
**Risk**: Medium (ensure no essential data removed)
|
|
1491
|
-
**Verification**: State field count ≤ 15, all essential data preserved
|
|
1492
|
-
|
|
1493
|
-
---
|
|
1494
|
-
|
|
1495
|
-
### Strategy: in_memory_consolidation
|
|
1496
|
-
|
|
1497
|
-
**Purpose**: Consolidate outputs into single file, eliminate redundant report files.
|
|
1498
|
-
|
|
1499
|
-
**Implementation**:
|
|
1500
|
-
```javascript
|
|
1501
|
-
// Before: Multiple output files
|
|
1502
|
-
Write(`${workDir}/diagnosis-report.md`, reportMarkdown);
|
|
1503
|
-
Write(`${workDir}/diagnosis-summary.json`, summaryJson);
|
|
1504
|
-
Write(`${workDir}/state.json`, JSON.stringify(state));
|
|
1505
|
-
Write(`${workDir}/tuning-report.md`, tuningReport);
|
|
1506
|
-
Write(`${workDir}/tuning-summary.md`, finalSummary);
|
|
1507
|
-
|
|
1508
|
-
// After: Single source of truth
|
|
1509
|
-
const consolidatedState = {
|
|
1510
|
-
...state,
|
|
1511
|
-
final_report: {
|
|
1512
|
-
summary: summaryJson,
|
|
1513
|
-
details_available_in_state: true,
|
|
1514
|
-
generated_at: new Date().toISOString()
|
|
1515
|
-
}
|
|
1516
|
-
};
|
|
1517
|
-
Write(`${workDir}/state.json`, JSON.stringify(consolidatedState, null, 2));
|
|
1518
|
-
|
|
1519
|
-
// Report can be rendered from state on-demand
|
|
1520
|
-
function renderReport(state) {
|
|
1521
|
-
return `
|
|
1522
|
-
# Tuning Report: ${state.target_skill.name}
|
|
1523
|
-
Status: ${state.status}
|
|
1524
|
-
Quality: ${state.quality_gate}
|
|
1525
|
-
Issues: ${state.issues.length}
|
|
1526
|
-
...
|
|
1527
|
-
`;
|
|
1528
|
-
}
|
|
376
|
+
**Gemini CLI Template**:
|
|
377
|
+
```bash
|
|
378
|
+
ccw cli -p "
|
|
379
|
+
PURPOSE: [optimization goal for skill at ${skillPath}]
|
|
380
|
+
TASK: • [specific analysis steps]
|
|
381
|
+
MODE: analysis
|
|
382
|
+
CONTEXT: @${skillPath}/**/*
|
|
383
|
+
EXPECTED: [specific deliverable]
|
|
384
|
+
" --tool gemini --mode analysis
|
|
1529
385
|
```
|
|
1530
|
-
|
|
1531
|
-
**Benefits**:
|
|
1532
|
-
- Single file to read/write
|
|
1533
|
-
- No data duplication
|
|
1534
|
-
- On-demand rendering
|
|
1535
|
-
|
|
1536
|
-
**Risk**: Low
|
|
1537
|
-
**Verification**: Only state.json exists as output, rendering works correctly
|