claude-code-workflow 6.3.26 → 6.3.28

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.
Files changed (129) hide show
  1. package/.claude/CLAUDE.md +7 -1
  2. package/.claude/agents/action-planning-agent.md +1 -0
  3. package/.claude/agents/cli-discuss-agent.md +391 -0
  4. package/.claude/agents/cli-execution-agent.md +2 -0
  5. package/.claude/agents/cli-explore-agent.md +2 -1
  6. package/.claude/agents/cli-lite-planning-agent.md +1 -0
  7. package/.claude/agents/cli-planning-agent.md +1 -0
  8. package/.claude/agents/code-developer.md +1 -0
  9. package/.claude/agents/conceptual-planning-agent.md +2 -0
  10. package/.claude/agents/context-search-agent.md +1 -0
  11. package/.claude/agents/debug-explore-agent.md +2 -0
  12. package/.claude/agents/doc-generator.md +1 -0
  13. package/.claude/agents/issue-plan-agent.md +2 -1
  14. package/.claude/agents/issue-queue-agent.md +2 -1
  15. package/.claude/agents/memory-bridge.md +2 -0
  16. package/.claude/agents/test-context-search-agent.md +2 -0
  17. package/.claude/agents/test-fix-agent.md +1 -0
  18. package/.claude/agents/ui-design-agent.md +2 -0
  19. package/.claude/agents/universal-executor.md +1 -0
  20. package/.claude/commands/issue/execute.md +141 -163
  21. package/.claude/commands/workflow/lite-lite-lite.md +798 -0
  22. package/.claude/commands/workflow/multi-cli-plan.md +510 -0
  23. package/.claude/skills/ccw/SKILL.md +262 -372
  24. package/.claude/skills/ccw/command.json +547 -0
  25. package/.claude/skills/ccw-help/SKILL.md +46 -107
  26. package/.claude/skills/ccw-help/command.json +511 -0
  27. package/.claude/skills/skill-tuning/SKILL.md +303 -0
  28. package/.claude/skills/skill-tuning/phases/actions/action-abort.md +164 -0
  29. package/.claude/skills/skill-tuning/phases/actions/action-analyze-requirements.md +406 -0
  30. package/.claude/skills/skill-tuning/phases/actions/action-apply-fix.md +206 -0
  31. package/.claude/skills/skill-tuning/phases/actions/action-complete.md +195 -0
  32. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-agent.md +317 -0
  33. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-context.md +243 -0
  34. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-dataflow.md +318 -0
  35. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-docs.md +299 -0
  36. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-memory.md +269 -0
  37. package/.claude/skills/skill-tuning/phases/actions/action-diagnose-token-consumption.md +200 -0
  38. package/.claude/skills/skill-tuning/phases/actions/action-gemini-analysis.md +322 -0
  39. package/.claude/skills/skill-tuning/phases/actions/action-generate-report.md +228 -0
  40. package/.claude/skills/skill-tuning/phases/actions/action-init.md +149 -0
  41. package/.claude/skills/skill-tuning/phases/actions/action-propose-fixes.md +317 -0
  42. package/.claude/skills/skill-tuning/phases/actions/action-verify.md +222 -0
  43. package/.claude/skills/skill-tuning/phases/orchestrator.md +377 -0
  44. package/.claude/skills/skill-tuning/phases/state-schema.md +378 -0
  45. package/.claude/skills/skill-tuning/specs/category-mappings.json +284 -0
  46. package/.claude/skills/skill-tuning/specs/dimension-mapping.md +212 -0
  47. package/.claude/skills/skill-tuning/specs/problem-taxonomy.md +318 -0
  48. package/.claude/skills/skill-tuning/specs/quality-gates.md +263 -0
  49. package/.claude/skills/skill-tuning/specs/skill-authoring-principles.md +189 -0
  50. package/.claude/skills/skill-tuning/specs/tuning-strategies.md +1537 -0
  51. package/.claude/skills/skill-tuning/templates/diagnosis-report.md +153 -0
  52. package/.claude/skills/skill-tuning/templates/fix-proposal.md +204 -0
  53. package/.claude/workflows/cli-templates/schemas/multi-cli-discussion-schema.json +421 -0
  54. package/.claude/workflows/cli-tools-usage.md +0 -41
  55. package/ccw/dist/core/auth/csrf-middleware.d.ts.map +1 -1
  56. package/ccw/dist/core/auth/csrf-middleware.js +3 -1
  57. package/ccw/dist/core/auth/csrf-middleware.js.map +1 -1
  58. package/ccw/dist/core/data-aggregator.d.ts +2 -0
  59. package/ccw/dist/core/data-aggregator.d.ts.map +1 -1
  60. package/ccw/dist/core/data-aggregator.js +5 -2
  61. package/ccw/dist/core/data-aggregator.js.map +1 -1
  62. package/ccw/dist/core/lite-scanner.d.ts +2 -1
  63. package/ccw/dist/core/lite-scanner.d.ts.map +1 -1
  64. package/ccw/dist/core/lite-scanner.js +295 -6
  65. package/ccw/dist/core/lite-scanner.js.map +1 -1
  66. package/ccw/dist/core/routes/codexlens/config-handlers.d.ts.map +1 -1
  67. package/ccw/dist/core/routes/codexlens/config-handlers.js +5 -5
  68. package/ccw/dist/core/routes/codexlens/config-handlers.js.map +1 -1
  69. package/ccw/dist/core/routes/session-routes.d.ts.map +1 -1
  70. package/ccw/dist/core/routes/session-routes.js +166 -48
  71. package/ccw/dist/core/routes/session-routes.js.map +1 -1
  72. package/ccw/dist/core/routes/system-routes.d.ts.map +1 -1
  73. package/ccw/dist/core/routes/system-routes.js +87 -0
  74. package/ccw/dist/core/routes/system-routes.js.map +1 -1
  75. package/ccw/dist/core/server.js +2 -2
  76. package/ccw/dist/core/server.js.map +1 -1
  77. package/ccw/scripts/IMPLEMENTATION-SUMMARY.md +226 -0
  78. package/ccw/scripts/QUICK-REFERENCE.md +135 -0
  79. package/ccw/scripts/README-memory-embedder.md +157 -0
  80. package/ccw/scripts/__pycache__/memory_embedder.cpython-313.pyc +0 -0
  81. package/ccw/scripts/__pycache__/test_memory_embedder.cpython-313-pytest-8.4.2.pyc +0 -0
  82. package/ccw/scripts/memory-embedder-example.ts +184 -0
  83. package/ccw/scripts/memory_embedder.py +428 -0
  84. package/ccw/scripts/test_memory_embedder.py +245 -0
  85. package/ccw/src/core/auth/csrf-middleware.ts +3 -1
  86. package/ccw/src/core/data-aggregator.ts +7 -2
  87. package/ccw/src/core/lite-scanner.ts +440 -6
  88. package/ccw/src/core/routes/codexlens/config-handlers.ts +12 -9
  89. package/ccw/src/core/routes/session-routes.ts +201 -48
  90. package/ccw/src/core/routes/system-routes.ts +102 -0
  91. package/ccw/src/core/server.ts +2 -2
  92. package/ccw/src/templates/dashboard-css/01-base.css +8 -0
  93. package/ccw/src/templates/dashboard-css/02-session.css +81 -0
  94. package/ccw/src/templates/dashboard-css/04-lite-tasks.css +2442 -0
  95. package/ccw/src/templates/dashboard-css/21-cli-toolmgmt.css +157 -0
  96. package/ccw/src/templates/dashboard-css/32-issue-manager.css +23 -0
  97. package/ccw/src/templates/dashboard-js/components/cli-stream-viewer.js +38 -4
  98. package/ccw/src/templates/dashboard-js/components/hook-manager.js +38 -13
  99. package/ccw/src/templates/dashboard-js/components/navigation.js +24 -4
  100. package/ccw/src/templates/dashboard-js/i18n.js +194 -6
  101. package/ccw/src/templates/dashboard-js/views/api-settings.js +32 -0
  102. package/ccw/src/templates/dashboard-js/views/claude-manager.js +44 -3
  103. package/ccw/src/templates/dashboard-js/views/cli-manager.js +303 -31
  104. package/ccw/src/templates/dashboard-js/views/history.js +44 -6
  105. package/ccw/src/templates/dashboard-js/views/home.js +1 -0
  106. package/ccw/src/templates/dashboard-js/views/issue-manager.js +54 -7
  107. package/ccw/src/templates/dashboard-js/views/lite-tasks.js +1817 -4
  108. package/ccw/src/templates/dashboard.html +5 -0
  109. package/package.json +2 -1
  110. package/.claude/skills/ccw/index/command-capabilities.json +0 -127
  111. package/.claude/skills/ccw/index/intent-rules.json +0 -136
  112. package/.claude/skills/ccw/index/workflow-chains.json +0 -451
  113. package/.claude/skills/ccw/phases/actions/bugfix.md +0 -218
  114. package/.claude/skills/ccw/phases/actions/coupled.md +0 -194
  115. package/.claude/skills/ccw/phases/actions/docs.md +0 -93
  116. package/.claude/skills/ccw/phases/actions/full.md +0 -154
  117. package/.claude/skills/ccw/phases/actions/issue.md +0 -201
  118. package/.claude/skills/ccw/phases/actions/rapid.md +0 -104
  119. package/.claude/skills/ccw/phases/actions/review-fix.md +0 -84
  120. package/.claude/skills/ccw/phases/actions/tdd.md +0 -66
  121. package/.claude/skills/ccw/phases/actions/ui.md +0 -79
  122. package/.claude/skills/ccw/phases/orchestrator.md +0 -435
  123. package/.claude/skills/ccw/specs/intent-classification.md +0 -336
  124. package/.claude/skills/ccw-help/index/all-agents.json +0 -82
  125. package/.claude/skills/ccw-help/index/all-commands.json +0 -882
  126. package/.claude/skills/ccw-help/index/by-category.json +0 -914
  127. package/.claude/skills/ccw-help/index/by-use-case.json +0 -896
  128. package/.claude/skills/ccw-help/index/command-relationships.json +0 -160
  129. package/.claude/skills/ccw-help/index/essential-commands.json +0 -112
