codymaster 4.6.0 → 5.2.0

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 (161) hide show
  1. package/CHANGELOG.md +74 -8
  2. package/README.md +192 -95
  3. package/dist/advisory-handoff.js +89 -0
  4. package/dist/advisory-report.js +105 -0
  5. package/dist/browse-server.js +251 -0
  6. package/dist/cli/command-registry.js +34 -0
  7. package/dist/cli/commands/agent.js +120 -0
  8. package/dist/cli/commands/bench.js +69 -0
  9. package/dist/cli/commands/brain.js +108 -0
  10. package/dist/cli/commands/dashboard.js +93 -0
  11. package/dist/cli/commands/design-studio.js +111 -0
  12. package/dist/cli/commands/distro.js +25 -0
  13. package/dist/cli/commands/engineering.js +596 -0
  14. package/dist/cli/commands/evolve.js +123 -0
  15. package/dist/cli/commands/mcp-serve.js +104 -0
  16. package/dist/cli/commands/project.js +324 -0
  17. package/dist/cli/commands/skill-chain.js +269 -0
  18. package/dist/cli/commands/system.js +89 -0
  19. package/dist/cli/commands/task.js +254 -0
  20. package/dist/cli/update-check.js +83 -0
  21. package/dist/cm-config.js +92 -0
  22. package/dist/cm-suggest.js +77 -0
  23. package/dist/codybench/judges/automated.js +31 -0
  24. package/dist/codybench/runners/claude-code.js +32 -0
  25. package/dist/codybench/suites/memory-retention.js +85 -0
  26. package/dist/codybench/suites/tdd-regression.js +35 -0
  27. package/dist/codybench/suites/token-efficiency.js +55 -0
  28. package/dist/codybench/types.js +2 -0
  29. package/dist/context-db.js +157 -0
  30. package/dist/continuity.js +2 -6
  31. package/dist/distro-validate.js +54 -0
  32. package/dist/execution-analyzer.js +138 -0
  33. package/dist/guardian-core.js +74 -0
  34. package/dist/index.js +36 -2759
  35. package/dist/indexer/skills-lib.js +533 -0
  36. package/dist/indexer/skills-map.js +1374 -0
  37. package/dist/indexer/skills.js +16 -0
  38. package/dist/learning-promoter.js +246 -0
  39. package/dist/mcp-context-server.js +289 -1
  40. package/dist/mcp-skills-tools.js +81 -0
  41. package/dist/retro-summary.js +70 -0
  42. package/dist/second-opinion-providers.js +79 -0
  43. package/dist/skill-chain.js +63 -1
  44. package/dist/skill-evolver.js +456 -0
  45. package/dist/skill-execution-cache.js +254 -0
  46. package/dist/smart-brain-router.js +184 -0
  47. package/dist/sprint-pipeline.js +228 -0
  48. package/dist/storage-backend.js +14 -67
  49. package/dist/token-budget.js +88 -0
  50. package/dist/utils/cli-utils.js +76 -0
  51. package/dist/utils/skill-utils.js +32 -0
  52. package/package.json +17 -7
  53. package/scripts/build-skills.mjs +51 -0
  54. package/scripts/gate-0-repo-hygiene.js +75 -0
  55. package/scripts/postinstall.js +34 -28
  56. package/scripts/security-scan.js +1 -1
  57. package/scripts/validate-skills.mjs +42 -0
  58. package/skills/CLAUDE.md +2 -7
  59. package/skills/_shared/helpers.md +2 -8
  60. package/skills/cm-ads-tracker/SKILL.md +3 -6
  61. package/skills/cm-browse/SKILL.md +34 -0
  62. package/skills/cm-conductor-worktrees/SKILL.md +28 -0
  63. package/skills/cm-content-factory/SKILL.md +1 -1
  64. package/skills/cm-content-factory/landing/docs/content/changelog.md +36 -0
  65. package/skills/cm-content-factory/landing/docs/content/deployment.md +46 -0
  66. package/skills/cm-content-factory/landing/docs/content/execution-flow.md +67 -0
  67. package/skills/cm-content-factory/landing/docs/content/memory-system.md +38 -0
  68. package/skills/cm-content-factory/landing/docs/content/openspace.md +27 -0
  69. package/skills/cm-content-factory/landing/docs/content/use-cases.md +26 -0
  70. package/skills/cm-content-factory/landing/docs/content/v5-intro.md +28 -0
  71. package/skills/cm-content-factory/landing/docs/index.html +240 -0
  72. package/skills/cm-content-factory/landing/index.html +100 -100
  73. package/skills/cm-content-factory/landing/script.js +42 -0
  74. package/skills/cm-content-factory/landing/translations.js +400 -400
  75. package/skills/cm-continuity/SKILL.md +32 -33
  76. package/skills/cm-design-studio/SKILL.md +34 -0
  77. package/skills/cm-ecosystem-roadmap/SKILL.md +15 -0
  78. package/skills/cm-engineering-meta/SKILL.md +73 -0
  79. package/skills/cm-growth-hacking/SKILL.md +1 -12
  80. package/skills/cm-guardian-runtime/SKILL.md +26 -0
  81. package/skills/cm-mcp-engineering/SKILL.md +22 -0
  82. package/skills/cm-notebooklm/SKILL.md +1 -17
  83. package/skills/cm-post-deploy-canary/SKILL.md +22 -0
  84. package/skills/cm-project-bootstrap/SKILL.md +11 -0
  85. package/skills/cm-qa-visual-cli/SKILL.md +22 -0
  86. package/skills/cm-retro-cli/SKILL.md +23 -0
  87. package/skills/cm-second-opinion-cli/SKILL.md +23 -0
  88. package/skills/cm-secret-shield/SKILL.md +2 -2
  89. package/skills/cm-security-gate/SKILL.md +1 -0
  90. package/skills/cm-skill-chain/SKILL.md +25 -4
  91. package/skills/cm-skill-evolution/SKILL.md +83 -0
  92. package/skills/cm-skill-health/SKILL.md +83 -0
  93. package/skills/cm-skill-index/SKILL.md +11 -3
  94. package/skills/cm-skill-search/SKILL.md +49 -0
  95. package/skills/cm-skill-share/SKILL.md +58 -0
  96. package/skills/cm-sprint-bus/SKILL.md +33 -0
  97. package/skills/cm-start/SKILL.md +0 -10
  98. package/skills/cm-tdd/SKILL.md +59 -72
  99. package/skills/profiles/README.md +21 -0
  100. package/skills/profiles/core.txt +23 -0
  101. package/skills/profiles/design.txt +6 -0
  102. package/skills/profiles/full.txt +62 -0
  103. package/skills/profiles/growth.txt +10 -0
  104. package/skills/profiles/knowledge.txt +7 -0
  105. package/install.sh +0 -901
  106. package/scripts/test-gemini.js +0 -13
  107. package/skills/cm-frappe-agent/SKILL.md +0 -134
  108. package/skills/cm-frappe-agent/agents/doctype-architect.md +0 -596
  109. package/skills/cm-frappe-agent/agents/erpnext-customizer.md +0 -643
  110. package/skills/cm-frappe-agent/agents/frappe-backend.md +0 -814
  111. package/skills/cm-frappe-agent/agents/frappe-custom-frontend.md +0 -557
  112. package/skills/cm-frappe-agent/agents/frappe-debugger.md +0 -625
  113. package/skills/cm-frappe-agent/agents/frappe-fixer.md +0 -275
  114. package/skills/cm-frappe-agent/agents/frappe-frontend.md +0 -660
  115. package/skills/cm-frappe-agent/agents/frappe-installer.md +0 -158
  116. package/skills/cm-frappe-agent/agents/frappe-performance.md +0 -307
  117. package/skills/cm-frappe-agent/agents/frappe-planner.md +0 -419
  118. package/skills/cm-frappe-agent/agents/frappe-remote-ops.md +0 -153
  119. package/skills/cm-frappe-agent/agents/github-workflow.md +0 -286
  120. package/skills/cm-frappe-agent/commands/frappe-app.md +0 -351
  121. package/skills/cm-frappe-agent/commands/frappe-backend.md +0 -162
  122. package/skills/cm-frappe-agent/commands/frappe-bench.md +0 -254
  123. package/skills/cm-frappe-agent/commands/frappe-debug.md +0 -263
  124. package/skills/cm-frappe-agent/commands/frappe-doctype-create.md +0 -272
  125. package/skills/cm-frappe-agent/commands/frappe-doctype-field.md +0 -310
  126. package/skills/cm-frappe-agent/commands/frappe-erpnext.md +0 -210
  127. package/skills/cm-frappe-agent/commands/frappe-fix.md +0 -59
  128. package/skills/cm-frappe-agent/commands/frappe-frontend.md +0 -210
  129. package/skills/cm-frappe-agent/commands/frappe-fullstack.md +0 -243
  130. package/skills/cm-frappe-agent/commands/frappe-github.md +0 -57
  131. package/skills/cm-frappe-agent/commands/frappe-install.md +0 -52
  132. package/skills/cm-frappe-agent/commands/frappe-plan.md +0 -442
  133. package/skills/cm-frappe-agent/commands/frappe-remote.md +0 -58
  134. package/skills/cm-frappe-agent/commands/frappe-test.md +0 -356
  135. package/skills/cm-frappe-agent/docs/README.md +0 -51
  136. package/skills/cm-frappe-agent/docs/agents-catalog.md +0 -113
  137. package/skills/cm-frappe-agent/docs/architecture.md +0 -149
  138. package/skills/cm-frappe-agent/docs/commands-catalog.md +0 -82
  139. package/skills/cm-frappe-agent/docs/resources-catalog.md +0 -66
  140. package/skills/cm-frappe-agent/docs/sitemap-urls.txt +0 -52
  141. package/skills/cm-frappe-agent/docs/sitemap.md +0 -81
  142. package/skills/cm-frappe-agent/docs/sop/user-guide.md +0 -178
  143. package/skills/cm-frappe-agent/docs/sop/vibe-coding-guide.md +0 -122
  144. package/skills/cm-frappe-agent/resources/7-layer-architecture.md +0 -985
  145. package/skills/cm-frappe-agent/resources/bench_commands.md +0 -73
  146. package/skills/cm-frappe-agent/resources/code-patterns-guide.md +0 -948
  147. package/skills/cm-frappe-agent/resources/common_pitfalls.md +0 -266
  148. package/skills/cm-frappe-agent/resources/doctype-registry.md +0 -158
  149. package/skills/cm-frappe-agent/resources/installation-guide.md +0 -289
  150. package/skills/cm-frappe-agent/resources/rest-api-patterns.md +0 -182
  151. package/skills/cm-frappe-agent/resources/scaffold_checklist.md +0 -82
  152. package/skills/cm-frappe-agent/resources/upgrade_patterns.md +0 -113
  153. package/skills/cm-frappe-agent/resources/web-form-patterns.md +0 -252
  154. package/skills/cm-frappe-agent/skills/bench-commands/SKILL.md +0 -621
  155. package/skills/cm-frappe-agent/skills/client-scripts/SKILL.md +0 -642
  156. package/skills/cm-frappe-agent/skills/doctype-patterns/SKILL.md +0 -576
  157. package/skills/cm-frappe-agent/skills/frappe-api/SKILL.md +0 -740
  158. package/skills/cm-frappe-agent/skills/remote-operations/SKILL.md +0 -47
  159. package/skills/cm-frappe-agent/skills/server-scripts/SKILL.md +0 -608
  160. package/skills/cm-frappe-agent/skills/web-forms/SKILL.md +0 -46
  161. package/skills/frappe-app-builder.zip +0 -0
