fraim 2.0.271 → 2.0.272

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.
@@ -12,6 +12,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.SYNCED_CONTENT_BANNER_MARKER = void 0;
15
+ exports.fetchRegistryFiles = fetchRegistryFiles;
16
+ exports.syncScriptsToUserDir = syncScriptsToUserDir;
15
17
  exports.syncFromRemote = syncFromRemote;
16
18
  const axios_1 = __importDefault(require("axios"));
17
19
  const fs_1 = require("fs");
@@ -177,6 +179,42 @@ function applySyncedContentBanner(file) {
177
179
  const banner = buildSyncedContentBanner(typeLabel);
178
180
  return insertAfterFrontmatter(file.content, banner);
179
181
  }
182
+ /**
183
+ * Fetch all registry files from the remote FRAIM server.
184
+ * Extracted so callers can partition the result (scripts vs project stubs).
185
+ */
186
+ async function fetchRegistryFiles(remoteUrl, apiKey) {
187
+ const response = await fetchRegistrySync(remoteUrl, apiKey);
188
+ return response.data.files || [];
189
+ }
190
+ /**
191
+ * Sync script files to the user-level ~/.fraim/scripts/ directory.
192
+ * Extracted from syncFromRemote so it can run without a project root.
193
+ */
194
+ async function syncScriptsToUserDir(files) {
195
+ const scriptFiles = files.filter(f => f.type === 'script');
196
+ if (scriptFiles.length === 0)
197
+ return 0;
198
+ const userDir = (0, script_sync_utils_1.getUserFraimDir)();
199
+ const scriptsDir = (0, path_1.join)(userDir, 'scripts');
200
+ if (!(0, fs_1.existsSync)(scriptsDir)) {
201
+ (0, fs_1.mkdirSync)(scriptsDir, { recursive: true });
202
+ }
203
+ cleanDirectory(scriptsDir, (candidatePath) => {
204
+ if ((0, path_1.resolve)(candidatePath) !== (0, path_1.resolve)(scriptsDir)) {
205
+ assertPathInsideDirectory(scriptsDir, candidatePath, 'script directory');
206
+ }
207
+ });
208
+ for (const file of scriptFiles) {
209
+ const { filePath } = resolveUserRegistryFile(scriptsDir, file.path, 'script file');
210
+ const fileDir = (0, path_1.dirname)(filePath);
211
+ if (!(0, fs_1.existsSync)(fileDir)) {
212
+ (0, fs_1.mkdirSync)(fileDir, { recursive: true });
213
+ }
214
+ (0, fs_1.writeFileSync)(filePath, file.content, 'utf8');
215
+ }
216
+ return scriptFiles.length;
217
+ }
180
218
  /**
181
219
  * Sync jobs and scripts from remote FRAIM server
182
220
  */