@@ -0,0 +1,299 @@
1
+ # Action: Diagnose Documentation Structure
2
+
3
+ 检测目标 skill 中的文档冗余和冲突问题。
4
+
5
+ ## Purpose
6
+
7
+ - 检测重复定义(State Schema、映射表、类型定义等)
8
+ - 检测冲突定义(优先级定义不一致、实现与文档漂移等)
9
+ - 生成合并和解决冲突的建议
10
+
11
+ ## Preconditions
12
+
13
+ - [ ] `state.status === 'running'`
14
+ - [ ] `state.target_skill !== null`
15
+ - [ ] `!state.diagnosis.docs`
16
+ - [ ] 用户指定 focus_areas 包含 'docs' 或 'all',或需要全面诊断
17
+
18
+ ## Detection Patterns
19
+
20
+ ### DOC-RED-001: 核心定义重复
21
+
22
+ 检测 State Schema、核心接口等在多处定义:
23
+
24
+ ```javascript
25
+ async function detectDefinitionDuplicates(skillPath) {
26
+ const patterns = [
27
+ { name: 'state_schema', regex: /interface\s+(TuningState|State)\s*\{/g },
28
+ { name: 'fix_strategy', regex: /type\s+FixStrategy\s*=/g },
29
+ { name: 'issue_type', regex: /type:\s*['"]?(context_explosion|memory_loss|dataflow_break)/g }
30
+ ];
31
+
32
+ const files = Glob('**/*.md', { cwd: skillPath });
33
+ const duplicates = [];
34
+
35
+ for (const pattern of patterns) {
36
+ const matches = [];
37
+ for (const file of files) {
38
+ const content = Read(`${skillPath}/${file}`);
39
+ if (pattern.regex.test(content)) {
40
+ matches.push({ file, pattern: pattern.name });
41
+ }
42
+ }
43
+ if (matches.length > 1) {
44
+ duplicates.push({
45
+ type: pattern.name,
46
+ files: matches.map(m => m.file),
47
+ severity: 'high'
48
+ });
49
+ }
50
+ }
51
+
52
+ return duplicates;
53
+ }
54
+ ```
55
+
56
+ ### DOC-RED-002: 硬编码配置重复
57
+
58
+ 检测 action 文件中硬编码与 spec 文档的重复:
59
+
60
+ ```javascript
61
+ async function detectHardcodedDuplicates(skillPath) {
62
+ const actionFiles = Glob('phases/actions/*.md', { cwd: skillPath });
63
+ const specFiles = Glob('specs/*.md', { cwd: skillPath });
64
+
65
+ const duplicates = [];
66
+
67
+ for (const actionFile of actionFiles) {
68
+ const content = Read(`${skillPath}/${actionFile}`);
69
+
70
+ // 检测硬编码的映射对象
71
+ const hardcodedPatterns = [
72
+ /const\s+\w*[Mm]apping\s*=\s*\{/g,
73
+ /patternMapping\s*=\s*\{/g,
74
+ /strategyMapping\s*=\s*\{/g
75
+ ];
76
+
77
+ for (const pattern of hardcodedPatterns) {
78
+ if (pattern.test(content)) {
79
+ duplicates.push({
80
+ type: 'hardcoded_mapping',
81
+ file: actionFile,
82
+ description: '硬编码映射可能与 specs/ 中的定义重复',
83
+ severity: 'high'
84
+ });
85
+ }
86
+ }
87
+ }
88
+
89
+ return duplicates;
90
+ }
91
+ ```
92
+
93
+ ### DOC-CON-001: 优先级定义冲突
94
+
95
+ 检测 P0-P3 等优先级在不同文件中的定义不一致:
96
+
97
+ ```javascript
98
+ async function detectPriorityConflicts(skillPath) {
99
+ const files = Glob('**/*.md', { cwd: skillPath });
100
+ const priorityDefs = {};
101
+
102
+ const priorityPattern = /\*\*P(\d+)\*\*[:\s]+([^\|]+)/g;
103
+
104
+ for (const file of files) {
105
+ const content = Read(`${skillPath}/${file}`);
106
+ let match;
107
+ while ((match = priorityPattern.exec(content)) !== null) {
108
+ const priority = `P${match[1]}`;
109
+ const definition = match[2].trim();
110
+
111
+ if (!priorityDefs[priority]) {
112
+ priorityDefs[priority] = [];
113
+ }
114
+ priorityDefs[priority].push({ file, definition });
115
+ }
116
+ }
117
+
118
+ const conflicts = [];
119
+ for (const [priority, defs] of Object.entries(priorityDefs)) {
120
+ const uniqueDefs = [...new Set(defs.map(d => d.definition))];
121
+ if (uniqueDefs.length > 1) {
122
+ conflicts.push({
123
+ key: priority,
124
+ definitions: defs,
125
+ severity: 'critical'
126
+ });
127
+ }
128
+ }
129
+
130
+ return conflicts;
131
+ }
132
+ ```
133
+
134
+ ### DOC-CON-002: 实现与文档漂移
135
+
136
+ 检测硬编码与文档表格的不一致:
137
+
138
+ ```javascript
139
+ async function detectImplementationDrift(skillPath) {
140
+ // 比较 category-mappings.json 与 specs/*.md 中的表格
141
+ const mappingsFile = `${skillPath}/specs/category-mappings.json`;
142
+
143
+ if (!fileExists(mappingsFile)) {
144
+ return []; // 无集中配置,跳过
145
+ }
146
+
147
+ const mappings = JSON.parse(Read(mappingsFile));
148
+ const conflicts = [];
149
+
150
+ // 与 dimension-mapping.md 对比
151
+ const dimMapping = Read(`${skillPath}/specs/dimension-mapping.md`);
152
+
153
+ for (const [category, config] of Object.entries(mappings.categories)) {
154
+ // 检查策略是否在文档中提及
155
+ for (const strategy of config.strategies || []) {
156
+ if (!dimMapping.includes(strategy)) {
157
+ conflicts.push({
158
+ type: 'mapping',
159
+ key: `${category}.strategies`,
160
+ issue: `策略 ${strategy} 在 JSON 中定义但未在文档中提及`
161
+ });
162
+ }
163
+ }
164
+ }
165
+
166
+ return conflicts;
167
+ }
168
+ ```
169
+
170
+ ## Execution
171
+
172
+ ```javascript
173
+ async function executeDiagnosis(state, workDir) {
174
+ console.log('=== Diagnosing Documentation Structure ===');
175
+
176
+ const skillPath = state.target_skill.path;
177
+ const issues = [];
178
+
179
+ // 1. 检测冗余
180
+ const definitionDups = await detectDefinitionDuplicates(skillPath);
181
+ const hardcodedDups = await detectHardcodedDuplicates(skillPath);
182
+
183
+ for (const dup of [...definitionDups, ...hardcodedDups]) {
184
+ issues.push({
185
+ id: `DOC-RED-${issues.length + 1}`,
186
+ type: 'doc_redundancy',
187
+ severity: dup.severity,
188
+ location: { files: dup.files || [dup.file] },
189
+ description: dup.description || `${dup.type} 在多处定义`,
190
+ evidence: dup.files || [dup.file],
191
+ root_cause: '缺乏单一真相来源',
192
+ impact: '维护困难,易产生不一致',
193
+ suggested_fix: 'consolidate_to_ssot'
194
+ });
195
+ }
196
+
197
+ // 2. 检测冲突
198
+ const priorityConflicts = await detectPriorityConflicts(skillPath);
199
+ const driftConflicts = await detectImplementationDrift(skillPath);
200
+
201
+ for (const conflict of priorityConflicts) {
202
+ issues.push({
203
+ id: `DOC-CON-${issues.length + 1}`,
204
+ type: 'doc_conflict',
205
+ severity: 'critical',
206
+ location: { files: conflict.definitions.map(d => d.file) },
207
+ description: `${conflict.key} 在不同文件中定义不一致`,
208
+ evidence: conflict.definitions.map(d => `${d.file}: ${d.definition}`),
209
+ root_cause: '定义更新后未同步',
210
+ impact: '行为不可预测',
211
+ suggested_fix: 'reconcile_conflicting_definitions'
212
+ });
213
+ }
214
+
215
+ // 3. 生成报告
216
+ const severity = issues.some(i => i.severity === 'critical') ? 'critical' :
217
+ issues.some(i => i.severity === 'high') ? 'high' :
218
+ issues.length > 0 ? 'medium' : 'none';
219
+
220
+ const result = {
221
+ status: 'completed',
222
+ issues_found: issues.length,
223
+ severity: severity,
224
+ execution_time_ms: Date.now() - startTime,
225
+ details: {
226
+ patterns_checked: ['DOC-RED-001', 'DOC-RED-002', 'DOC-CON-001', 'DOC-CON-002'],
227
+ patterns_matched: issues.map(i => i.id.split('-').slice(0, 2).join('-')),
228
+ evidence: issues.flatMap(i => i.evidence),
229
+ recommendations: generateRecommendations(issues)
230
+ },
231
+ redundancies: issues.filter(i => i.type === 'doc_redundancy'),
232
+ conflicts: issues.filter(i => i.type === 'doc_conflict')
233
+ };
234
+
235
+ // 写入诊断结果
236
+ Write(`${workDir}/diagnosis/docs-diagnosis.json`, JSON.stringify(result, null, 2));
237
+
238
+ return {
239
+ stateUpdates: {
240
+ 'diagnosis.docs': result,
241
+ issues: [...state.issues, ...issues]
242
+ },
243
+ outputFiles: [`${workDir}/diagnosis/docs-diagnosis.json`],
244
+ summary: `文档诊断完成:发现 ${issues.length} 个问题 (${severity})`
245
+ };
246
+ }
247
+
248
+ function generateRecommendations(issues) {
249
+ const recommendations = [];
250
+
251
+ if (issues.some(i => i.type === 'doc_redundancy')) {
252
+ recommendations.push('使用 consolidate_to_ssot 策略合并重复定义');
253
+ recommendations.push('考虑创建 specs/category-mappings.json 集中管理配置');
254
+ }
255
+
256
+ if (issues.some(i => i.type === 'doc_conflict')) {
257
+ recommendations.push('使用 reconcile_conflicting_definitions 策略解决冲突');
258
+ recommendations.push('建立文档同步检查机制');
259
+ }
260
+
261
+ return recommendations;
262
+ }
263
+ ```
264
+
265
+ ## Output
266
+
267
+ ### State Updates
268
+
269
+ ```javascript
270
+ {
271
+ stateUpdates: {
272
+ 'diagnosis.docs': {
273
+ status: 'completed',
274
+ issues_found: N,
275
+ severity: 'critical|high|medium|low|none',
276
+ redundancies: [...],
277
+ conflicts: [...]
278
+ },
279
+ issues: [...existingIssues, ...newIssues]
280
+ }
281
+ }
282
+ ```
283
+
284
+ ### Output Files
285
+
286
+ - `${workDir}/diagnosis/docs-diagnosis.json` - 完整诊断结果
287
+
288
+ ## Error Handling
289
+
290
+ | Error | Recovery |
291
+ |-------|----------|
292
+ | 文件读取失败 | 记录警告,继续处理其他文件 |
293
+ | 正则匹配超时 | 跳过该模式,记录 skipped |
294
+ | JSON 解析失败 | 跳过配置对比,仅进行模式检测 |
295
+
296
+ ## Next Actions
297
+
298
+ - 如果发现 critical 问题 → 优先进入 action-propose-fixes
299
+ - 如果无问题 → 继续下一个诊断或 action-generate-report
@@ -0,0 +1,269 @@
1
+ # Action: Diagnose Long-tail Forgetting
2
+
3
+ Analyze target skill for long-tail effect and constraint forgetting issues.
4
+
5
+ ## Purpose
6
+
7
+ - Detect loss of early instructions in long execution chains
8
+ - Identify missing constraint propagation mechanisms
9
+ - Find weak goal alignment between phases
10
+ - Measure instruction retention across phases
11
+
12
+ ## Preconditions
13
+
14
+ - [ ] state.status === 'running'
15
+ - [ ] state.target_skill.path is set
16
+ - [ ] 'memory' in state.focus_areas OR state.focus_areas is empty
17
+
18
+ ## Detection Patterns
19
+
20
+ ### Pattern 1: Missing Constraint References
21
+
22
+ ```regex
23
+ # Phases that don't reference original requirements
24
+ # Look for absence of: requirements, constraints, original, initial, user_request
25
+ ```
26
+
27
+ ### Pattern 2: Goal Drift
28
+
29
+ ```regex
30
+ # Later phases focus on immediate task without global context
31
+ /\[TASK\][^[]*(?!\[CONSTRAINTS\]|\[REQUIREMENTS\])/
32
+ ```
33
+
34
+ ### Pattern 3: No Checkpoint Mechanism
35
+
36
+ ```regex
37
+ # Absence of state preservation at key points
38
+ # Look for lack of: checkpoint, snapshot, preserve, restore
39
+ ```
40
+
41
+ ### Pattern 4: Implicit State Passing
42
+
43
+ ```regex
44
+ # State passed implicitly through conversation rather than explicitly
45
+ /(?<!state\.)context\./
46
+ ```
47
+
48
+ ## Execution
49
+
50
+ ```javascript
51
+ async function execute(state, workDir) {
52
+ const skillPath = state.target_skill.path;
53
+ const startTime = Date.now();
54
+ const issues = [];
55
+ const evidence = [];
56
+
57
+ console.log(`Diagnosing long-tail forgetting in ${skillPath}...`);
58
+
59
+ // 1. Analyze phase chain for constraint propagation
60
+ const phaseFiles = Glob(`${skillPath}/phases/*.md`)
61
+ .filter(f => !f.includes('orchestrator') && !f.includes('state-schema'))
62
+ .sort();
63
+
64
+ // Extract phase order (for sequential) or action dependencies (for autonomous)
65
+ const isAutonomous = state.target_skill.execution_mode === 'autonomous';
66
+
67
+ // 2. Check each phase for constraint awareness
68
+ let firstPhaseConstraints = [];
69
+
70
+ for (let i = 0; i < phaseFiles.length; i++) {
71
+ const file = phaseFiles[i];
72
+ const content = Read(file);
73
+ const relativePath = file.replace(skillPath + '/', '');
74
+ const phaseNum = i + 1;
75
+
76
+ // Extract constraints from first phase
77
+ if (i === 0) {
78
+ const constraintMatch = content.match(/\[CONSTRAINTS?\]([^[]*)/i);
79
+ if (constraintMatch) {
80
+ firstPhaseConstraints = constraintMatch[1]
81
+ .split('\n')
82
+ .filter(l => l.trim().startsWith('-'))
83
+ .map(l => l.trim().replace(/^-\s*/, ''));
84
+ }
85
+ }
86
+
87
+ // Check if later phases reference original constraints
88
+ if (i > 0 && firstPhaseConstraints.length > 0) {
89
+ const mentionsConstraints = firstPhaseConstraints.some(c =>
90
+ content.toLowerCase().includes(c.toLowerCase().slice(0, 20))
91
+ );
92
+
93
+ if (!mentionsConstraints) {
94
+ issues.push({
95
+ id: `MEM-${issues.length + 1}`,
96
+ type: 'memory_loss',
97
+ severity: 'high',
98
+ location: { file: relativePath, phase: `Phase ${phaseNum}` },
99
+ description: `Phase ${phaseNum} does not reference original constraints`,
100
+ evidence: [`Original constraints: ${firstPhaseConstraints.slice(0, 3).join(', ')}`],
101
+ root_cause: 'Constraint information not propagated to later phases',
102
+ impact: 'May produce output violating original requirements',
103
+ suggested_fix: 'Add explicit constraint injection or reference to state.original_constraints'
104
+ });
105
+ evidence.push({
106
+ file: relativePath,
107
+ pattern: 'missing_constraint_reference',
108
+ context: `Phase ${phaseNum} of ${phaseFiles.length}`,
109
+ severity: 'high'
110
+ });
111
+ }
112
+ }
113
+
114
+ // Check for goal drift - task without constraints
115
+ const hasTask = /\[TASK\]/i.test(content);
116
+ const hasConstraints = /\[CONSTRAINTS?\]|\[REQUIREMENTS?\]|\[RULES?\]/i.test(content);
117
+
118
+ if (hasTask && !hasConstraints && i > 1) {
119
+ issues.push({
120
+ id: `MEM-${issues.length + 1}`,
121
+ type: 'memory_loss',
122
+ severity: 'medium',
123
+ location: { file: relativePath },
124
+ description: 'Phase has TASK but no CONSTRAINTS/RULES section',
125
+ evidence: ['Task defined without boundary constraints'],
126
+ root_cause: 'Agent may not adhere to global constraints',
127
+ impact: 'Potential goal drift from original intent',
128
+ suggested_fix: 'Add [CONSTRAINTS] section referencing global rules'
129
+ });
130
+ }
131
+
132
+ // Check for checkpoint mechanism
133
+ const hasCheckpoint = /checkpoint|snapshot|preserve|savepoint/i.test(content);
134
+ const isKeyPhase = i === Math.floor(phaseFiles.length / 2) || i === phaseFiles.length - 1;
135
+
136
+ if (isKeyPhase && !hasCheckpoint && phaseFiles.length > 3) {
137
+ issues.push({
138
+ id: `MEM-${issues.length + 1}`,
139
+ type: 'memory_loss',
140
+ severity: 'low',
141
+ location: { file: relativePath },
142
+ description: 'Key phase without checkpoint mechanism',
143
+ evidence: [`Phase ${phaseNum} is a key milestone but has no state preservation`],
144
+ root_cause: 'Cannot recover from failures or verify constraint adherence',
145
+ impact: 'No rollback capability if constraints violated',
146
+ suggested_fix: 'Add checkpoint before major state changes'
147
+ });
148
+ }
149
+ }
150
+
151
+ // 3. Check for explicit state schema with constraints field
152
+ const stateSchemaFile = Glob(`${skillPath}/phases/state-schema.md`)[0];
153
+ if (stateSchemaFile) {
154
+ const schemaContent = Read(stateSchemaFile);
155
+ const hasConstraintsField = /constraints|requirements|original_request/i.test(schemaContent);
156
+
157
+ if (!hasConstraintsField) {
158
+ issues.push({
159
+ id: `MEM-${issues.length + 1}`,
160
+ type: 'memory_loss',
161
+ severity: 'medium',
162
+ location: { file: 'phases/state-schema.md' },
163
+ description: 'State schema lacks constraints/requirements field',
164
+ evidence: ['No dedicated field for preserving original requirements'],
165
+ root_cause: 'State structure does not support constraint persistence',
166
+ impact: 'Constraints may be lost during state transitions',
167
+ suggested_fix: 'Add original_requirements field to state schema'
168
+ });
169
+ }
170
+ }
171
+
172
+ // 4. Check SKILL.md for constraint enforcement in execution flow
173
+ const skillMd = Read(`${skillPath}/SKILL.md`);
174
+ const hasConstraintVerification = /constraint.*verif|verif.*constraint|quality.*gate/i.test(skillMd);
175
+
176
+ if (!hasConstraintVerification && phaseFiles.length > 3) {
177
+ issues.push({
178
+ id: `MEM-${issues.length + 1}`,
179
+ type: 'memory_loss',
180
+ severity: 'medium',
181
+ location: { file: 'SKILL.md' },
182
+ description: 'No constraint verification step in execution flow',
183
+ evidence: ['Execution flow lacks quality gate or constraint check'],
184
+ root_cause: 'No mechanism to verify output matches original intent',
185
+ impact: 'Constraint violations may go undetected',
186
+ suggested_fix: 'Add verification phase comparing output to original requirements'
187
+ });
188
+ }
189
+
190
+ // 5. Calculate severity
191
+ const criticalCount = issues.filter(i => i.severity === 'critical').length;
192
+ const highCount = issues.filter(i => i.severity === 'high').length;
193
+ const severity = criticalCount > 0 ? 'critical' :
194
+ highCount > 2 ? 'high' :
195
+ highCount > 0 ? 'medium' :
196
+ issues.length > 0 ? 'low' : 'none';
197
+
198
+ // 6. Write diagnosis result
199
+ const diagnosisResult = {
200
+ status: 'completed',
201
+ issues_found: issues.length,
202
+ severity: severity,
203
+ execution_time_ms: Date.now() - startTime,
204
+ details: {
205
+ patterns_checked: [
206
+ 'constraint_propagation',
207
+ 'goal_drift',
208
+ 'checkpoint_mechanism',
209
+ 'state_schema_constraints'
210
+ ],
211
+ patterns_matched: evidence.map(e => e.pattern),
212
+ evidence: evidence,
213
+ phase_analysis: {
214
+ total_phases: phaseFiles.length,
215
+ first_phase_constraints: firstPhaseConstraints.length,
216
+ phases_with_constraint_ref: phaseFiles.length - issues.filter(i =>
217
+ i.description.includes('does not reference')).length
218
+ },
219
+ recommendations: [
220
+ highCount > 0 ? 'Implement constraint injection at each phase' : null,
221
+ issues.some(i => i.description.includes('checkpoint'))
222
+ ? 'Add checkpoint/restore mechanism' : null,
223
+ issues.some(i => i.description.includes('State schema'))
224
+ ? 'Add original_requirements to state schema' : null
225
+ ].filter(Boolean)
226
+ }
227
+ };
228
+
229
+ Write(`${workDir}/diagnosis/memory-diagnosis.json`,
230
+ JSON.stringify(diagnosisResult, null, 2));
231
+
232
+ return {
233
+ stateUpdates: {
234
+ 'diagnosis.memory': diagnosisResult,
235
+ issues: [...state.issues, ...issues]
236
+ },
237
+ outputFiles: [`${workDir}/diagnosis/memory-diagnosis.json`],
238
+ summary: `Memory diagnosis: ${issues.length} issues found (severity: ${severity})`
239
+ };
240
+ }
241
+ ```
242
+
243
+ ## State Updates
244
+
245
+ ```javascript
246
+ return {
247
+ stateUpdates: {
248
+ 'diagnosis.memory': {
249
+ status: 'completed',
250
+ issues_found: <count>,
251
+ severity: '<critical|high|medium|low|none>',
252
+ // ... full diagnosis result
253
+ },
254
+ issues: [...existingIssues, ...newIssues]
255
+ }
256
+ };
257
+ ```
258
+
259
+ ## Error Handling
260
+
261
+ | Error Type | Recovery |
262
+ |------------|----------|
263
+ | Phase file read error | Skip file, continue analysis |
264
+ | No phases found | Report as structure issue |
265
+
266
+ ## Next Actions
267
+
268
+ - Success: action-diagnose-dataflow (or next in focus_areas)
269
+ - Skipped: If 'memory' not in focus_areas