codymaster 4.8.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 (72) hide show
  1. package/CHANGELOG.md +55 -7
  2. package/README.md +142 -95
  3. package/dist/advisory-handoff.js +89 -0
  4. package/dist/advisory-report.js +105 -0
  5. package/dist/cli/command-registry.js +8 -0
  6. package/dist/cli/commands/bench.js +69 -0
  7. package/dist/cli/commands/brain.js +108 -0
  8. package/dist/cli/commands/engineering.js +108 -0
  9. package/dist/cli/commands/evolve.js +123 -0
  10. package/dist/cli/commands/mcp-serve.js +104 -0
  11. package/dist/cm-config.js +0 -18
  12. package/dist/codybench/judges/automated.js +31 -0
  13. package/dist/codybench/runners/claude-code.js +32 -0
  14. package/dist/codybench/suites/memory-retention.js +85 -0
  15. package/dist/codybench/suites/tdd-regression.js +35 -0
  16. package/dist/codybench/suites/token-efficiency.js +55 -0
  17. package/dist/codybench/types.js +2 -0
  18. package/dist/context-db.js +157 -0
  19. package/dist/continuity.js +2 -6
  20. package/dist/execution-analyzer.js +138 -0
  21. package/dist/indexer/skills-lib.js +533 -0
  22. package/dist/indexer/skills-map.js +1374 -0
  23. package/dist/indexer/skills.js +16 -0
  24. package/dist/learning-promoter.js +246 -0
  25. package/dist/mcp-context-server.js +230 -1
  26. package/dist/skill-chain.js +63 -1
  27. package/dist/skill-evolver.js +456 -0
  28. package/dist/skill-execution-cache.js +254 -0
  29. package/dist/smart-brain-router.js +184 -0
  30. package/dist/storage-backend.js +10 -8
  31. package/dist/token-budget.js +88 -0
  32. package/package.json +2 -3
  33. package/scripts/postinstall.js +10 -59
  34. package/skills/CLAUDE.md +0 -5
  35. package/skills/_shared/helpers.md +2 -8
  36. package/skills/cm-browse/SKILL.md +6 -0
  37. package/skills/cm-conductor-worktrees/SKILL.md +4 -0
  38. package/skills/cm-content-factory/landing/docs/content/changelog.md +4 -4
  39. package/skills/cm-content-factory/landing/docs/content/deployment.md +3 -3
  40. package/skills/cm-content-factory/landing/docs/content/execution-flow.md +8 -8
  41. package/skills/cm-content-factory/landing/docs/content/memory-system.md +38 -0
  42. package/skills/cm-content-factory/landing/docs/content/openspace.md +1 -1
  43. package/skills/cm-content-factory/landing/docs/content/use-cases.md +2 -2
  44. package/skills/cm-content-factory/landing/docs/content/v5-intro.md +3 -3
  45. package/skills/cm-content-factory/landing/docs/index.html +1 -1
  46. package/skills/cm-content-factory/landing/index.html +3 -3
  47. package/skills/cm-content-factory/landing/translations.js +37 -37
  48. package/skills/cm-continuity/SKILL.md +32 -33
  49. package/skills/cm-design-studio/SKILL.md +4 -0
  50. package/skills/cm-ecosystem-roadmap/SKILL.md +4 -0
  51. package/skills/cm-engineering-meta/SKILL.md +4 -0
  52. package/skills/cm-guardian-runtime/SKILL.md +5 -1
  53. package/skills/cm-mcp-engineering/SKILL.md +4 -0
  54. package/skills/cm-post-deploy-canary/SKILL.md +4 -0
  55. package/skills/cm-project-bootstrap/SKILL.md +11 -0
  56. package/skills/cm-qa-visual-cli/SKILL.md +4 -0
  57. package/skills/cm-retro-cli/SKILL.md +4 -0
  58. package/skills/cm-second-opinion-cli/SKILL.md +4 -0
  59. package/skills/cm-security-gate/SKILL.md +1 -0
  60. package/skills/cm-skill-chain/SKILL.md +25 -4
  61. package/skills/cm-skill-evolution/SKILL.md +83 -0
  62. package/skills/cm-skill-health/SKILL.md +83 -0
  63. package/skills/cm-skill-index/SKILL.md +11 -3
  64. package/skills/cm-skill-search/SKILL.md +49 -0
  65. package/skills/cm-skill-share/SKILL.md +58 -0
  66. package/skills/cm-sprint-bus/SKILL.md +4 -0
  67. package/skills/cm-start/SKILL.md +0 -10
  68. package/skills/cm-tdd/SKILL.md +2 -2
  69. package/skills/profiles/full.txt +4 -0
  70. package/install.sh +0 -1125
  71. package/scripts/viking-demo.ts +0 -105
  72. package/skills/cm-content-factory/landing/docs/content/openviking.md +0 -33
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateProjectSkillsIndex = generateProjectSkillsIndex;
4
+ const skills_lib_1 = require("./skills-lib");
5
+ /**
6
+ * Parses the project directory to detect the tech stack (using deterministic config file checks)
7
+ * and returns a miniaturized list of recommended AI skills.
8
+ */
9
+ function generateProjectSkillsIndex(projectDir) {
10
+ const { detected, isFrontend, combos } = (0, skills_lib_1.detectTechnologies)(projectDir);
11
+ const skills = (0, skills_lib_1.collectSkills)({ detected, isFrontend, combos });
12
+ return {
13
+ detectedTechnologies: detected.map((tech) => tech.name),
14
+ recommendedSkills: skills.map((s) => s.skill),
15
+ };
16
+ }
@@ -0,0 +1,246 @@
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.LearningPromoter = void 0;
7
+ exports.formatPromotionCandidates = formatPromotionCandidates;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const storage_backend_1 = require("./storage-backend");
11
+ // ─── Constants ──────────────────────────────────────────────────────────────
12
+ const MIN_REINFORCEMENT = 3; // Minimum times a learning must be reinforced
13
+ const MIN_PROMOTION_SCORE = 0.50; // Minimum score to qualify for promotion
14
+ const PROMOTION_LOG = '.cm/evolution/promotions.jsonl';
15
+ // ─── Learning Promoter ──────────────────────────────────────────────────────
16
+ // TRIZ #22 "Blessing in Disguise" — failures become reusable knowledge
17
+ /**
18
+ * LearningPromoter — Promotes mature learnings into reusable skills.
19
+ *
20
+ * When a learning has been reinforced enough times (appearing in multiple
21
+ * execution analyses or being manually confirmed), it graduates from
22
+ * ephemeral memory into a permanent skill entry.
23
+ *
24
+ * Flow:
25
+ * 1. Scan learnings in SQLite for candidates with high reinforcement
26
+ * 2. Score each candidate based on: reinforcement count, recency, category
27
+ * 3. Generate a minimal SKILL.md from the learning content
28
+ * 4. Save to skills/ directory
29
+ */
30
+ class LearningPromoter {
31
+ constructor(projectPath, backend) {
32
+ this.projectPath = projectPath;
33
+ this.backend = backend !== null && backend !== void 0 ? backend : (0, storage_backend_1.getBackend)(projectPath);
34
+ this.backend.initialize();
35
+ this.skillsDir = this.findSkillsDir();
36
+ }
37
+ /**
38
+ * Find learnings that qualify for promotion.
39
+ */
40
+ findCandidates(limit = 10) {
41
+ var _a;
42
+ // Query all learnings and count reinforcement (same what_failed pattern)
43
+ const allLearnings = this.backend.queryLearnings('', undefined, 200);
44
+ const patternCounts = new Map();
45
+ for (const learning of allLearnings) {
46
+ const pattern = this.normalizePattern(learning.what_failed);
47
+ const existing = (_a = patternCounts.get(pattern)) !== null && _a !== void 0 ? _a : { count: 0, learnings: [] };
48
+ existing.count++;
49
+ existing.learnings.push(learning);
50
+ patternCounts.set(pattern, existing);
51
+ }
52
+ const candidates = [];
53
+ for (const [_pattern, { count, learnings }] of patternCounts) {
54
+ if (count < MIN_REINFORCEMENT)
55
+ continue;
56
+ // Use the most recent learning as the representative
57
+ const representative = learnings.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
58
+ const score = this.calculateScore(count, representative);
59
+ if (score >= MIN_PROMOTION_SCORE) {
60
+ candidates.push({
61
+ learning: representative,
62
+ reinforcementCount: count,
63
+ score,
64
+ reason: `Reinforced ${count}x, score ${(score * 100).toFixed(0)}%`,
65
+ });
66
+ }
67
+ }
68
+ return candidates
69
+ .sort((a, b) => b.score - a.score)
70
+ .slice(0, limit);
71
+ }
72
+ /**
73
+ * Promote a specific learning to a skill.
74
+ */
75
+ promote(learningId) {
76
+ const learning = this.backend.getLearningById(learningId);
77
+ if (!learning) {
78
+ return {
79
+ promoted: false,
80
+ skillName: '',
81
+ skillPath: '',
82
+ learningId,
83
+ reason: `Learning ${learningId} not found.`,
84
+ };
85
+ }
86
+ // Generate skill name from the learning content
87
+ const skillName = this.generateSkillName(learning);
88
+ const skillDir = path_1.default.join(this.skillsDir, skillName);
89
+ if (fs_1.default.existsSync(skillDir)) {
90
+ return {
91
+ promoted: false,
92
+ skillName,
93
+ skillPath: skillDir,
94
+ learningId,
95
+ reason: `Skill ${skillName} already exists.`,
96
+ };
97
+ }
98
+ // Generate the SKILL.md content
99
+ const skillContent = this.generateSkillContent(learning, skillName);
100
+ // Create the skill
101
+ fs_1.default.mkdirSync(skillDir, { recursive: true });
102
+ const skillPath = path_1.default.join(skillDir, 'SKILL.md');
103
+ fs_1.default.writeFileSync(skillPath, skillContent, 'utf-8');
104
+ // Log the promotion
105
+ this.logPromotion(learningId, skillName, skillPath);
106
+ return {
107
+ promoted: true,
108
+ skillName,
109
+ skillPath,
110
+ learningId,
111
+ reason: `Learning promoted to skill: ${skillName}`,
112
+ };
113
+ }
114
+ /**
115
+ * Auto-promote: find candidates and promote the top one.
116
+ */
117
+ autoPromote() {
118
+ const candidates = this.findCandidates(1);
119
+ if (candidates.length === 0)
120
+ return null;
121
+ return this.promote(candidates[0].learning.id);
122
+ }
123
+ /**
124
+ * Get promotion history.
125
+ */
126
+ getPromotionHistory(limit = 20) {
127
+ const logPath = path_1.default.join(this.projectPath, PROMOTION_LOG);
128
+ if (!fs_1.default.existsSync(logPath))
129
+ return [];
130
+ const lines = fs_1.default.readFileSync(logPath, 'utf-8').trim().split('\n').filter(Boolean);
131
+ const entries = [];
132
+ for (const line of lines) {
133
+ try {
134
+ entries.push(JSON.parse(line));
135
+ }
136
+ catch ( /* skip */_a) { /* skip */ }
137
+ }
138
+ return entries.slice(-limit).reverse();
139
+ }
140
+ // ─── Private Helpers ────────────────────────────────────────────────────
141
+ findSkillsDir() {
142
+ const candidates = [
143
+ path_1.default.join(this.projectPath, 'skills'),
144
+ path_1.default.join(this.projectPath, '.agent', 'skills'),
145
+ ];
146
+ for (const dir of candidates) {
147
+ if (fs_1.default.existsSync(dir))
148
+ return dir;
149
+ }
150
+ return path_1.default.join(this.projectPath, 'skills');
151
+ }
152
+ normalizePattern(text) {
153
+ return text
154
+ .toLowerCase()
155
+ .replace(/[^\w\s]/g, '')
156
+ .replace(/\s+/g, ' ')
157
+ .trim()
158
+ .split(' ')
159
+ .sort()
160
+ .join(' ');
161
+ }
162
+ calculateScore(reinforcementCount, learning) {
163
+ // Reinforcement factor (0-0.5): more reinforcement = higher score
164
+ const reinforcementFactor = Math.min(0.5, reinforcementCount / 10);
165
+ // Recency factor (0-0.3): newer learnings score higher
166
+ const daysSince = (Date.now() - new Date(learning.created_at).getTime()) / (1000 * 60 * 60 * 24);
167
+ const recencyFactor = Math.max(0, 0.3 - (daysSince / 365) * 0.3);
168
+ // Content quality factor (0-0.2): longer, more detailed = better
169
+ const contentLength = (learning.what_failed.length + learning.how_to_prevent.length);
170
+ const qualityFactor = Math.min(0.2, contentLength / 500 * 0.2);
171
+ return reinforcementFactor + recencyFactor + qualityFactor;
172
+ }
173
+ generateSkillName(learning) {
174
+ const words = learning.what_failed
175
+ .toLowerCase()
176
+ .replace(/[^\w\s]/g, '')
177
+ .split(/\s+/)
178
+ .filter(w => w.length > 3)
179
+ .slice(0, 3);
180
+ const base = words.length > 0 ? words.join('-') : 'promoted';
181
+ return `cm-learned-${base}`;
182
+ }
183
+ generateSkillContent(learning, skillName) {
184
+ return [
185
+ '---',
186
+ `name: ${skillName}`,
187
+ `description: Auto-promoted from reinforced learning`,
188
+ '---',
189
+ '',
190
+ `# ${skillName}`,
191
+ '',
192
+ `> 🎓 Auto-promoted from learning on ${new Date().toISOString().split('T')[0]}`,
193
+ `> Original module: ${learning.module}`,
194
+ `> Agent: ${learning.agent}`,
195
+ '',
196
+ '## Problem Pattern',
197
+ '',
198
+ learning.what_failed,
199
+ '',
200
+ '## Root Cause',
201
+ '',
202
+ learning.why_failed,
203
+ '',
204
+ '## Prevention / Solution',
205
+ '',
206
+ learning.how_to_prevent,
207
+ '',
208
+ '## When to Apply',
209
+ '',
210
+ `Apply this skill when encountering patterns similar to: "${learning.what_failed.slice(0, 100)}"`,
211
+ '',
212
+ '## Steps',
213
+ '',
214
+ `1. Recognize the problem pattern described above`,
215
+ `2. Apply the prevention strategy: ${learning.how_to_prevent.slice(0, 100)}`,
216
+ `3. Verify the fix resolves the root cause`,
217
+ '',
218
+ ].join('\n');
219
+ }
220
+ logPromotion(learningId, skillName, skillPath) {
221
+ const logPath = path_1.default.join(this.projectPath, PROMOTION_LOG);
222
+ const dir = path_1.default.dirname(logPath);
223
+ if (!fs_1.default.existsSync(dir))
224
+ fs_1.default.mkdirSync(dir, { recursive: true });
225
+ const entry = { learningId, skillName, skillPath, promotedAt: new Date().toISOString() };
226
+ fs_1.default.appendFileSync(logPath, JSON.stringify(entry) + '\n');
227
+ }
228
+ }
229
+ exports.LearningPromoter = LearningPromoter;
230
+ // ─── Display Helpers ─────────────────────────────────────────────────────────
231
+ function formatPromotionCandidates(candidates) {
232
+ if (candidates.length === 0)
233
+ return 'No learnings qualify for promotion yet. Need ≥3 reinforcements.';
234
+ const lines = [
235
+ '🎓 Learning → Skill Promotion Candidates',
236
+ '─'.repeat(70),
237
+ `${'Score'.padEnd(8)} ${'Reinf'.padEnd(8)} Pattern`,
238
+ '─'.repeat(70),
239
+ ];
240
+ for (const c of candidates) {
241
+ const score = (c.score * 100).toFixed(0) + '%';
242
+ const pattern = c.learning.what_failed.slice(0, 50);
243
+ lines.push(`${score.padEnd(8)} ${(c.reinforcementCount + 'x').padEnd(8)} ${pattern}`);
244
+ }
245
+ return lines.join('\n');
246
+ }
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * CodyMaster MCP Context Server
5
5
  *
