fraim 2.0.280 → 2.0.283

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 (31) hide show
  1. package/README.md +467 -467
  2. package/bin/fraim.js +12 -12
  3. package/dist/src/cli/mcp/fraim-mcp-latest-launcher.js +266 -182
  4. package/dist/src/cli/mcp/mcp-server-registry.js +11 -3
  5. package/dist/src/cli/setup/ide-invocation-surfaces.js +64 -64
  6. package/dist/src/cli/utils/agent-adapters.js +61 -61
  7. package/dist/src/core/ai-mentor.js +35 -0
  8. package/dist/src/core/handoff-contracts.js +73 -46
  9. package/dist/src/core/resolve-phase-edge.js +33 -0
  10. package/dist/src/core/utils/stub-generator.js +53 -53
  11. package/dist/src/first-run/server.js +5 -1
  12. package/dist/src/first-run/session-service.js +48 -12
  13. package/dist/src/fraim/issues.js +4 -4
  14. package/dist/src/local-mcp-server/stdio-server.js +43 -4
  15. package/dist/src/mcp/tool-schemas.js +40 -40
  16. package/dist/src/middleware/telemetry.js +21 -21
  17. package/dist/src/services/email-service.js +623 -623
  18. package/dist/src/services/installer-service.js +22 -22
  19. package/index.js +83 -83
  20. package/package.json +59 -59
  21. package/public/first-run/error-frame.js +100 -100
  22. package/public/first-run/index.html +35 -35
  23. package/public/first-run/script.js +747 -742
  24. package/public/first-run/styles.css +929 -929
  25. package/dist/src/cli/commands/learning-usage.js +0 -412
  26. package/dist/src/cli/commands/test-mcp.js +0 -171
  27. package/dist/src/cli/setup/first-run.js +0 -242
  28. package/dist/src/core/config-writer.js +0 -75
  29. package/dist/src/core/utils/job-aliases.js +0 -47
  30. package/dist/src/core/utils/workflow-parser.js +0 -174
  31. package/dist/src/services/email-service-clean.js +0 -782