@@ -200,9 +238,7 @@ async function syncFromRemote(options) {
200
238
  const assertWorkspacePath = (0, project_fraim_paths_1.createWorkspaceFraimPathAsserter)(options.projectRoot);
201
239
  console.log(chalk_1.default.blue('🔄 Syncing from remote FRAIM server...'));
202
240
  console.log(chalk_1.default.gray(` Remote: ${remoteUrl}`));
203
- // Fetch registry files from remote server
204
- const response = await fetchRegistrySync(remoteUrl, apiKey);
205
- const files = response.data.files || [];
241
+ const files = options.registryFiles || await fetchRegistryFiles(remoteUrl, apiKey);
206
242
  if (!files || files.length === 0) {
207
243
  console.log(chalk_1.default.yellow('⚠️ No files received from remote server'));
208
244
  return {
@@ -297,29 +333,9 @@ async function syncFromRemote(options) {
297
333
  (0, fs_1.writeFileSync)(filePath, applySyncedContentBanner(file), 'utf8');
298
334
  console.log(chalk_1.default.gray(` + ${(0, project_fraim_paths_1.getWorkspaceFraimDisplayPath)(`ai-employee/rules/${relativePath}`)} (stub)`));
299
335
  }
300
- // Sync scripts to user directory
336
+ // Scripts are synced by machine-level layer (syncScriptsToUserDir).
337
+ // Only count them for the result.
301
338
  const scriptFiles = files.filter(f => f.type === 'script');
302
- const userDir = (0, script_sync_utils_1.getUserFraimDir)();
303
- const scriptsDir = (0, path_1.join)(userDir, 'scripts');
304
- if (!(0, fs_1.existsSync)(scriptsDir)) {
305
- (0, fs_1.mkdirSync)(scriptsDir, { recursive: true });
306
- }
307
- // Clean existing scripts
308
- cleanDirectory(scriptsDir, (candidatePath) => {
309
- if ((0, path_1.resolve)(candidatePath) !== (0, path_1.resolve)(scriptsDir)) {
310
- assertPathInsideDirectory(scriptsDir, candidatePath, 'script directory');
311
- }
312
- });
313
- // Write script files
314
- for (const file of scriptFiles) {
315
- const { filePath, relativePath } = resolveUserRegistryFile(scriptsDir, file.path, 'script file');
316
- const fileDir = (0, path_1.dirname)(filePath);
317
- if (!(0, fs_1.existsSync)(fileDir)) {
318
- (0, fs_1.mkdirSync)(fileDir, { recursive: true });
319
- }
320
- (0, fs_1.writeFileSync)(filePath, file.content, 'utf8');
321
- console.log(chalk_1.default.gray(` + ${relativePath}`));
322
- }
323
339
  // Sync docs to fraim/docs/
324
340
  const docsFiles = files.filter(f => f.type === 'docs');
325
341
  const docsDir = (0, project_fraim_paths_1.getWorkspaceFraimPath)(options.projectRoot, 'docs');
@@ -64,8 +64,8 @@ exports.FIRST_RUN_AGENT_OPTIONS = [
64
64
  detectAliases: ['agy', 'antigravity', 'antigravity-cli'],
65
65
  loginCommand: 'agy auth login',
66
66
  launchCommand: 'agy',
67
- // agy has no npm package — install via https://antigravity.google/cli/
68
67
  installPackage: '',
68
+ installUrl: 'https://antigravity.google/cli/',
69
69
  },
70
70
  ];
71
71
  /**
@@ -0,0 +1,408 @@
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 - command surface used by the learning-usage script.
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
+ const commander_1 = require("commander");
15
+ const node_fs_1 = __importDefault(require("node:fs"));
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const learning_context_builder_1 = require("./learning-context-builder");
18
+ const learning_usage_analysis_1 = require("./learning-usage-analysis");
19
+ const learning_usage_store_1 = require("./learning-usage-store");
20
+ const learning_usage_attestation_1 = require("./learning-usage-attestation");
21
+ function resolveWorkspaceRoot(options) {
22
+ return node_path_1.default.resolve(options.workspaceRoot || options.root || process.cwd());
23
+ }
24
+ function resolveUser(options) {
25
+ const email = options.user || process.env.FRAIM_ACTIVE_USER_EMAIL || '';
26
+ if (!email.trim()) {
27
+ throw new Error('Missing active user email. Pass --user <email> or set FRAIM_ACTIVE_USER_EMAIL.');
28
+ }
29
+ return email.trim();
30
+ }
31
+ function emit(payload, json, text) {
32
+ process.stdout.write(json ? `${JSON.stringify(payload, null, 2)}\n` : `${text()}\n`);
33
+ }
34
+ function addCommonOptions(command) {
35
+ return command
36
+ .option('--workspace-root <path>', 'Workspace root containing fraim/config.json')
37
+ .option('--root <path>', 'Alias for --workspace-root')
38
+ .option('--user <email>', 'Active user email')
39
+ .option('--json', 'Print JSON');
40
+ }
41
+ // ── offers ───────────────────────────────────────────────────────────────────
42
+ const offersCommand = addCommonOptions(new commander_1.Command('offers'))
43
+ .description('List the learning entries and rule files the runtime delivered, so an attestation is written against the record rather than memory')
44
+ .option('--job <name>', 'The job whose context was loaded', 'unknown')
45
+ .option('--domain <domain>', 'Learning domain the job resolved to')
46
+ .option('--session', 'Use the session frame rather than the job frame')
47
+ .action((options) => {
48
+ const workspaceRoot = resolveWorkspaceRoot(options);
49
+ const user = resolveUser(options);
50
+ const forJob = !options.session;
51
+ // Prefer what the runtime recorded for this job, because that is what was
52
+ // actually delivered. Re-deriving from the files on disk answers a subtly
53
+ // different question — what would be delivered now — and the two diverge if a
54
+ // learning file changed during the job.
55
+ const store = (0, learning_usage_store_1.readUsageStore)();
56
+ const recorded = Object.values(store.entries)
57
+ .filter((entry) => entry.offered.log.some((offer) => offer.job === options.job))
58
+ .map((entry) => {
59
+ const last = [...entry.offered.log].reverse().find((offer) => offer.job === options.job);
60
+ return {
61
+ key: entry.key,
62
+ family: entry.family,
63
+ id: entry.key.startsWith('L-') ? entry.key : null,
64
+ title: entry.titles[entry.titles.length - 1] ?? entry.key,
65
+ fileType: entry.fileType ?? 'unknown',
66
+ level: entry.level ?? 'unknown',
67
+ displayPath: '',
68
+ severity: null,
69
+ aboveThreshold: last.aboveThreshold,
70
+ };
71
+ });
72
+ const source = recorded.length > 0 ? 'offer-record' : 'derived';
73
+ const offered = recorded.length > 0
74
+ ? recorded
75
+ : [
76
+ ...(0, learning_context_builder_1.collectOfferedLearningEntries)(workspaceRoot, user, forJob, options.domain ?? null),
77
+ ...(0, learning_context_builder_1.collectOfferedRuleFiles)(workspaceRoot, forJob),
78
+ ];
79
+ const payload = { job: options.job, forJob, source, offered };
80
+ emit(payload, options.json, () => {
81
+ if (payload.offered.length === 0) {
82
+ return `No offer record and nothing resolves for job ${options.job}. Do not attest any firing for this job.`;
83
+ }
84
+ const rows = payload.offered.map((o) => `| ${o.id ?? '(no id)'} | ${o.title} | ${o.fileType} | ${o.aboveThreshold ? 'yes' : 'no'} |`);
85
+ const header = source === 'offer-record'
86
+ ? `Entries offered for job ${options.job}, from the offer record:`
87
+ : `No offer record exists for job ${options.job} yet, so this is what would be delivered now. Say so when you attest against it.`;
88
+ return [
89
+ header,
90
+ '',
91
+ '| Id | Title | Family | Above threshold |',
92
+ '|---|---|---|---|',
93
+ ...rows,
94
+ ].join('\n');
95
+ });
96
+ });
97
+ // ── record-firings ───────────────────────────────────────────────────────────
98
+ const recordFiringsCommand = addCommonOptions(new commander_1.Command('record-firings'))
99
+ .description('Read the firing section of a retrospective and write the attested firings into the usage record')
100
+ .requiredOption('--retrospective <path>', 'Retrospective file to read')
101
+ .option('--job <name>', 'The job that produced the retrospective')
102
+ .option('--agent <name>', 'Agent that attested')
103
+ .option('--model <model>', 'Model that attested')
104
+ .option('--legacy', 'Also accept the pre-#1103 prose form')
105
+ .action((options) => {
106
+ const workspaceRoot = resolveWorkspaceRoot(options);
107
+ const user = resolveUser(options);
108
+ const filePath = node_path_1.default.resolve(options.retrospective);
109
+ if (!node_fs_1.default.existsSync(filePath)) {
110
+ throw new Error(`Retrospective not found: ${filePath}`);
111
+ }
112
+ const content = node_fs_1.default.readFileSync(filePath, 'utf8');
113
+ const source = node_path_1.default.relative(workspaceRoot, filePath).replace(/\\/g, '/');
114
+ const result = (0, learning_usage_attestation_1.recordAttestationsFromRetrospective)(workspaceRoot, user, {
115
+ content,
116
+ source,
117
+ job: options.job ?? 'unknown',
118
+ agent: options.agent ?? null,
119
+ model: options.model ?? null,
120
+ legacy: Boolean(options.legacy),
121
+ });
122
+ emit(result, options.json, () => {
123
+ const lines = [
124
+ `Section state: ${result.sectionState}`,
125
+ `Items read: ${result.itemsRead}`,
126
+ `Recorded: ${result.applied}`,
127
+ `Already recorded: ${result.alreadyRecorded}`,
128
+ `Unmatched: ${result.unmatched.length}`,
129
+ `Rejected: ${result.rejected.length}`,
130
+ ];
131
+ for (const item of result.unmatched)
132
+ lines.push(` unmatched: ${item.title} — ${item.reason}`);
133
+ for (const item of result.rejected)
134
+ lines.push(` rejected: ${item.reason}`);
135
+ return lines.join('\n');
136
+ });
137
+ });
138
+ // ── classify ─────────────────────────────────────────────────────────────────
139
+ const classifyCommand = addCommonOptions(new commander_1.Command('classify'))
140
+ .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')
141
+ .option('--entry <id>', 'The entry id, for an entry that carries one')
142
+ .option('--title <title>', 'The exact entry title, for an entry with no id yet. Use with --family')
143
+ .option('--family <family>', 'The entry family: mistake-patterns, preferences, validated-patterns, or manager-coaching')
144
+ .requiredOption('--job <name>', 'The job the recurrence happened in')
145
+ .requiredOption('--date <YYYY-MM-DD>', 'The date the mistake recurred')
146
+ .option('--window <days>', 'How far back an offer still counts as in-context', '30')
147
+ .action((options) => {
148
+ const workspaceRoot = resolveWorkspaceRoot(options);
149
+ // `--title` plus `--family` exists so a caller never has to build the composite
150
+ // title key by hand. An entry title is corpus content and can contain any
151
+ // character, so an agent assembling `T:<family>:<title>` into a shell command
152
+ // would be interpolating untrusted text into a command line. Passing the title
153
+ // as its own argument keeps it a single argv entry.
154
+ let key;
155
+ if (options.entry) {
156
+ key = String(options.entry);
157
+ }
158
+ else if (options.title && options.family) {
159
+ key = (0, learning_usage_store_1.titleUsageKey)(String(options.family), String(options.title));
160
+ }
161
+ else {
162
+ throw new Error('Pass --entry <id>, or --title <title> together with --family <family>.');
163
+ }
164
+ const store = (0, learning_usage_store_1.readUsageStore)();
165
+ const diagnosis = (0, learning_usage_analysis_1.classifyRecurrence)(store, {
166
+ key,
167
+ job: options.job,
168
+ date: options.date,
169
+ windowDays: Number.parseInt(options.window, 10) || 30,
170
+ });
171
+ void workspaceRoot;
172
+ emit(diagnosis, options.json, () => [
173
+ `Classification: ${diagnosis.classification}`,
174
+ `Diagnosis: ${diagnosis.diagnosis}`,
175
+ `Recommendation: ${diagnosis.recommendation}`,
176
+ `Raise the recurrence count: ${diagnosis.recurrenceBump ? 'yes' : 'no'}`,
177
+ ].join('\n'));
178
+ });
179
+ // ── candidates ───────────────────────────────────────────────────────────────
180
+ const candidatesCommand = addCommonOptions(new commander_1.Command('candidates'))
181
+ .description('List retirement candidates: offered often under the current model with no firing under it, paired with a structural signal')
182
+ .option('--model <model>', 'Override the current model (defaults to the most recently offered-to model)')
183
+ .option('--detector <path>', 'Path to the corpus hygiene detector that provides the structural signal')
184
+ .action((options) => {
185
+ const workspaceRoot = resolveWorkspaceRoot(options);
186
+ const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
187
+ const result = (0, learning_usage_analysis_1.findRetirementCandidates)((0, learning_usage_store_1.readUsageStore)(), {
188
+ workspaceRoot,
189
+ limits,
190
+ currentModel: options.model ?? undefined,
191
+ structuralSignalPath: options.detector,
192
+ });
193
+ emit(result, options.json, () => {
194
+ if (result.candidates.length === 0) {
195
+ return `No retirement candidates. Current model: ${result.currentModel ?? 'unknown'}; threshold ${result.offerThreshold} offers.`;
196
+ }
197
+ const lines = [`Current model: ${result.currentModel ?? 'unknown'}. Threshold: ${result.offerThreshold} offers.`, ''];
198
+ for (const c of result.candidates) {
199
+ const earlier = c.firedUnderEarlierModels.map((m) => `${m.count} under ${m.model}`).join(', ') || 'none under any earlier model';
200
+ 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}`);
201
+ }
202
+ return lines.join('\n');
203
+ });
204
+ });
205
+ // ── standing ─────────────────────────────────────────────────────────────────
206
+ const standingCommand = addCommonOptions(new commander_1.Command('standing'))
207
+ .description('Assess each entry as promoted, standard or demoted from its usage record, and list the ones whose standing should change')
208
+ .option('--changes-only', 'Print only the entries whose standing should change')
209
+ .action((options) => {
210
+ const workspaceRoot = resolveWorkspaceRoot(options);
211
+ const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
212
+ const report = (0, learning_usage_analysis_1.assessStanding)((0, learning_usage_store_1.readUsageStore)(), { limits });
213
+ const payload = options.changesOnly ? { ...report, assessments: report.changes } : report;
214
+ emit(payload, options.json, () => {
215
+ const rows = (options.changesOnly ? report.changes : report.assessments);
216
+ if (rows.length === 0) {
217
+ return options.changesOnly
218
+ ? 'No standing changes. Every measured entry is already where the record says it belongs.'
219
+ : 'No entry has a usage record yet, so there is nothing to assess.';
220
+ }
221
+ const lines = [];
222
+ if (report.changes.length > 0) {
223
+ lines.push(`${report.changes.length} entr${report.changes.length === 1 ? 'y' : 'ies'} should change standing.`, '');
224
+ }
225
+ for (const a of rows) {
226
+ lines.push(`- ${a.title}`);
227
+ lines.push(` ${a.standing}${a.recommendation ? ` (recommend: ${a.recommendation})` : ''}. ${a.reason}`);
228
+ }
229
+ lines.push('', 'Nothing is applied here. Run sleep-on-learnings to decide.');
230
+ return lines.join('\n');
231
+ });
232
+ });
233
+ // ── report ───────────────────────────────────────────────────────────────────
234
+ const reportCommand = addCommonOptions(new commander_1.Command('report'))
235
+ .description('Answer which learnings are still earning their place, from the record rather than from memory')
236
+ .option('--window <days>', 'Reporting window', '90')
237
+ .action((options) => {
238
+ const workspaceRoot = resolveWorkspaceRoot(options);
239
+ const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
240
+ const report = (0, learning_usage_analysis_1.buildUsageReport)((0, learning_usage_store_1.readUsageStore)(), {
241
+ workspaceRoot,
242
+ limits,
243
+ windowDays: Number.parseInt(options.window, 10) || 90,
244
+ });
245
+ emit(report, options.json, () => {
246
+ const lines = [
247
+ `${report.totals.entriesOffered} entries were offered. ${report.totals.entriesWithFirings} fired. ${report.totals.entriesNeverFired} have never fired.`,
248
+ ];
249
+ if (report.workingHardest.length) {
250
+ lines.push('', 'Working hardest');
251
+ report.workingHardest.forEach((e, i) => lines.push(`${i + 1}. ${e.title}. Offered ${e.offered} times, fired ${e.fired}. Last fired ${e.lastFired ?? 'never'}.`));
252
+ }
253
+ if (report.neverFired.length) {
254
+ lines.push('', 'Never fired');
255
+ report.neverFired.forEach((e, i) => lines.push(`${i + 1}. ${e.title}. Offered ${e.offered} times, never fired.`));
256
+ }
257
+ if (report.ignoredWhileInContext.length) {
258
+ lines.push('', 'Ignored while in context');
259
+ 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.`));
260
+ }
261
+ lines.push('', 'Nothing is retired from this view. Run sleep-on-learnings to decide.');
262
+ return lines.join('\n');
263
+ });
264
+ });
265
+ // ── backfill ─────────────────────────────────────────────────────────────────
266
+ const backfillCommand = addCommonOptions(new commander_1.Command('backfill'))
267
+ .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')
268
+ .option('--agent <name>', 'Agent to attribute the backfilled records to', 'backfill')
269
+ .option('--model <model>', 'Model to attribute the backfilled records to')
270
+ .action((options) => {
271
+ const workspaceRoot = resolveWorkspaceRoot(options);
272
+ const user = resolveUser(options);
273
+ const report = (0, learning_usage_attestation_1.runBackfill)(workspaceRoot, user, {
274
+ agent: options.agent ?? 'backfill',
275
+ model: options.model ?? null,
276
+ });
277
+ emit(report, options.json, () => [
278
+ `Files scanned: ${report.filesScanned} (${report.filesWithSection} carry the section, ${report.synthesizedFilesRead} already synthesized)`,
279
+ `Items read: ${report.itemsRead}`,
280
+ `Applied: ${report.applied}`,
281
+ `Already recorded: ${report.alreadyRecorded}`,
282
+ `Unmatched: ${report.unmatched.length}`,
283
+ `Rejected: ${report.rejected.length}`,
284
+ '',
285
+ '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.',
286
+ ].join('\n'));
287
+ });
288
+ /**
289
+ * Add the `**Id**` line to entries that do not have one.
290
+ *
291
+ * This is a format migration, not a change to any lesson: it inserts one
292
+ * identifier line per entry and touches nothing else. R19 forbids a new write path
293
+ * into the corpus for usage data, and this is not one — it writes no usage data,
294
+ * and it is run explicitly by the manager rather than by any automatic path.
295
+ */
296
+ function stampFile(filePath, fileType, apply) {
297
+ const content = node_fs_1.default.readFileSync(filePath, 'utf8');
298
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
299
+ const lines = content.split(/\r?\n/);
300
+ const headingRe = (0, learning_context_builder_1.learningEntryHeadingRegex)();
301
+ const idRe = (0, learning_context_builder_1.learningEntryIdLineRegex)();
302
+ const out = [];
303
+ let stamped = 0;
304
+ let alreadyStamped = 0;
305
+ for (let i = 0; i < lines.length; i++) {
306
+ const line = lines[i];
307
+ out.push(line);
308
+ const header = line.match(headingRe);
309
+ if (!header)
310
+ continue;
311
+ // Look ahead to the next entry heading for an existing id line.
312
+ let hasId = false;
313
+ for (let j = i + 1; j < lines.length; j++) {
314
+ if (headingRe.test(lines[j]))
315
+ break;
316
+ if (idRe.test(lines[j].trim())) {
317
+ hasId = true;
318
+ break;
319
+ }
320
+ }
321
+ if (hasId) {
322
+ alreadyStamped++;
323
+ continue;
324
+ }
325
+ const title = header[2].trim();
326
+ if (!title)
327
+ continue;
328
+ // Insert immediately after the heading, keeping the blank line that usually
329
+ // follows it so the file's shape is unchanged.
330
+ if (lines[i + 1] !== undefined && lines[i + 1].trim() === '') {
331
+ out.push('');
332
+ out.push(`**Id**: ${(0, learning_context_builder_1.generateLearningEntryId)(fileType, title)}`);
333
+ i++;
334
+ }
335
+ else {
336
+ out.push(`**Id**: ${(0, learning_context_builder_1.generateLearningEntryId)(fileType, title)}`);
337
+ }
338
+ stamped++;
339
+ }
340
+ if (apply && stamped > 0) {
341
+ node_fs_1.default.writeFileSync(filePath, out.join(eol), 'utf8');
342
+ }
343
+ return { file: filePath, entriesStamped: stamped, entriesAlreadyStamped: alreadyStamped };
344
+ }
345
+ const FILE_TYPES = ['mistake-patterns', 'preferences', 'validated-patterns', 'manager-coaching'];
346
+ function fileTypeFromName(fileName) {
347
+ for (const type of FILE_TYPES) {
348
+ if (fileName.includes(type))
349
+ return type;
350
+ }
351
+ return null;
352
+ }
353
+ const stampIdsCommand = addCommonOptions(new commander_1.Command('stamp-ids'))
354
+ .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')
355
+ .option('--dir <path>', 'Learning directory to stamp (repeatable)', (value, previous) => [...previous, value], [])
356
+ .option('--apply', 'Write the changes. Without this flag the command reports what it would do')
357
+ .action((options) => {
358
+ const workspaceRoot = resolveWorkspaceRoot(options);
359
+ const dirs = options.dir.length
360
+ ? options.dir.map((d) => node_path_1.default.resolve(d))
361
+ : [node_path_1.default.join(workspaceRoot, 'fraim', 'personalized-employee', 'learnings')];
362
+ const results = [];
363
+ for (const dir of dirs) {
364
+ if (!node_fs_1.default.existsSync(dir))
365
+ continue;
366
+ for (const fileName of node_fs_1.default.readdirSync(dir)) {
367
+ if (!fileName.endsWith('.md'))
368
+ continue;
369
+ const fileType = fileTypeFromName(fileName);
370
+ if (!fileType)
371
+ continue;
372
+ results.push(stampFile(node_path_1.default.join(dir, fileName), fileType, Boolean(options.apply)));
373
+ }
374
+ }
375
+ const payload = {
376
+ apply: Boolean(options.apply),
377
+ filesScanned: results.length,
378
+ entriesStamped: results.reduce((sum, r) => sum + r.entriesStamped, 0),
379
+ entriesAlreadyStamped: results.reduce((sum, r) => sum + r.entriesAlreadyStamped, 0),
380
+ files: results,
381
+ };
382
+ emit(payload, options.json, () => [
383
+ `${payload.apply ? 'Stamped' : 'Would stamp'} ${payload.entriesStamped} entries across ${payload.filesScanned} files.`,
384
+ `${payload.entriesAlreadyStamped} entries already carry an id.`,
385
+ payload.apply ? '' : 'Re-run with --apply to write the changes.',
386
+ ].filter(Boolean).join('\n'));
387
+ });
388
+ // ── prune ────────────────────────────────────────────────────────────────────
389
+ const pruneCommand = addCommonOptions(new commander_1.Command('prune'))
390
+ .description('Apply the configured retention window and log bounds to the usage record. Aggregate counters are never pruned')
391
+ .action((options) => {
392
+ const workspaceRoot = resolveWorkspaceRoot(options);
393
+ const limits = (0, learning_usage_store_1.resolveUsageLimits)(workspaceRoot);
394
+ const result = (0, learning_usage_store_1.pruneUsageStore)(limits);
395
+ 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.`);
396
+ });
397
+ // ── root ─────────────────────────────────────────────────────────────────────
398
+ exports.learningUsageCommand = new commander_1.Command('learning-usage')
399
+ .description('Read and analyse the learning and rule usage record (issue #1103)')
400
+ .addCommand(offersCommand)
401
+ .addCommand(recordFiringsCommand)
402
+ .addCommand(classifyCommand)
403
+ .addCommand(candidatesCommand)
404
+ .addCommand(standingCommand)
405
+ .addCommand(reportCommand)
406
+ .addCommand(backfillCommand)
407
+ .addCommand(stampIdsCommand)
408
+ .addCommand(pruneCommand);
@@ -139,8 +139,8 @@ function emptyStore() {
139
139
  * The shallow `record.offered && record.fired` this replaced was not enough. A
140
140
  * record whose sub-objects exist but are empty passed it and then threw in
141
141
  * `buildUsageReport` (`record.offered.log is not iterable`),
142
- * `findRetirementCandidates` and `deriveStanding`, so `fraim learning-usage
143
- * report` and `candidates` failed outright instead of degrading. That state is
142
+ * `findRetirementCandidates` and `deriveStanding`, so usage reports and
143
+ * candidate analysis failed outright instead of degrading. That state is
144
144
  * reachable: the store is a JSON file inside the manager home, which is commonly
145
145
  * a synced folder, so an interrupted write or a partial sync produces valid JSON
146
146
  * with a hollow record.
@@ -12,7 +12,7 @@ const PROVIDERS = {
12
12
  description: 'GitHub repository and issue management',
13
13
  capabilities: ['code', 'issues', 'integrated'],
14
14
  docsUrl: 'https://github.com/settings/tokens',
15
- setupInstructions: 'Run "fraim add-provider github" your IDE handles OAuth automatically on first use',
15
+ setupInstructions: 'Ask your agent to use the FRAIM connect-mcp skill and follow current GitHub and host guidance',
16
16
  mcpServer: {
17
17
  type: 'http',
18
18
  url: 'https://api.githubcopilot.com/mcp/'
@@ -25,7 +25,7 @@ const PROVIDERS = {
25
25
  description: 'GitLab repository and issue management',
26
26
  capabilities: ['code', 'issues', 'integrated'],
27
27
  docsUrl: 'https://gitlab.com/-/profile/personal_access_tokens',
28
- setupInstructions: 'Create a Personal Access Token at https://gitlab.com/-/profile/personal_access_tokens with api scope',
28
+ setupInstructions: 'Ask your agent to use the FRAIM connect-mcp skill and follow current GitLab and host guidance',
29
29
  mcpServer: {
30
30
  type: 'http',
31
31
  url: 'https://gitlab.com/api/v4/mcp',
@@ -49,7 +49,7 @@ const PROVIDERS = {
49
49
  }
50
50
  ],
51
51
  docsUrl: 'https://dev.azure.com',
52
- setupInstructions: 'Create a Personal Access Token in Azure DevOps with Code (Read & Write) and Work Items (Read & Write) scopes',
52
+ setupInstructions: 'Ask your agent to use the FRAIM connect-mcp skill and follow current Azure DevOps and host guidance',
53
53
  mcpServer: {
54
54
  type: 'stdio',
55
55
  command: 'npx',
@@ -91,7 +91,7 @@ const PROVIDERS = {
91
91
  }
92
92
  ],
93
93
  docsUrl: 'https://id.atlassian.com/manage-profile/security/api-tokens',
94
- setupInstructions: 'Create an API Token at https://id.atlassian.com/manage-profile/security/api-tokens',
94
+ setupInstructions: 'Ask your agent to use the FRAIM connect-mcp skill and follow current Jira and host guidance',
95
95
  mcpServer: {
96
96
  type: 'stdio',
97
97
  command: 'uvx',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fraim",
3
- "version": "2.0.271",
3
+ "version": "2.0.272",
4
4
  "description": "FRAIM core CLI and MCP package.",
5
5
  "main": "index.js",
6
6
  "bin": {