6
- * Exposes 13 tools over JSON-RPC 2.0 / stdio (Content-Length framing):
6
+ * Exposes 18 tools over JSON-RPC 2.0 / stdio (Content-Length framing):
7
7
  * cm_query — FTS5 search across learnings + decisions
8
8
  * cm_resolve — resolve a cm:// URI at L0/L1/L2
9
9
  * cm_bus_read — read context bus state
@@ -11,6 +11,7 @@
11
11
  * cm_budget_check — check token budget for a category
12
12
  * cm_memory_decay — TTL cleanup for learnings
13
13
  * cm_index_refresh — regenerate L0 indexes
14
+ * cm_advisory_report / cm_advisory_metrics / cm_advisory_handoff — advisory loop JSON surfaces
14
15
  * cm_plan / cm_review / cm_qa / cm_deploy / cm_search / cm_memory_query — engineering kit bridge
15
16
  *
16
17
  * Usage (stdio MCP):
@@ -39,6 +40,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
40
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
41
  };
41
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.cmAdvisoryReport = cmAdvisoryReport;
44
+ exports.cmAdvisoryMetrics = cmAdvisoryMetrics;
45
+ exports.cmAdvisoryHandoff = cmAdvisoryHandoff;
42
46
  const path_1 = __importDefault(require("path"));