@@ -1,412 +0,0 @@
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.learningUsageCommand = void 0;
7
- /**
8
- * Issue #1103 — `fraim learning-usage <subcommand>`.
9
- *
10
- * The read and analysis side of the usage record. The write side of an offer is the
11
- * proxy (no agent involvement, R2); the write side of a firing is an attestation in
12
- * a retrospective, which `record-firings` reads back.
13
- *
14
- * This is a CLI rather than a new MCP tool deliberately: the store schema then has
15
- * exactly one implementation, and nothing is added to the MCP tool surface that
16
- * issues #801, #860 and #861 are working to shrink.
17
- */
18
- const commander_1 = require("commander");
19
- const node_fs_1 = __importDefault(require("node:fs"));
20
- const node_path_1 = __importDefault(require("node:path"));
21
- const learning_context_builder_1 = require("../../local-mcp-server/learning-context-builder");
22
- const learning_usage_analysis_1 = require("../../local-mcp-server/learning-usage-analysis");
23
- const learning_usage_store_1 = require("../../local-mcp-server/learning-usage-store");
24
- const learning_usage_attestation_1 = require("../../local-mcp-server/learning-usage-attestation");
25
- function resolveWorkspaceRoot(options) {
26
- return node_path_1.default.resolve(options.workspaceRoot || options.root || process.cwd());
27
- }
28
- function resolveUser(options) {
29
- const email = options.user || process.env.FRAIM_ACTIVE_USER_EMAIL || '';
30
- if (!email.trim()) {
31
- throw new Error('Missing active user email. Pass --user <email> or set FRAIM_ACTIVE_USER_EMAIL.');
32
- }
33
- return email.trim();
34
- }
35
- function emit(payload, json, text) {
36
- process.stdout.write(json ? `${JSON.stringify(payload, null, 2)}\n` : `${text()}\n`);
37
- }
38
- function addCommonOptions(command) {
39
- return command
40
- .option('--workspace-root <path>', 'Workspace root containing fraim/config.json')
41
- .option('--root <path>', 'Alias for --workspace-root')
42
- .option('--user <email>', 'Active user email')
43
- .option('--json', 'Print JSON');
44
- }
45
- // ── offers ───────────────────────────────────────────────────────────────────
46
- const offersCommand = addCommonOptions(new commander_1.Command('offers'))
47
- .description('List the learning entries and rule files the runtime delivered, so an attestation is written against the record rather than memory')
48
- .option('--job <name>', 'The job whose context was loaded', 'unknown')
49
- .option('--domain <domain>', 'Learning domain the job resolved to')
50
- .option('--session', 'Use the session frame rather than the job frame')
51
- .action((options) => {
52
- const workspaceRoot = resolveWorkspaceRoot(options);
53
- const user = resolveUser(options);
54
- const forJob = !options.session;
55
- // Prefer what the runtime recorded for this job, because that is what was
56
- // actually delivered. Re-deriving from the files on disk answers a subtly
57
- // different question — what would be delivered now — and the two diverge if a
58
- // learning file changed during the job.
59
- const store = (0, learning_usage_store_1.readUsageStore)();
60
- const recorded = Object.values(store.entries)
61
- .filter((entry) => entry.offered.log.some((offer) => offer.job === options.job))
62
- .map((entry) => {
63
- const last = [...entry.offered.log].reverse().find((offer) => offer.job === options.job);
64
- return {
65
- key: entry.key,
66
- family: entry.family,
67
- id: entry.key.startsWith('L-') ? entry.key : null,
68
- title: entry.titles[entry.titles.length - 1] ?? entry.key,
69
- fileType: entry.fileType ?? 'unknown',
70
- level: entry.level ?? 'unknown',
71
- displayPath: '',
72
- severity: null,
73
- aboveThreshold: last.aboveThreshold,
74
- };
75
- });
76
- const source = recorded.length > 0 ? 'offer-record' : 'derived';
77
- const offered = recorded.length > 0
78
- ? recorded
79
- : [
80
- ...(0, learning_context_builder_1.collectOfferedLearningEntries)(workspaceRoot, user, forJob, options.domain ?? null),
81
- ...(0, learning_context_builder_1.collectOfferedRuleFiles)(workspaceRoot, forJob),
82
- ];
83
- const payload = { job: options.job, forJob, source, offered };
84
- emit(payload, options.json, () => {
85
- if (payload.offered.length === 0) {
86
- return `No offer record and nothing resolves for job ${options.job}. Do not attest any firing for this job.`;
87
- }
88
- const rows = payload.offered.map((o) => `| ${o.id ?? '(no id)'} | ${o.title} | ${o.fileType} | ${o.aboveThreshold ? 'yes' : 'no'} |`);
89
- const header = source === 'offer-record'
90
- ? `Entries offered for job ${options.job}, from the offer record:`
91
- : `No offer record exists for job ${options.job} yet, so this is what would be delivered now. Say so when you attest against it.`;
92
- return [
93
- header,
94
- '',
95
- '| Id | Title | Family | Above threshold |',
96
- '|---|---|---|---|',
97
- ...rows,
98
- ].join('\n');
99
- });
100
- });
101
- // ── record-firings ───────────────────────────────────────────────────────────
102
- const recordFiringsCommand = addCommonOptions(new commander_1.Command('record-firings'))
103
- .description('Read the firing section of a retrospective and write the attested firings into the usage record')
104
- .requiredOption('--retrospective <path>', 'Retrospective file to read')
105
- .option('--job <name>', 'The job that produced the retrospective')
106
- .option('--agent <name>', 'Agent that attested')
107
- .option('--model <model>', 'Model that attested')
108
- .option('--legacy', 'Also accept the pre-#1103 prose form')
109
- .action((options) => {
110
- const workspaceRoot = resolveWorkspaceRoot(options);
111
- const user = resolveUser(options);
112
- const filePath = node_path_1.default.resolve(options.retrospective);
113
- if (!node_fs_1.default.existsSync(filePath)) {
114
- throw new Error(`Retrospective not found: ${filePath}`);
115
- }
116
- const content = node_fs_1.default.readFileSync(filePath, 'utf8');
117
- const source = node_path_1.default.relative(workspaceRoot, filePath).replace(/\\/g, '/');
118
- const result = (0, learning_usage_attestation_1.recordAttestationsFromRetrospective)(workspaceRoot, user, {
119
- content,
120
- source,
121
- job: options.job ?? 'unknown',
122
- agent: options.agent ?? null,
123
- model: options.model ?? null,
124
- legacy: Boolean(options.legacy),
125
- });
126
- emit(result, options.json, () => {
127
- const lines = [
128
- `Section state: ${result.sectionState}`,
129
- `Items read: ${result.itemsRead}`,
130
- `Recorded: ${result.applied}`,
131
- `Already recorded: ${result.alreadyRecorded}`,
132
- `Unmatched: ${result.unmatched.length}`,
133
- `Rejected: ${result.rejected.length}`,
134
- ];
135
- for (const item of result.unmatched)
136
- lines.push(` unmatched: ${item.title} — ${item.reason}`);
137
- for (const item of result.rejected)
138
- lines.push(` rejected: ${item.reason}`);
139
- return lines.join('\n');
140
- });
141
- });
142
- // ── classify ─────────────────────────────────────────────────────────────────
143
- const classifyCommand = addCommonOptions(new commander_1.Command('classify'))
144
- .description('Say whether a recurrence was ignored (the entry was in context) or not-offered (it never reached the agent), because the two need different fixes')
145
- .option('--entry <id>', 'The entry id, for an entry that carries one')
146
- .option('--title <title>', 'The exact entry title, for an entry with no id yet. Use with --family')
147
- .option('--family <family>', 'The entry family: mistake-patterns, preferences, validated-patterns, or manager-coaching')
148
- .requiredOption('--job <name>', 'The job the recurrence happened in')
149
- .requiredOption('--date <YYYY-MM-DD>', 'The date the mistake recurred')
150
- .option('--window <days>', 'How far back an offer still counts as in-context', '30')
151
- .action((options) => {
152
- const workspaceRoot = resolveWorkspaceRoot(options);
153
- // `--title` plus `--family` exists so a caller never has to build the composite
154
- // title key by hand. An entry title is corpus content and can contain any
155
- // character, so an agent assembling `T:<family>:<title>` into a shell command
156
- // would be interpolating untrusted text into a command line. Passing the title
157
- // as its own argument keeps it a single argv entry.
158
- let key;
159
- if (options.entry) {
160
- key = String(options.entry);
161
- }
162
- else if (options.title && options.family) {
163
- key = (0, learning_usage_store_1.titleUsageKey)(String(options.family), String(options.title));
164
- }
165
- else {
166
- throw new Error('Pass --entry <id>, or --title <title> together with --family <family>.');
167
- }
168
- const store = (0, learning_usage_store_1.readUsageStore)();
169
- const diagnosis = (0, learning_usage_analysis_1.classifyRecurrence)(store, {
170
- key,
171
- job: options.job,
172
- date: options.date,
173
- windowDays: Number.parseInt(options.window, 10) || 30,
174
- });
175
- void workspaceRoot;
176
- emit(diagnosis, options.json, () => [
177
- `Classification: ${diagnosis.classification}`,
178
- `Diagnosis: ${diagnosis.diagnosis}`,
179
- `Recommendation: ${diagnosis.recommendation}`,
180
- `Raise the recurrence count: ${diagnosis.recurrenceBump ? 'yes' : 'no'}`,
181
- ].join('\n'));
182
- });
183
- // ── candidates ───────────────────────────────────────────────────────────────
184
- const candidatesCommand = addCommonOptions(new commander_1.Command('candidates'))
185
- .description('List retirement candidates: offered often under the current model with no firing under it, paired with a structural signal')
186
- .option('--model <model>', 'Override the current model (defaults to the most recently offered-to model)')
187
- .option('--detector <path>', 'Path to the corpus hygiene detector that provides the structural signal')
188
- .action((options) => {
189
- const workspaceRoot = resolveWorkspaceRoot(options);
190
- const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
191
- const result = (0, learning_usage_analysis_1.findRetirementCandidates)((0, learning_usage_store_1.readUsageStore)(), {
192
- workspaceRoot,
193
- limits,
194
- currentModel: options.model ?? undefined,
195
- structuralSignalPath: options.detector,
196
- });
197
- emit(result, options.json, () => {
198
- if (result.candidates.length === 0) {
199
- return `No retirement candidates. Current model: ${result.currentModel ?? 'unknown'}; threshold ${result.offerThreshold} offers.`;
200
- }
201
- const lines = [`Current model: ${result.currentModel ?? 'unknown'}. Threshold: ${result.offerThreshold} offers.`, ''];
202
- for (const c of result.candidates) {
203
- const earlier = c.firedUnderEarlierModels.map((m) => `${m.count} under ${m.model}`).join(', ') || 'none under any earlier model';
204
- lines.push(`- ${c.title}`, ` Offered ${c.offeredUnderCurrentModel} times under the current model, fired ${c.firedUnderCurrentModel}. Earlier: ${earlier}.`, ` Structural signal: ${c.structural}. ${c.structuralDetail}`, ` Recommendation: ${c.recommendation}`);
205
- }
206
- return lines.join('\n');
207
- });
208
- });
209
- // ── standing ─────────────────────────────────────────────────────────────────
210
- const standingCommand = addCommonOptions(new commander_1.Command('standing'))
211
- .description('Assess each entry as promoted, standard or demoted from its usage record, and list the ones whose standing should change')
212
- .option('--changes-only', 'Print only the entries whose standing should change')
213
- .action((options) => {
214
- const workspaceRoot = resolveWorkspaceRoot(options);
215
- const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
216
- const report = (0, learning_usage_analysis_1.assessStanding)((0, learning_usage_store_1.readUsageStore)(), { limits });
217
- const payload = options.changesOnly ? { ...report, assessments: report.changes } : report;
218
- emit(payload, options.json, () => {
219
- const rows = (options.changesOnly ? report.changes : report.assessments);
220
- if (rows.length === 0) {
221
- return options.changesOnly
222
- ? 'No standing changes. Every measured entry is already where the record says it belongs.'
223
- : 'No entry has a usage record yet, so there is nothing to assess.';
224
- }
225
- const lines = [];
226
- if (report.changes.length > 0) {
227
- lines.push(`${report.changes.length} entr${report.changes.length === 1 ? 'y' : 'ies'} should change standing.`, '');
228
- }
229
- for (const a of rows) {
230
- lines.push(`- ${a.title}`);
231
- lines.push(` ${a.standing}${a.recommendation ? ` (recommend: ${a.recommendation})` : ''}. ${a.reason}`);
232
- }
233
- lines.push('', 'Nothing is applied here. Run sleep-on-learnings to decide.');
234
- return lines.join('\n');
235
- });
236
- });
237
- // ── report ───────────────────────────────────────────────────────────────────
238
- const reportCommand = addCommonOptions(new commander_1.Command('report'))
239
- .description('Answer which learnings are still earning their place, from the record rather than from memory')
240
- .option('--window <days>', 'Reporting window', '90')
241
- .action((options) => {
242
- const workspaceRoot = resolveWorkspaceRoot(options);
243
- const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
244
- const report = (0, learning_usage_analysis_1.buildUsageReport)((0, learning_usage_store_1.readUsageStore)(), {
245
- workspaceRoot,
246
- limits,
247
- windowDays: Number.parseInt(options.window, 10) || 90,
248
- });
249
- emit(report, options.json, () => {
250
- const lines = [
251
- `${report.totals.entriesOffered} entries were offered. ${report.totals.entriesWithFirings} fired. ${report.totals.entriesNeverFired} have never fired.`,
252
- ];
253
- if (report.workingHardest.length) {
254
- lines.push('', 'Working hardest');
255
- report.workingHardest.forEach((e, i) => lines.push(`${i + 1}. ${e.title}. Offered ${e.offered} times, fired ${e.fired}. Last fired ${e.lastFired ?? 'never'}.`));
256
- }
257
- if (report.neverFired.length) {
258
- lines.push('', 'Never fired');
259
- report.neverFired.forEach((e, i) => lines.push(`${i + 1}. ${e.title}. Offered ${e.offered} times, never fired.`));
260
- }
261
- if (report.ignoredWhileInContext.length) {
262
- lines.push('', 'Ignored while in context');
263
- report.ignoredWhileInContext.forEach((e, i) => lines.push(`${i + 1}. ${e.title}. In context and the work went against it, so the entry needs work rather than another recurrence.`));
264
- }
265
- lines.push('', 'Nothing is retired from this view. Run sleep-on-learnings to decide.');
266
- return lines.join('\n');
267
- });
268
- });
269
- // ── backfill ─────────────────────────────────────────────────────────────────
270
- const backfillCommand = addCommonOptions(new commander_1.Command('backfill'))
271
- .description('Read the firings already attested in existing retrospectives, matching only on an id or an exact title, and report what could not be matched')
272
- .option('--agent <name>', 'Agent to attribute the backfilled records to', 'backfill')
273
- .option('--model <model>', 'Model to attribute the backfilled records to')
274
- .action((options) => {
275
- const workspaceRoot = resolveWorkspaceRoot(options);
276
- const user = resolveUser(options);
277
- const report = (0, learning_usage_attestation_1.runBackfill)(workspaceRoot, user, {
278
- agent: options.agent ?? 'backfill',
279
- model: options.model ?? null,
280
- });
281
- emit(report, options.json, () => [
282
- `Files scanned: ${report.filesScanned} (${report.filesWithSection} carry the section, ${report.synthesizedFilesRead} already synthesized)`,
283
- `Items read: ${report.itemsRead}`,
284
- `Applied: ${report.applied}`,
285
- `Already recorded: ${report.alreadyRecorded}`,
286
- `Unmatched: ${report.unmatched.length}`,
287
- `Rejected: ${report.rejected.length}`,
288
- '',
289
- 'Only an id or an exact title resolves. A low match rate is expected on retrospectives written before entries carried ids, and is reported rather than resolved by similarity matching.',
290
- ].join('\n'));
291
- });
292
- /**
293
- * Add the `**Id**` line to entries that do not have one.
294
- *
295
- * This is a format migration, not a change to any lesson: it inserts one
296
- * identifier line per entry and touches nothing else. R19 forbids a new write path
297
- * into the corpus for usage data, and this is not one — it writes no usage data,
298
- * and it is run explicitly by the manager rather than by any automatic path.
299
- */
300
- function stampFile(filePath, fileType, apply) {
301
- const content = node_fs_1.default.readFileSync(filePath, 'utf8');
302
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
303
- const lines = content.split(/\r?\n/);
304
- const headingRe = (0, learning_context_builder_1.learningEntryHeadingRegex)();
305
- const idRe = (0, learning_context_builder_1.learningEntryIdLineRegex)();
306
- const out = [];
307
- let stamped = 0;
308
- let alreadyStamped = 0;
309
- for (let i = 0; i < lines.length; i++) {
310
- const line = lines[i];
311
- out.push(line);
312
- const header = line.match(headingRe);
313
- if (!header)
314
- continue;
315
- // Look ahead to the next entry heading for an existing id line.
316
- let hasId = false;
317
- for (let j = i + 1; j < lines.length; j++) {
318
- if (headingRe.test(lines[j]))
319
- break;
320
- if (idRe.test(lines[j].trim())) {
321
- hasId = true;
322
- break;
323
- }
324
- }
325
- if (hasId) {
326
- alreadyStamped++;
327
- continue;
328
- }
329
- const title = header[2].trim();
330
- if (!title)
331
- continue;
332
- // Insert immediately after the heading, keeping the blank line that usually
333
- // follows it so the file's shape is unchanged.
334
- if (lines[i + 1] !== undefined && lines[i + 1].trim() === '') {
335
- out.push('');
336
- out.push(`**Id**: ${(0, learning_context_builder_1.generateLearningEntryId)(fileType, title)}`);
337
- i++;
338
- }
339
- else {
340
- out.push(`**Id**: ${(0, learning_context_builder_1.generateLearningEntryId)(fileType, title)}`);
341
- }
342
- stamped++;
343
- }
344
- if (apply && stamped > 0) {
345
- node_fs_1.default.writeFileSync(filePath, out.join(eol), 'utf8');
346
- }
347
- return { file: filePath, entriesStamped: stamped, entriesAlreadyStamped: alreadyStamped };
348
- }
349
- const FILE_TYPES = ['mistake-patterns', 'preferences', 'validated-patterns', 'manager-coaching'];
350
- function fileTypeFromName(fileName) {
351
- for (const type of FILE_TYPES) {
352
- if (fileName.includes(type))
353
- return type;
354
- }
355
- return null;
356
- }
357
- const stampIdsCommand = addCommonOptions(new commander_1.Command('stamp-ids'))
358
- .description('Add the stable Id line to learning entries that do not have one. A format migration: it inserts one identifier line per entry and changes no lesson text')
359
- .option('--dir <path>', 'Learning directory to stamp (repeatable)', (value, previous) => [...previous, value], [])
360
- .option('--apply', 'Write the changes. Without this flag the command reports what it would do')
361
- .action((options) => {
362
- const workspaceRoot = resolveWorkspaceRoot(options);
363
- const dirs = options.dir.length
364
- ? options.dir.map((d) => node_path_1.default.resolve(d))
365
- : [node_path_1.default.join(workspaceRoot, 'fraim', 'personalized-employee', 'learnings')];
366
- const results = [];
367
- for (const dir of dirs) {
368
- if (!node_fs_1.default.existsSync(dir))
369
- continue;
370
- for (const fileName of node_fs_1.default.readdirSync(dir)) {
371
- if (!fileName.endsWith('.md'))
372
- continue;
373
- const fileType = fileTypeFromName(fileName);
374
- if (!fileType)
375
- continue;
376
- results.push(stampFile(node_path_1.default.join(dir, fileName), fileType, Boolean(options.apply)));
377
- }
378
- }
379
- const payload = {
380
- apply: Boolean(options.apply),
381
- filesScanned: results.length,
382
- entriesStamped: results.reduce((sum, r) => sum + r.entriesStamped, 0),
383
- entriesAlreadyStamped: results.reduce((sum, r) => sum + r.entriesAlreadyStamped, 0),
384
- files: results,
385
- };
386
- emit(payload, options.json, () => [
387
- `${payload.apply ? 'Stamped' : 'Would stamp'} ${payload.entriesStamped} entries across ${payload.filesScanned} files.`,
388
- `${payload.entriesAlreadyStamped} entries already carry an id.`,
389
- payload.apply ? '' : 'Re-run with --apply to write the changes.',
390
- ].filter(Boolean).join('\n'));
391
- });
392
- // ── prune ────────────────────────────────────────────────────────────────────
393
- const pruneCommand = addCommonOptions(new commander_1.Command('prune'))
394
- .description('Apply the configured retention window and log bounds to the usage record. Aggregate counters are never pruned')
395
- .action((options) => {
396
- const workspaceRoot = resolveWorkspaceRoot(options);
397
- const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
398
- const result = (0, learning_usage_store_1.pruneUsageStore)(limits);
399
- emit({ ...result, storePath: (0, learning_usage_store_1.resolveUsageStorePath)(), limits }, options.json, () => `Pruned ${result.prunedOfferRecords} offer records and ${result.prunedFiringRecords} firing records across ${result.entries} entries. Aggregates unchanged.`);
400
- });
401
- // ── root ─────────────────────────────────────────────────────────────────────
402
- exports.learningUsageCommand = new commander_1.Command('learning-usage')
403
- .description('Read and analyse the learning and rule usage record (issue #1103)')
404
- .addCommand(offersCommand)
405
- .addCommand(recordFiringsCommand)
406
- .addCommand(classifyCommand)
407
- .addCommand(candidatesCommand)
408
- .addCommand(standingCommand)
409
- .addCommand(reportCommand)
410
- .addCommand(backfillCommand)
411
- .addCommand(stampIdsCommand)
412
- .addCommand(pruneCommand);
@@ -1,171 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.testMCPCommand = exports.runTestMCP = void 0;
40
- const commander_1 = require("commander");
41
- const chalk_1 = __importDefault(require("chalk"));
42
- const fs_1 = __importDefault(require("fs"));
43
- const path_1 = __importDefault(require("path"));
44
- const ide_detector_1 = require("../setup/ide-detector");
45
- const script_sync_utils_1 = require("../utils/script-sync-utils");
46
- const testIDEConfig = async (ide) => {
47
- const result = {
48
- ide: ide.name,
49
- configExists: false,
50
- configValid: false,
51
- mcpServers: [],
52
- errors: []
53
- };
54
- const configPath = (0, ide_detector_1.expandPath)(ide.configPath);
55
- if (!fs_1.default.existsSync(configPath)) {
56
- result.errors.push('Config file does not exist');
57
- return result;
58
- }
59
- result.configExists = true;
60
- try {
61
- if (ide.configFormat === 'json') {
62
- const configContent = fs_1.default.readFileSync(configPath, 'utf8');
63
- const config = JSON.parse(configContent);
64
- const servers = ide.configType === 'vscode' ? config.servers : config.mcpServers;
65
- if (servers) {
66
- result.configValid = true;
67
- result.mcpServers = Object.keys(servers);
68
- }
69
- else {
70
- const expectedKey = ide.configType === 'vscode' ? 'servers' : 'mcpServers';
71
- result.errors.push(`No ${expectedKey} section found`);
72
- }
73
- }
74
- else if (ide.configFormat === 'toml') {
75
- const configContent = fs_1.default.readFileSync(configPath, 'utf8');
76
- // Simple TOML parsing for MCP servers
77
- const serverMatches = configContent.match(/\[mcp_servers\.(\w+)\]/g);
78
- if (serverMatches) {
79
- result.configValid = true;
80
- result.mcpServers = serverMatches.map(match => match.replace(/\[mcp_servers\.(\w+)\]/, '$1'));
81
- }
82
- else {
83
- result.errors.push('No mcp_servers sections found');
84
- }
85
- }
86
- }
87
- catch (error) {
88
- result.errors.push(`Failed to parse config: ${error instanceof Error ? error.message : 'Unknown error'}`);
89
- }
90
- return result;
91
- };
92
- const checkGlobalSetup = () => {
93
- const globalConfigPath = path_1.default.join((0, script_sync_utils_1.getUserFraimDir)(), 'config.json');
94
- return fs_1.default.existsSync(globalConfigPath);
95
- };
96
- const runTestMCP = async () => {
97
- console.log(chalk_1.default.blue('🔍 Testing MCP configuration...\n'));
98
- // Check global setup
99
- if (!checkGlobalSetup()) {
100
- console.log(chalk_1.default.red('❌ Global FRAIM setup not found.'));
101
- console.log(chalk_1.default.yellow('Please run: fraim setup --key=<your-fraim-key>'));
102
- return;
103
- }
104
- console.log(chalk_1.default.green('✅ Global FRAIM setup found'));
105
- // Detect IDEs
106
- const detectedIDEs = (0, ide_detector_1.detectInstalledIDEs)();
107
- if (detectedIDEs.length === 0) {
108
- console.log(chalk_1.default.yellow('⚠️ No supported IDEs detected.'));
109
- return;
110
- }
111
- console.log(chalk_1.default.blue(`\n🔍 Testing ${detectedIDEs.length} detected IDEs...\n`));
112
- const results = await Promise.all(detectedIDEs.map(ide => testIDEConfig(ide)));
113
- let totalConfigured = 0;
114
- let totalWithFRAIM = 0;
115
- for (const result of results) {
116
- console.log(chalk_1.default.white(`📱 ${result.ide}`));
117
- if (!result.configExists) {
118
- console.log(chalk_1.default.red(' ❌ No MCP config found'));
119
- console.log(chalk_1.default.gray(` 💡 Run: fraim setup --ide=${result.ide.toLowerCase()}`));
120
- }
121
- else if (!result.configValid) {
122
- console.log(chalk_1.default.yellow(' ⚠️ Config exists but invalid'));
123
- result.errors.forEach(error => {
124
- console.log(chalk_1.default.red(` ❌ ${error}`));
125
- });
126
- }
127
- else {
128
- totalConfigured++;
129
- console.log(chalk_1.default.green(` ✅ MCP config valid (${result.mcpServers.length} servers)`));
130
- // Check for essential servers
131
- const { BASE_MCP_SERVERS } = await Promise.resolve().then(() => __importStar(require('../mcp/mcp-server-registry')));
132
- const essentialServers = BASE_MCP_SERVERS.map(s => s.id); // fraim, git, playwright
133
- const hasEssential = essentialServers.filter(server => result.mcpServers.includes(server));
134
- if (hasEssential.includes('fraim')) {
135
- totalWithFRAIM++;
136
- console.log(chalk_1.default.green(' ✅ FRAIM server configured'));
137
- }
138
- else {
139
- console.log(chalk_1.default.yellow(' ⚠️ FRAIM server missing'));
140
- }
141
- if (hasEssential.length > 1) {
142
- console.log(chalk_1.default.green(` ✅ ${hasEssential.length - 1} additional servers: ${hasEssential.filter(s => s !== 'fraim').join(', ')}`));
143
- }
144
- const missingEssential = essentialServers.filter(server => !result.mcpServers.includes(server));
145
- if (missingEssential.length > 0) {
146
- console.log(chalk_1.default.yellow(` ⚠️ Missing servers: ${missingEssential.join(', ')}`));
147
- }
148
- }
149
- console.log(); // Empty line
150
- }
151
- // Summary
152
- console.log(chalk_1.default.blue('📊 Summary:'));
153
- console.log(chalk_1.default.green(` ✅ ${totalConfigured}/${detectedIDEs.length} IDEs have valid MCP configs`));
154
- console.log(chalk_1.default.green(` ✅ ${totalWithFRAIM}/${detectedIDEs.length} IDEs have FRAIM configured`));
155
- if (totalWithFRAIM === 0) {
156
- console.log(chalk_1.default.red('\n❌ No IDEs have FRAIM configured!'));
157
- console.log(chalk_1.default.yellow('💡 Run: fraim setup --key=<your-fraim-key>'));
158
- }
159
- else if (totalWithFRAIM < detectedIDEs.length) {
160
- console.log(chalk_1.default.yellow(`\n⚠️ ${detectedIDEs.length - totalWithFRAIM} IDEs missing FRAIM configuration`));
161
- console.log(chalk_1.default.yellow('💡 Run: fraim setup to configure remaining IDEs'));
162
- }
163
- else {
164
- console.log(chalk_1.default.green('\n🎉 All detected IDEs have FRAIM configured!'));
165
- console.log(chalk_1.default.blue('💡 Try running: fraim init-project in any project'));
166
- }
167
- };
168
- exports.runTestMCP = runTestMCP;
169
- exports.testMCPCommand = new commander_1.Command('test-mcp')
170
- .description('Test MCP server configurations for all detected IDEs')
171
- .action(exports.runTestMCP);