@@ -0,0 +1,456 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SkillEvolver = void 0;
7
+ exports.formatEvolutionResult = formatEvolutionResult;
8
+ exports.formatEvolutionHistory = formatEvolutionHistory;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const storage_backend_1 = require("./storage-backend");
13
+ // ─── Constants ──────────────────────────────────────────────────────────────
14
+ const BACKUP_DIR = '.cm/skill-backups';
15
+ const MAX_EVOLUTION_DEPTH = 5; // Anti-loop: max generations
16
+ const MIN_FIX_CONFIDENCE = 0.70;
17
+ const MIN_DERIVED_CONFIDENCE = 0.75;
18
+ const MIN_CAPTURED_CONFIDENCE = 0.80;
19
+ // ─── Skill Evolver ──────────────────────────────────────────────────────────
20
+ // TRIZ #15 Dynamization — skills transform based on environment feedback
21
+ /**
22
+ * SkillEvolver — Executes evolution actions recommended by the ExecutionAnalyzer.
23
+ *
24
+ * Three modes:
25
+ * FIX — In-place repair of degraded skills (patch SKILL.md)
26
+ * DERIVED — Create specialized variant of an existing skill
27
+ * CAPTURED — Generate a new skill from successful reasoning patterns
28
+ *
29
+ * Safety: Always creates backups before mutations. Anti-loop protection
30
+ * prevents runaway evolution chains.
31
+ */
32
+ class SkillEvolver {
33
+ constructor(projectPath, backend) {
34
+ this.projectPath = projectPath;
35
+ this.backend = backend !== null && backend !== void 0 ? backend : (0, storage_backend_1.getBackend)(projectPath);
36
+ this.backend.initialize();
37
+ this.skillsDir = this.findSkillsDir();
38
+ this.backupDir = path_1.default.join(projectPath, BACKUP_DIR);
39
+ }
40
+ // ─── Public API ─────────────────────────────────────────────────────────
41
+ /**
42
+ * Evolve a skill based on an advisory handoff.
43
+ */
44
+ evolveFromAdvisory(handoff) {
45
+ var _a;
46
+ const mode = handoff.recommendation.action;
47
+ const skill = handoff.skill.name;
48
+ const confidence = (_a = handoff.recommendation.confidence) !== null && _a !== void 0 ? _a : 0;
49
+ if (!skill) {
50
+ return { success: false, mode: mode !== null && mode !== void 0 ? mode : 'FIX', skill: '', error: 'No target skill in advisory handoff.' };
51
+ }
52
+ if (!mode || mode === 'NONE') {
53
+ return { success: false, mode: 'FIX', skill, error: 'No evolution action recommended.' };
54
+ }
55
+ return this.evolve(mode, skill, confidence, handoff.source.analysis_id);
56
+ }
57
+ /**
58
+ * Execute a specific evolution mode on a skill.
59
+ */
60
+ evolve(mode, skill, confidence, sourceAnalysisId) {
61
+ // Anti-loop protection
62
+ const record = this.getSkillRecord(skill);
63
+ if (record && record.generation >= MAX_EVOLUTION_DEPTH) {
64
+ return {
65
+ success: false, mode, skill,
66
+ error: `Anti-loop: ${skill} has reached max evolution depth (${MAX_EVOLUTION_DEPTH}). Manual review required.`,
67
+ };
68
+ }
69
+ // Confidence threshold check
70
+ const minConfidence = this.getMinConfidence(mode);
71
+ if (confidence < minConfidence) {
72
+ return {
73
+ success: false, mode, skill,
74
+ error: `Confidence ${(confidence * 100).toFixed(0)}% is below ${mode} threshold of ${(minConfidence * 100).toFixed(0)}%.`,
75
+ };
76
+ }
77
+ switch (mode) {
78
+ case 'FIX':
79
+ return this.executeFix(skill, confidence, sourceAnalysisId);
80
+ case 'DERIVED':
81
+ return this.executeDerived(skill, confidence, sourceAnalysisId);
82
+ case 'CAPTURED':
83
+ return this.executeCaptured(skill, confidence, sourceAnalysisId);
84
+ }
85
+ }
86
+ /**
87
+ * Get evolution history for a skill.
88
+ */
89
+ getHistory(skill, limit = 20) {
90
+ return this.loadHistory(skill, limit);
91
+ }
92
+ /**
93
+ * Get the skill record (lineage tracking).
94
+ */
95
+ getSkillRecord(skill) {
96
+ return this.loadSkillRecord(skill);
97
+ }
98
+ /**
99
+ * List all skill records.
100
+ */
101
+ listSkillRecords(limit = 50) {
102
+ return this.loadAllSkillRecords(limit);
103
+ }
104
+ /**
105
+ * Rollback a skill to its pre-evolution state.
106
+ */
107
+ rollback(skill) {
108
+ const backupPath = this.getLatestBackup(skill);
109
+ if (!backupPath) {
110
+ return { success: false, mode: 'FIX', skill, error: `No backup found for ${skill}.` };
111
+ }
112
+ const skillMdPath = this.getSkillPath(skill);
113
+ if (!skillMdPath) {
114
+ return { success: false, mode: 'FIX', skill, error: `Skill ${skill} not found.` };
115
+ }
116
+ try {
117
+ const backupContent = fs_1.default.readFileSync(backupPath, 'utf-8');
118
+ fs_1.default.writeFileSync(skillMdPath, backupContent, 'utf-8');
119
+ return { success: true, mode: 'FIX', skill, backupPath, patchApplied: 'Rolled back to backup.' };
120
+ }
121
+ catch (err) {
122
+ return { success: false, mode: 'FIX', skill, error: `Rollback failed: ${err}` };
123
+ }
124
+ }
125
+ // ─── Evolution Modes ──────────────────────────────────────────────────────
126
+ /**
127
+ * FIX mode — In-place repair of a degraded skill.
128
+ * Appends learnings from failed executions to the skill's SKILL.md.
129
+ */
130
+ executeFix(skill, confidence, sourceAnalysisId) {
131
+ const skillPath = this.getSkillPath(skill);
132
+ if (!skillPath) {
133
+ return { success: false, mode: 'FIX', skill, error: `Skill ${skill} not found at expected path.` };
134
+ }
135
+ // Read current content
136
+ let content;
137
+ try {
138
+ content = fs_1.default.readFileSync(skillPath, 'utf-8');
139
+ }
140
+ catch (_a) {
141
+ return { success: false, mode: 'FIX', skill, error: `Cannot read ${skillPath}` };
142
+ }
143
+ // Create backup before mutation
144
+ const backupPath = this.createBackup(skill, content);
145
+ // Build the fix patch from execution analysis
146
+ const analyses = this.backend.getExecutionAnalyses(10);
147
+ const relevantAnalysis = sourceAnalysisId
148
+ ? analyses.find(a => a.id === sourceAnalysisId)
149
+ : analyses.find(a => a.recommended_action === 'FIX' && a.skill_judgments.some(j => j.skill === skill));
150
+ if (!relevantAnalysis) {
151
+ return { success: false, mode: 'FIX', skill, backupPath, error: 'No relevant analysis found for fix.' };
152
+ }
153
+ const fixPatch = this.buildFixPatch(skill, relevantAnalysis);
154
+ const beforeHash = this.hashContent(content);
155
+ // Apply the fix (append learnings section)
156
+ const updatedContent = content + '\n' + fixPatch;
157
+ fs_1.default.writeFileSync(skillPath, updatedContent, 'utf-8');
158
+ const afterHash = this.hashContent(updatedContent);
159
+ // Record evolution
160
+ this.recordEvolution(skill, 'FIX', sourceAnalysisId, beforeHash, afterHash, fixPatch, confidence);
161
+ this.upsertSkillRecord(skill, 'fix');
162
+ return { success: true, mode: 'FIX', skill, backupPath, patchApplied: fixPatch };
163
+ }
164
+ /**
165
+ * DERIVED mode — Create a specialized variant of an existing skill.
166
+ * Copies the skill and adds specialization notes.
167
+ */
168
+ executeDerived(skill, confidence, sourceAnalysisId) {
169
+ var _a;
170
+ const skillPath = this.getSkillPath(skill);
171
+ if (!skillPath) {
172
+ return { success: false, mode: 'DERIVED', skill, error: `Parent skill ${skill} not found.` };
173
+ }
174
+ let content;
175
+ try {
176
+ content = fs_1.default.readFileSync(skillPath, 'utf-8');
177
+ }
178
+ catch (_b) {
179
+ return { success: false, mode: 'DERIVED', skill, error: `Cannot read ${skillPath}` };
180
+ }
181
+ // Generate derived skill name
182
+ const record = this.getSkillRecord(skill);
183
+ const gen = ((_a = record === null || record === void 0 ? void 0 : record.generation) !== null && _a !== void 0 ? _a : 0) + 1;
184
+ const derivedName = `${skill}-v${gen}`;
185
+ const derivedDir = path_1.default.join(this.skillsDir, derivedName);
186
+ if (fs_1.default.existsSync(derivedDir)) {
187
+ return { success: false, mode: 'DERIVED', skill, error: `Derived skill ${derivedName} already exists.` };
188
+ }
189
+ // Get specialization context from analysis
190
+ const analyses = this.backend.getExecutionAnalyses(10);
191
+ const analysis = sourceAnalysisId
192
+ ? analyses.find(a => a.id === sourceAnalysisId)
193
+ : analyses.find(a => a.recommended_action === 'DERIVED');
194
+ const specialization = analysis
195
+ ? `\n\n## Derived Specialization (gen ${gen})\n\n> Auto-derived from ${skill} based on execution analysis.\n> Analysis: ${analysis.summary}\n> Fallback patterns addressed: ${analysis.skill_judgments.filter(j => j.fallback_used).map(j => j.note || j.skill).join(', ') || 'N/A'}\n`
196
+ : `\n\n## Derived Specialization (gen ${gen})\n\n> Auto-derived from ${skill}.\n`;
197
+ const derivedContent = content + specialization;
198
+ const beforeHash = this.hashContent(content);
199
+ const afterHash = this.hashContent(derivedContent);
200
+ // Create derived skill directory and file
201
+ fs_1.default.mkdirSync(derivedDir, { recursive: true });
202
+ fs_1.default.writeFileSync(path_1.default.join(derivedDir, 'SKILL.md'), derivedContent, 'utf-8');
203
+ // Record evolution
204
+ this.recordEvolution(derivedName, 'DERIVED', sourceAnalysisId, beforeHash, afterHash, `Derived from ${skill} (gen ${gen})`, confidence);
205
+ this.upsertSkillRecord(derivedName, 'derived', skill, gen);
206
+ return { success: true, mode: 'DERIVED', skill: derivedName, patchApplied: `Derived from ${skill}` };
207
+ }
208
+ /**
209
+ * CAPTURED mode — Generate a new skill from successful reasoning patterns.
210
+ * Creates a minimal SKILL.md scaffold capturing the successful approach.
211
+ */
212
+ executeCaptured(skill, confidence, sourceAnalysisId) {
213
+ var _a;
214
+ const analyses = this.backend.getExecutionAnalyses(10);
215
+ const analysis = sourceAnalysisId
216
+ ? analyses.find(a => a.id === sourceAnalysisId)
217
+ : analyses.find(a => a.recommended_action === 'CAPTURED');
218
+ if (!analysis) {
219
+ return { success: false, mode: 'CAPTURED', skill, error: 'No analysis with CAPTURED recommendation found.' };
220
+ }
221
+ const capturedName = `cm-captured-${Date.now()}`;
222
+ const capturedDir = path_1.default.join(this.skillsDir, capturedName);
223
+ const skillContent = [
224
+ '---',
225
+ `name: ${capturedName}`,
226
+ `description: Auto-captured skill from successful task execution`,
227
+ '---',
228
+ '',
229
+ `# ${capturedName}`,
230
+ '',
231
+ `> Auto-captured on ${new Date().toISOString()}`,
232
+ `> Source: ${analysis.task_title}`,
233
+ `> Confidence: ${(confidence * 100).toFixed(0)}%`,
234
+ '',
235
+ '## Context',
236
+ '',
237
+ analysis.summary,
238
+ '',
239
+ '## Approach',
240
+ '',
241
+ `The following skill chain was NOT used but the task completed successfully:`,
242
+ `- Selected skills: ${((_a = analysis.selected_skills) !== null && _a !== void 0 ? _a : []).join(', ') || 'none'}`,
243
+ '',
244
+ '## When to Apply',
245
+ '',
246
+ `Apply this skill when facing tasks similar to: "${analysis.task_title}"`,
247
+ '',
248
+ '## Steps',
249
+ '',
250
+ '1. [TODO: Extract specific steps from the captured pattern]',
251
+ '2. [TODO: Document the reasoning that led to success]',
252
+ '',
253
+ ].join('\n');
254
+ const afterHash = this.hashContent(skillContent);
255
+ fs_1.default.mkdirSync(capturedDir, { recursive: true });
256
+ fs_1.default.writeFileSync(path_1.default.join(capturedDir, 'SKILL.md'), skillContent, 'utf-8');
257
+ this.recordEvolution(capturedName, 'CAPTURED', sourceAnalysisId, '', afterHash, `Captured from: ${analysis.task_title}`, confidence);
258
+ this.upsertSkillRecord(capturedName, 'captured', undefined, 0);
259
+ return { success: true, mode: 'CAPTURED', skill: capturedName, patchApplied: `Captured from task: ${analysis.task_title}` };
260
+ }
261
+ // ─── Helpers ──────────────────────────────────────────────────────────────
262
+ findSkillsDir() {
263
+ // Check common skill locations
264
+ const candidates = [
265
+ path_1.default.join(this.projectPath, 'skills'),
266
+ path_1.default.join(this.projectPath, '.agent', 'skills'),
267
+ ];
268
+ for (const dir of candidates) {
269
+ if (fs_1.default.existsSync(dir))
270
+ return dir;
271
+ }
272
+ // Default to skills/ (will be created if needed)
273
+ return path_1.default.join(this.projectPath, 'skills');
274
+ }
275
+ getSkillPath(skill) {
276
+ const candidates = [
277
+ path_1.default.join(this.skillsDir, skill, 'SKILL.md'),
278
+ path_1.default.join(this.projectPath, '.agent', 'skills', skill, 'SKILL.md'),
279
+ ];
280
+ for (const p of candidates) {
281
+ if (fs_1.default.existsSync(p))
282
+ return p;
283
+ }
284
+ return null;
285
+ }
286
+ createBackup(skill, content) {
287
+ const backupSkillDir = path_1.default.join(this.backupDir, skill);
288
+ fs_1.default.mkdirSync(backupSkillDir, { recursive: true });
289
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
290
+ const backupPath = path_1.default.join(backupSkillDir, `SKILL-${timestamp}.md`);
291
+ fs_1.default.writeFileSync(backupPath, content, 'utf-8');
292
+ return backupPath;
293
+ }
294
+ getLatestBackup(skill) {
295
+ const backupSkillDir = path_1.default.join(this.backupDir, skill);
296
+ if (!fs_1.default.existsSync(backupSkillDir))
297
+ return null;
298
+ const files = fs_1.default.readdirSync(backupSkillDir)
299
+ .filter(f => f.startsWith('SKILL-') && f.endsWith('.md'))
300
+ .sort()
301
+ .reverse();
302
+ return files.length > 0 ? path_1.default.join(backupSkillDir, files[0]) : null;
303
+ }
304
+ buildFixPatch(skill, analysis) {
305
+ const judgment = analysis.skill_judgments.find(j => j.skill === skill);
306
+ const lines = [
307
+ '',
308
+ `## Evolution Fix (${new Date().toISOString().split('T')[0]})`,
309
+ '',
310
+ `> Auto-applied by SkillEvolver based on execution analysis.`,
311
+ `> Analysis: ${analysis.id.slice(0, 8)}`,
312
+ `> Task: ${analysis.task_title}`,
313
+ `> Status: ${analysis.status}`,
314
+ ];
315
+ if (judgment === null || judgment === void 0 ? void 0 : judgment.note) {
316
+ lines.push(`> Note: ${judgment.note}`);
317
+ }
318
+ if (analysis.retro_summary) {
319
+ lines.push('', '### Learnings Applied', '', analysis.retro_summary);
320
+ }
321
+ lines.push('', `### Corrective Action`, '', `- Review and address the failure pattern from: "${analysis.task_title}"`);
322
+ return lines.join('\n');
323
+ }
324
+ hashContent(content) {
325
+ return crypto_1.default.createHash('sha256').update(content).digest('hex').slice(0, 16);
326
+ }
327
+ getMinConfidence(mode) {
328
+ switch (mode) {
329
+ case 'FIX': return MIN_FIX_CONFIDENCE;
330
+ case 'DERIVED': return MIN_DERIVED_CONFIDENCE;
331
+ case 'CAPTURED': return MIN_CAPTURED_CONFIDENCE;
332
+ }
333
+ }
334
+ // ─── Persistence (file-based for simplicity, can migrate to SQLite later) ─
335
+ recordEvolution(skill, mode, sourceAnalysisId, beforeHash, afterHash, patchSummary, confidence) {
336
+ const historyDir = path_1.default.join(this.projectPath, '.cm', 'evolution');
337
+ fs_1.default.mkdirSync(historyDir, { recursive: true });
338
+ const entry = {
339
+ id: crypto_1.default.randomUUID(),
340
+ skill_name: skill,
341
+ mode,
342
+ source_analysis_id: sourceAnalysisId,
343
+ before_hash: beforeHash,
344
+ after_hash: afterHash,
345
+ patch_summary: patchSummary,
346
+ confidence,
347
+ created_at: new Date().toISOString(),
348
+ };
349
+ const historyFile = path_1.default.join(historyDir, 'history.jsonl');
350
+ fs_1.default.appendFileSync(historyFile, JSON.stringify(entry) + '\n');
351
+ }
352
+ loadHistory(skill, limit = 20) {
353
+ const historyFile = path_1.default.join(this.projectPath, '.cm', 'evolution', 'history.jsonl');
354
+ if (!fs_1.default.existsSync(historyFile))
355
+ return [];
356
+ const lines = fs_1.default.readFileSync(historyFile, 'utf-8').trim().split('\n').filter(Boolean);
357
+ let entries = [];
358
+ for (const line of lines) {
359
+ try {
360
+ entries.push(JSON.parse(line));
361
+ }
362
+ catch ( /* skip malformed */_a) { /* skip malformed */ }
363
+ }
364
+ if (skill)
365
+ entries = entries.filter(e => e.skill_name === skill);
366
+ return entries.slice(-limit).reverse();
367
+ }
368
+ upsertSkillRecord(skill, origin, parentSkill, generation) {
369
+ var _a, _b, _c, _d, _e, _f;
370
+ const recordsDir = path_1.default.join(this.projectPath, '.cm', 'evolution');
371
+ fs_1.default.mkdirSync(recordsDir, { recursive: true });
372
+ const recordsFile = path_1.default.join(recordsDir, 'records.json');
373
+ let records = {};
374
+ if (fs_1.default.existsSync(recordsFile)) {
375
+ try {
376
+ records = JSON.parse(fs_1.default.readFileSync(recordsFile, 'utf-8'));
377
+ }
378
+ catch ( /* fresh */_g) { /* fresh */ }
379
+ }
380
+ const existing = records[skill];
381
+ const now = new Date().toISOString();
382
+ records[skill] = {
383
+ id: (_a = existing === null || existing === void 0 ? void 0 : existing.id) !== null && _a !== void 0 ? _a : crypto_1.default.randomUUID(),
384
+ skill_name: skill,
385
+ origin: (_b = existing === null || existing === void 0 ? void 0 : existing.origin) !== null && _b !== void 0 ? _b : origin,
386
+ parent_skill: parentSkill !== null && parentSkill !== void 0 ? parentSkill : existing === null || existing === void 0 ? void 0 : existing.parent_skill,
387
+ generation: generation !== null && generation !== void 0 ? generation : ((_c = existing === null || existing === void 0 ? void 0 : existing.generation) !== null && _c !== void 0 ? _c : 0),
388
+ version: `${((_d = existing === null || existing === void 0 ? void 0 : existing.evolution_count) !== null && _d !== void 0 ? _d : 0) + 1}.0.0`,
389
+ created_at: (_e = existing === null || existing === void 0 ? void 0 : existing.created_at) !== null && _e !== void 0 ? _e : now,
390
+ updated_at: now,
391
+ evolution_count: ((_f = existing === null || existing === void 0 ? void 0 : existing.evolution_count) !== null && _f !== void 0 ? _f : 0) + 1,
392
+ last_evolution_mode: origin.toUpperCase(),
393
+ };
394
+ fs_1.default.writeFileSync(recordsFile, JSON.stringify(records, null, 2));
395
+ }
396
+ loadSkillRecord(skill) {
397
+ var _a;
398
+ const recordsFile = path_1.default.join(this.projectPath, '.cm', 'evolution', 'records.json');
399
+ if (!fs_1.default.existsSync(recordsFile))
400
+ return null;
401
+ try {
402
+ const records = JSON.parse(fs_1.default.readFileSync(recordsFile, 'utf-8'));
403
+ return (_a = records[skill]) !== null && _a !== void 0 ? _a : null;
404
+ }
405
+ catch (_b) {
406
+ return null;
407
+ }
408
+ }
409
+ loadAllSkillRecords(limit) {
410
+ const recordsFile = path_1.default.join(this.projectPath, '.cm', 'evolution', 'records.json');
411
+ if (!fs_1.default.existsSync(recordsFile))
412
+ return [];
413
+ try {
414
+ const records = JSON.parse(fs_1.default.readFileSync(recordsFile, 'utf-8'));
415
+ return Object.values(records).slice(0, limit);
416
+ }
417
+ catch (_a) {
418
+ return [];
419
+ }
420
+ }
421
+ }
422
+ exports.SkillEvolver = SkillEvolver;
423
+ // ─── Display Helpers ─────────────────────────────────────────────────────────
424
+ function formatEvolutionResult(result) {
425
+ const icon = result.success ? '✅' : '❌';
426
+ const lines = [
427
+ `${icon} Skill Evolution — ${result.mode}`,
428
+ '─'.repeat(50),
429
+ `Skill: ${result.skill}`,
430
+ `Result: ${result.success ? 'Success' : 'Failed'}`,
431
+ ];
432
+ if (result.backupPath)
433
+ lines.push(`Backup: ${result.backupPath}`);
434
+ if (result.patchApplied)
435
+ lines.push(`Patch: ${result.patchApplied.split('\n')[0]}...`);
436
+ if (result.error)
437
+ lines.push(`Error: ${result.error}`);
438
+ return lines.join('\n');
439
+ }
440
+ function formatEvolutionHistory(history) {
441
+ if (history.length === 0)
442
+ return 'No evolution history recorded.';
443
+ const lines = [
444
+ '🧬 Evolution History',
445
+ '─'.repeat(70),
446
+ `${'Date'.padEnd(12)} ${'Skill'.padEnd(25)} ${'Mode'.padEnd(10)} ${'Conf'.padEnd(6)} Summary`,
447
+ '─'.repeat(70),
448
+ ];
449
+ for (const entry of history) {
450
+ const date = entry.created_at.split('T')[0];
451
+ const conf = (entry.confidence * 100).toFixed(0) + '%';
452
+ const summary = entry.patch_summary.split('\n')[0].slice(0, 30);
453
+ lines.push(`${date.padEnd(12)} ${entry.skill_name.padEnd(25)} ${entry.mode.padEnd(10)} ${conf.padEnd(6)} ${summary}`);
454
+ }
455
+ return lines.join('\n');
456
+ }