43
47
  const context_db_1 = require("./context-db");
44
48
  const uri_resolver_1 = require("./uri-resolver");
@@ -46,6 +50,9 @@ const context_bus_1 = require("./context-bus");
46
50
  const token_budget_1 = require("./token-budget");
47
51
  const l0_indexer_1 = require("./l0-indexer");
48
52
  const mcp_skills_tools_1 = require("./mcp-skills-tools");
53
+ const storage_backend_1 = require("./storage-backend");
54
+ const advisory_report_1 = require("./advisory-report");
55
+ const advisory_handoff_1 = require("./advisory-handoff");
49
56
  // ─── Config ──────────────────────────────────────────────────────────────────
50
57
  const SERVER_NAME = 'cm-context';
51
58
  const SERVER_VERSION = '1.0.0';
@@ -132,6 +139,84 @@ function cmBudgetCheck(args) {
132
139
  suggestion: check.suggestion,
133
140
  };
134
141
  }
142
+ function autoDetectCategory(content) {
143
+ const c = content.toLowerCase();
144
+ if (/\b(decided|architecture|we chose|design decision|chose to)\b/.test(c))
145
+ return 'arch_decision';
146
+ if (/\b(bug|fixed|caused by|root cause|crash)\b/.test(c))
147
+ return 'bug_fix';
148
+ if (/\b(prefer|always use|never use|avoid|convention|standard)\b/.test(c))
149
+ return 'user_pref';
150
+ if (/\b(function|pattern|approach|method|implementation)\b/.test(c))
151
+ return 'code_pattern';
152
+ return 'context';
153
+ }
154
+ function cmMemoryWrite(args) {
155
+ var _a;
156
+ const { content, scope = 'project', category, ttl_days, importance = 'medium' } = args;
157
+ if (!(content === null || content === void 0 ? void 0 : content.trim()))
158
+ throw new Error('content is required');
159
+ const detectedCategory = category || autoDetectCategory(content);
160
+ const defaultTtl = { session: 30, project: 90, global: 365 };
161
+ const ttl = (_a = ttl_days !== null && ttl_days !== void 0 ? ttl_days : defaultTtl[scope]) !== null && _a !== void 0 ? _a : 90;
162
+ const now = new Date().toISOString();
163
+ const id = `nli-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
164
+ const dbPath = (0, context_db_1.getDbPath)(PROJECT_PATH);
165
+ (0, context_db_1.insertLearning)(dbPath, {
166
+ id,
167
+ what_failed: content,
168
+ why_failed: detectedCategory,
169
+ how_to_prevent: `importance:${importance}`,
170
+ scope,
171
+ ttl,
172
+ reinforce_count: 0,
173
+ status: 'active',
174
+ created_at: now,
175
+ updated_at: now,
176
+ agent: 'cm_natural',
177
+ });
178
+ return { ok: true, id, content, category: detectedCategory, scope, ttl_days: ttl, importance };
179
+ }
180
+ const NLI_PATTERNS = [
181
+ { pattern: /\b(remember|save|note)\s+that\s+/i, action: 'write', scope: 'project' },
182
+ { pattern: /\b(remember|save)\s+this[:\s]/i, action: 'write', scope: 'project' },
183
+ { pattern: /\bimportant[:\s]+/i, action: 'write', scope: 'project', importance: 'high' },
184
+ { pattern: /\b(forget|remove|ignore)\s+(about\s+)?/i, action: 'decay' },
185
+ { pattern: /\bwhat\s+did\s+we\s+(learn|know)\b/i, action: 'query' },
186
+ { pattern: /\bwhat\s+do\s+we\s+know\b/i, action: 'query' },
187
+ { pattern: /\blessons?\s+learned\b/i, action: 'query' },
188
+ { pattern: /\b(search|find|look\s+up)\b/i, action: 'query' },
189
+ ];
190
+ function cmNatural(args) {
191
+ var _a, _b, _c;
192
+ const { text } = args;
193
+ if (!(text === null || text === void 0 ? void 0 : text.trim()))
194
+ throw new Error('text is required');
195
+ for (const rule of NLI_PATTERNS) {
196
+ const match = text.match(rule.pattern);
197
+ if (!match)
198
+ continue;
199
+ const extracted = text.slice(((_a = match.index) !== null && _a !== void 0 ? _a : 0) + match[0].length).trim();
200
+ if (rule.action === 'write') {
201
+ const result = cmMemoryWrite({
202
+ content: extracted || text,
203
+ scope: (_b = rule.scope) !== null && _b !== void 0 ? _b : 'project',
204
+ importance: (_c = rule.importance) !== null && _c !== void 0 ? _c : 'medium',
205
+ });
206
+ return Object.assign(Object.assign({}, result), { matched_pattern: rule.pattern.source, routed_to: 'cm_memory_write' });
207
+ }
208
+ if (rule.action === 'decay') {
209
+ const result = cmMemoryDecay({ dry_run: false });
210
+ return Object.assign(Object.assign({}, result), { matched_pattern: rule.pattern.source, routed_to: 'cm_memory_decay' });
211
+ }
212
+ // query / search
213
+ const result = cmQuery({ query: extracted || text, scope: 'all', limit: 10 });
214
+ return Object.assign(Object.assign({}, result), { matched_pattern: rule.pattern.source, routed_to: 'cm_query' });
215
+ }
216
+ // No pattern matched — default to search
217
+ const result = cmQuery({ query: text, scope: 'all', limit: 10 });
218
+ return Object.assign(Object.assign({}, result), { matched_pattern: null, routed_to: 'cm_query (default)' });
219
+ }
135
220
  function cmMemoryDecay(args) {
136
221
  const { dry_run = false } = args;
137
222
  const dbPath = (0, context_db_1.getDbPath)(PROJECT_PATH);
@@ -188,6 +273,55 @@ function cmIndexRefresh(args) {
188
273
  }
189
274
  throw new Error(`Unknown target: ${target}. Valid: learnings, skeleton, all`);
190
275
  }
276
+ function cmAdvisoryReport(args) {
277
+ var _a;
278
+ const backend = (0, storage_backend_1.getBackend)(PROJECT_PATH);
279
+ backend.initialize();
280
+ try {
281
+ const limit = Math.max(1, (_a = args.limit) !== null && _a !== void 0 ? _a : 10);
282
+ const analyses = (0, advisory_report_1.buildAdvisoryReportData)(backend, { limit });
283
+ return {
284
+ count: analyses.length,
285
+ analyses,
286
+ generated_at: new Date().toISOString(),
287
+ };
288
+ }
289
+ finally {
290
+ backend.close();
291
+ }
292
+ }
293
+ function cmAdvisoryMetrics(args) {
294
+ var _a;
295
+ const backend = (0, storage_backend_1.getBackend)(PROJECT_PATH);
296
+ backend.initialize();
297
+ try {
298
+ const limit = Math.max(1, (_a = args.limit) !== null && _a !== void 0 ? _a : 10);
299
+ const metrics = (0, advisory_report_1.buildAdvisoryMetricsData)(backend, { limit });
300
+ return {
301
+ count: metrics.length,
302
+ metrics,
303
+ generated_at: new Date().toISOString(),
304
+ };
305
+ }
306
+ finally {
307
+ backend.close();
308
+ }
309
+ }
310
+ function cmAdvisoryHandoff(args) {
311
+ const backend = (0, storage_backend_1.getBackend)(PROJECT_PATH);
312
+ backend.initialize();
313
+ try {
314
+ return (0, advisory_handoff_1.buildAdvisoryHandoff)(backend, {
315
+ consumer: args.consumer,
316
+ analysisId: args.analysis_id,
317
+ skill: args.skill,
318
+ searchLimit: args.limit,
319
+ });
320
+ }
321
+ finally {
322
+ backend.close();
323
+ }
324
+ }
191
325
  // ─── Tool Registry ─────────────────────────────────────────────────────────────
192
326
  const TOOLS = [
193
327
  {
@@ -297,6 +431,53 @@ const TOOLS = [
297
431
  },
298
432
  },
299
433
  },
434
+ {
435
+ name: 'cm_advisory_report',
436
+ description: 'Return recent advisory analyses as structured JSON for agent consumption.',
437
+ inputSchema: {
438
+ type: 'object',
439
+ properties: {
440
+ limit: { type: 'number', description: 'Max analyses to return (default: 10)' },
441
+ },
442
+ },
443
+ },
444
+ {
445
+ name: 'cm_advisory_metrics',
446
+ description: 'Return aggregated skill metrics and quality weights as structured JSON.',
447
+ inputSchema: {
448
+ type: 'object',
449
+ properties: {
450
+ limit: { type: 'number', description: 'Max skills to return (default: 10)' },
451
+ },
452
+ },
453
+ },
454
+ {
455
+ name: 'cm_advisory_handoff',
456
+ description: 'Build a structured advisory handoff for cm-skill-health or cm-skill-evolution.',
457
+ inputSchema: {
458
+ type: 'object',
459
+ properties: {
460
+ consumer: {
461
+ type: 'string',
462
+ enum: ['cm-skill-health', 'cm-skill-evolution'],
463
+ description: 'Which self-healing skill should consume the handoff',
464
+ },
465
+ analysis_id: {
466
+ type: 'string',
467
+ description: 'Optional analysis id prefix (defaults to latest advisory analysis)',
468
+ },
469
+ skill: {
470
+ type: 'string',
471
+ description: 'Optional skill override when the target skill should be forced',
472
+ },
473
+ limit: {
474
+ type: 'number',
475
+ description: 'How many recent analyses to search while resolving analysis_id (default: 50)',
476
+ },
477
+ },
478
+ required: ['consumer'],
479
+ },
480
+ },
300
481
  {
301
482
  name: 'cm_plan',
302
483
  description: 'Sprint + context bus snapshot: pipeline state, next skill hint, artifact paths.',
@@ -342,6 +523,44 @@ const TOOLS = [
342
523
  required: ['query'],
343
524
  },
344
525
  },
526
+ {
527
+ name: 'cm_memory_write',
528
+ description: 'Write a new memory/learning to persistent storage. Use to save knowledge, decisions, preferences, or patterns for future sessions.',
529
+ inputSchema: {
530
+ type: 'object',
531
+ properties: {
532
+ content: { type: 'string', description: 'What to remember (the memory content)' },
533
+ scope: {
534
+ type: 'string',
535
+ enum: ['session', 'project', 'global'],
536
+ description: 'Memory scope: session=30d, project=90d, global=365d (default: project)',
537
+ },
538
+ category: {
539
+ type: 'string',
540
+ enum: ['code_pattern', 'arch_decision', 'bug_fix', 'user_pref', 'context'],
541
+ description: 'Category (auto-detected from content if omitted)',
542
+ },
543
+ ttl_days: { type: 'number', description: 'Override TTL in days' },
544
+ importance: {
545
+ type: 'string',
546
+ enum: ['low', 'medium', 'high'],
547
+ description: 'Importance level (default: medium)',
548
+ },
549
+ },
550
+ required: ['content'],
551
+ },
552
+ },
553
+ {
554
+ name: 'cm_natural',
555
+ description: 'Natural language memory interface. Understands "remember that...", "forget about...", "what did we learn about...", "find...". Routes to appropriate memory operation automatically.',
556
+ inputSchema: {
557
+ type: 'object',
558
+ properties: {
559
+ text: { type: 'string', description: 'Freeform natural language instruction or question' },
560
+ },
561
+ required: ['text'],
562
+ },
563
+ },
345
564
  ];
346
565
  // ─── MCP stdio protocol (JSON-RPC 2.0, Content-Length framing) ───────────────
347
566
  function sendMessage(msg) {
@@ -391,6 +610,12 @@ function handleRequest(msg) {
391
610
  result = cmMemoryDecay(a);
392
611
  else if (name === 'cm_index_refresh')
393
612
  result = cmIndexRefresh(a);
613
+ else if (name === 'cm_advisory_report')
614
+ result = cmAdvisoryReport(a);
615
+ else if (name === 'cm_advisory_metrics')
616
+ result = cmAdvisoryMetrics(a);
617
+ else if (name === 'cm_advisory_handoff')
618
+ result = cmAdvisoryHandoff(a);
394
619
  else if (name === 'cm_plan')
395
620
  result = (0, mcp_skills_tools_1.cmPlanTool)(PROJECT_PATH);
396
621
  else if (name === 'cm_review')
@@ -403,6 +628,10 @@ function handleRequest(msg) {
403
628
  result = (0, mcp_skills_tools_1.cmSearchTool)(PROJECT_PATH, a);
404
629
  else if (name === 'cm_memory_query')
405
630
  result = (0, mcp_skills_tools_1.cmMemoryQueryTool)(PROJECT_PATH, a);
631
+ else if (name === 'cm_memory_write')
632
+ result = cmMemoryWrite(a);
633
+ else if (name === 'cm_natural')
634
+ result = cmNatural(a);
406
635
  else
407
636
  throw new Error(`Unknown tool: ${name}`);
408
637
  respond(id, {
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.matchChain = matchChain;
7
+ exports.scoreStepRelevance = scoreStepRelevance;
8
+ exports.selectTopSkills = selectTopSkills;
7
9
  exports.listChains = listChains;
8
10
  exports.findChain = findChain;
9
11
  exports.createChainExecution = createChainExecution;
@@ -17,6 +19,8 @@ exports.getCurrentSkill = getCurrentSkill;
17
19
  const crypto_1 = __importDefault(require("crypto"));
18
20
  const builtin_1 = require("./chains/builtin");
19
21
  const context_bus_1 = require("./context-bus");
22
+ const execution_analyzer_1 = require("./execution-analyzer");
23
+ const storage_backend_1 = require("./storage-backend");
20
24
  // ─── Chain Matching ─────────────────────────────────────────────────────────
21
25
  // TRIZ #10: Preliminary Action — analyze task BEFORE dispatching
22
26
  /**
@@ -43,6 +47,53 @@ function matchChain(taskTitle) {
43
47
  }
44
48
  return bestMatch;
45
49
  }
50
+ // ─── Intelligent Skill Selection (SkillsBench: 2-3 skills = +18.6pp) ────────
51
+ // TRIZ #1: Segmentation — select only relevant sub-components
52
+ /**
53
+ * Score a single chain step's relevance to the given task title.
54
+ * Mandatory steps (optional=false, condition='always') receive a +100 base bonus
55
+ * to ensure they are always prioritised over optional ones.
56
+ */
57
+ function scoreStepRelevance(taskTitle, step) {
58
+ const taskTokens = new Set(taskTitle.toLowerCase().split(/\W+/).filter(t => t.length > 2));
59
+ const descTokens = step.description.toLowerCase().split(/\W+/).filter(t => t.length > 2);
60
+ const overlap = descTokens.filter(t => taskTokens.has(t)).length;
61
+ const mandatoryBonus = (!step.optional && step.condition === 'always') ? 100 : 0;
62
+ return overlap + mandatoryBonus;
63
+ }
64
+ /**
65
+ * Select the most relevant skills for a task, capped at maxSkills.
66
+ *
67
+ * Rules:
68
+ * - Mandatory steps (optional=false AND condition='always') are ALWAYS included,
69
+ * even if their count exceeds maxSkills (safety > optimisation).
70
+ * - Remaining slots are filled with the highest-scoring optional steps.
71
+ * - If mandatory count > maxSkills, a performance warning is emitted.
72
+ */
73
+ function selectTopSkills(taskTitle, chain, maxSkills = 3, options = {}) {
74
+ const mandatory = chain.steps.filter(s => !s.optional && s.condition === 'always');
75
+ const optional = chain.steps.filter(s => s.optional || s.condition !== 'always');
76
+ if (mandatory.length > maxSkills) {
77
+ process.stderr.write(`[CodyMaster] Chain "${chain.name}" has ${mandatory.length} mandatory steps (>${maxSkills}). ` +
78
+ `Consider splitting this chain. (SkillsBench: 2-3 skills = +18.6pp)\n`);
79
+ return mandatory; // include all mandatory — cannot safely drop them
80
+ }
81
+ const remaining = maxSkills - mandatory.length;
82
+ const scoredOptional = optional
83
+ .map(step => {
84
+ var _a, _b;
85
+ const relevance = scoreStepRelevance(taskTitle, step);
86
+ const metric = (_b = (_a = options.getSkillMetric) === null || _a === void 0 ? void 0 : _a.call(options, step.skill)) !== null && _b !== void 0 ? _b : null;
87
+ const quality = (0, execution_analyzer_1.qualityWeight)(metric);
88
+ return { step, score: relevance + quality, relevance, quality };
89
+ })
90
+ .sort((a, b) => b.score - a.score)
91
+ .slice(0, remaining)
92
+ .map(({ step }) => step);
93
+ // Preserve original chain order
94
+ const selected = new Set([...mandatory, ...scoredOptional]);
95
+ return chain.steps.filter(s => selected.has(s));
96
+ }
46
97
  /**
47
98
  * List all available chains (built-in + user-defined in the future).
48
99
  */
@@ -62,7 +113,18 @@ function findChain(chainId) {
62
113
  */
63
114
  function createChainExecution(chain, projectId, taskTitle, agent, projectPath) {
64
115
  const now = new Date().toISOString();
65
- const steps = chain.steps.map((step, index) => ({
116
+ const backend = projectPath ? (0, storage_backend_1.getBackend)(projectPath) : undefined;
117
+ let selectedSteps;
118
+ backend === null || backend === void 0 ? void 0 : backend.initialize();
119
+ try {
120
+ selectedSteps = selectTopSkills(taskTitle, chain, 3, {
121
+ getSkillMetric: backend ? (skill) => backend.getSkillMetric(skill) : undefined,
122
+ });
123
+ }
124
+ finally {
125
+ backend === null || backend === void 0 ? void 0 : backend.close();
126
+ }
127
+ const steps = selectedSteps.map((step, index) => ({
66
128
  index,
67
129
  skill: step.skill,
68
130
  description: step.description,