@fabersep/memory 0.1.0 → 0.2.1

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.
@@ -0,0 +1,565 @@
1
+ import * as fs from 'node:fs';
2
+ import { analyzeCacheLogs } from './cache-logs.js';
3
+ import { estimateCorpusTokens, estimateTokens, renderGlobalL0 } from './compiler.js';
4
+ import { getCompiledL0Path, getConfigPath, getHomeDir, loadConfig } from './config.js';
5
+ import { MCP_TOOLS } from './mcp.js';
6
+ import { readMetrics, } from './metrics.js';
7
+ import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
8
+ import { c, hr } from './ui.js';
9
+ import { getPackageVersion } from './version.js';
10
+ export { getPackageVersion };
11
+ export const STATS_SCHEMA_VERSION = 1;
12
+ export const MCP_SCHEMA_TOKEN_TARGET = 500;
13
+ export const STALE_VERIFIED_DAYS = 90;
14
+ export const L0_CHURN_WARN_THRESHOLD = 5;
15
+ export function validateDaysArg(raw) {
16
+ if (raw === undefined || raw === false) {
17
+ return { ok: true, days: 30 };
18
+ }
19
+ if (raw === true || typeof raw !== 'string') {
20
+ return { ok: false, error: '--days must be an integer between 1 and 90.' };
21
+ }
22
+ if (!/^\d+$/.test(raw.trim())) {
23
+ return { ok: false, error: `--days must be an integer between 1 and 90 (got "${raw}").` };
24
+ }
25
+ const parsed = Number.parseInt(raw.trim(), 10);
26
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 90) {
27
+ return { ok: false, error: `--days must be an integer between 1 and 90 (got ${parsed}).` };
28
+ }
29
+ return { ok: true, days: parsed };
30
+ }
31
+ function round1(n) {
32
+ return Math.round(n * 10) / 10;
33
+ }
34
+ function round2(n) {
35
+ return Math.round(n * 100) / 100;
36
+ }
37
+ export function computeStats(options = {}) {
38
+ const homeDir = options.homeDir || getHomeDir();
39
+ const cwd = options.cwd || process.cwd();
40
+ const days = options.days ?? 30;
41
+ const nowMs = options.nowMs ?? Date.now();
42
+ const packageVersion = getPackageVersion();
43
+ const mcpSchemaTokens = estimateTokens(JSON.stringify(MCP_TOOLS));
44
+ const emptySource = () => ({
45
+ staged: 0,
46
+ duplicateBlocked: 0,
47
+ hygieneBlockedSecret: 0,
48
+ hygieneBlockedMachinePath: 0,
49
+ validationError: 0,
50
+ });
51
+ if (!fs.existsSync(getConfigPath(homeDir))) {
52
+ return {
53
+ schemaVersion: STATS_SCHEMA_VERSION,
54
+ packageVersion,
55
+ configured: false,
56
+ windowDays: days,
57
+ ledger: { exists: false, coverageDays: 0, totalEvents: 0, windowEvents: 0, skippedLines: 0 },
58
+ corpus: {
59
+ activeEntries: 0,
60
+ l0Entries: 0,
61
+ corpusTokens: 0,
62
+ l0Tokens: 0,
63
+ tokenBudget: 1500,
64
+ reductionPct: 0,
65
+ budgetUtilizationPct: 0,
66
+ },
67
+ mcpSchema: {
68
+ tokens: mcpSchemaTokens,
69
+ target: MCP_SCHEMA_TOKEN_TARGET,
70
+ toolCount: MCP_TOOLS.length,
71
+ },
72
+ l0Stability: { changesLast7Days: 0, changesInWindow: 0, churnWarning: false },
73
+ retrieval: {
74
+ nonEmptySearches: 0,
75
+ emptySearches: 0,
76
+ getCalls: 0,
77
+ getCallsPerSearch: 0,
78
+ zeroResultCount: 0,
79
+ zeroResultPct: 0,
80
+ medianBm25LatencyMs: null,
81
+ },
82
+ entryTemperature: {
83
+ hotEntries: [],
84
+ coldWithheld: true,
85
+ coldWithheldReason: 'No configuration found.',
86
+ coldL0Entries: [],
87
+ staleL0Entries: [],
88
+ unverifiedL0Entries: [],
89
+ },
90
+ funnel: {
91
+ bySource: { mcp: emptySource(), import: emptySource() },
92
+ reviewOutcomes: {
93
+ approvedCommitted: 0,
94
+ approvedPushed: 0,
95
+ approvedPr: 0,
96
+ pushFailed: 0,
97
+ awaitingCommit: 0,
98
+ rejected: 0,
99
+ },
100
+ },
101
+ };
102
+ }
103
+ const config = loadConfig(homeDir);
104
+ const teamScope = config.roots.team
105
+ ? loadScopeFromHead(config.roots.team.path, 'team')
106
+ : undefined;
107
+ const personalScope = config.roots.personal
108
+ ? loadScopeFromHead(config.roots.personal.path, 'personal')
109
+ : undefined;
110
+ const activeGlobalEntries = [
111
+ ...(teamScope?.entries || []),
112
+ ...(personalScope?.entries || []),
113
+ ].filter((e) => e.status === 'active');
114
+ const activeL0Entries = activeGlobalEntries.filter((e) => e.l0 === 'line' || e.l0 === 'body');
115
+ const corpusTokens = estimateCorpusTokens(activeGlobalEntries);
116
+ const compiledL0Path = getCompiledL0Path(homeDir);
117
+ const l0Text = fs.existsSync(compiledL0Path)
118
+ ? fs.readFileSync(compiledL0Path, 'utf8')
119
+ : renderGlobalL0(teamScope?.entries || [], personalScope?.entries || []);
120
+ const l0Tokens = estimateTokens(l0Text);
121
+ const reductionPct = corpusTokens > 0 ? round1((1 - l0Tokens / corpusTokens) * 100) : 0;
122
+ const budgetUtilizationPct = config.tokenBudget > 0 ? round1((l0Tokens / config.tokenBudget) * 100) : 0;
123
+ // Separate informational project scope tokens (excluded from L0 reduction ratio)
124
+ let projectActiveEntries;
125
+ let projectTokens;
126
+ const projRes = resolveProjectRoot(undefined, cwd);
127
+ if (projRes.source !== 'none' && projRes.projectRoot) {
128
+ const projScope = loadScopeFromHead(projRes.projectRoot, 'project', PROJECT_MEMORY_REL_DIR);
129
+ const projActive = projScope.entries.filter((e) => e.status === 'active');
130
+ if (projActive.length > 0) {
131
+ projectActiveEntries = projActive.length;
132
+ projectTokens = estimateCorpusTokens(projActive);
133
+ }
134
+ }
135
+ // Read metrics ledger
136
+ const metrics = readMetrics(homeDir);
137
+ const windowCutoffMs = nowMs - days * 24 * 60 * 60 * 1000;
138
+ const sevenDayCutoffMs = nowMs - 7 * 24 * 60 * 60 * 1000;
139
+ let oldestTsMs = Infinity;
140
+ for (const ev of metrics.events) {
141
+ const t = Date.parse(ev.ts);
142
+ if (Number.isFinite(t) && t < oldestTsMs)
143
+ oldestTsMs = t;
144
+ }
145
+ const coverageDays = Number.isFinite(oldestTsMs) && nowMs >= oldestTsMs
146
+ ? Math.floor((nowMs - oldestTsMs) / (24 * 60 * 60 * 1000))
147
+ : 0;
148
+ const windowEvents = metrics.events.filter((ev) => Date.parse(ev.ts) >= windowCutoffMs);
149
+ const compileEventsAll = metrics.events.filter((e) => e.type === 'compile');
150
+ const changesLast7Days = compileEventsAll.filter((e) => e.changed && Date.parse(e.ts) >= sevenDayCutoffMs).length;
151
+ const changesInWindow = compileEventsAll.filter((e) => e.changed && Date.parse(e.ts) >= windowCutoffMs).length;
152
+ const churnWarning = changesLast7Days > L0_CHURN_WARN_THRESHOLD;
153
+ // Retrieval quality
154
+ const searchEvents = windowEvents.filter((e) => e.type === 'search');
155
+ const getEvents = windowEvents.filter((e) => e.type === 'get');
156
+ const nonEmptySearches = searchEvents.filter((e) => !e.empty_query);
157
+ const emptySearches = searchEvents.filter((e) => e.empty_query).length;
158
+ const nonEmptySearchCount = nonEmptySearches.length;
159
+ const getCallCount = getEvents.length;
160
+ const getCallsPerSearch = nonEmptySearchCount > 0 ? round2(getCallCount / nonEmptySearchCount) : 0;
161
+ const zeroResultCount = nonEmptySearches.filter((e) => e.zero_result).length;
162
+ const zeroResultPct = nonEmptySearchCount > 0 ? round1((zeroResultCount / nonEmptySearchCount) * 100) : 0;
163
+ let medianBm25LatencyMs = null;
164
+ if (nonEmptySearches.length > 0) {
165
+ const sorted = nonEmptySearches.map((e) => e.latency_ms).sort((a, b) => a - b);
166
+ // Lower-middle element for even counts (FR-03, AC-10)
167
+ medianBm25LatencyMs = sorted[Math.floor((sorted.length - 1) / 2)];
168
+ }
169
+ // Entry temperature
170
+ const hitCounts = new Map();
171
+ for (const ge of getEvents) {
172
+ for (const foundId of ge.found_ids || []) {
173
+ hitCounts.set(foundId, (hitCounts.get(foundId) || 0) + 1);
174
+ }
175
+ }
176
+ const hotEntries = [...hitCounts.entries()]
177
+ .sort((a, b) => (b[1] !== a[1] ? b[1] - a[1] : a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
178
+ .slice(0, 10)
179
+ .map(([id, hits]) => ({ id, hits }));
180
+ const minRequiredCoverage = Math.max(days, 7);
181
+ const coldWithheld = !metrics.exists || metrics.events.length === 0 || coverageDays < minRequiredCoverage;
182
+ const coldWithheldReason = coldWithheld
183
+ ? !metrics.exists || metrics.events.length === 0
184
+ ? 'No runtime metrics recorded yet.'
185
+ : `Ledger covers ${coverageDays}d (< ${minRequiredCoverage}d required for reliable cold-entry detection).`
186
+ : undefined;
187
+ const coldL0Entries = coldWithheld
188
+ ? []
189
+ : activeL0Entries
190
+ .map((e) => `${e.scope}:${e.id}`)
191
+ .filter((key) => !hitCounts.has(key))
192
+ .sort();
193
+ const staleL0Entries = [];
194
+ const unverifiedL0Entries = [];
195
+ for (const e of activeL0Entries) {
196
+ const key = `${e.scope}:${e.id}`;
197
+ if (!e.last_verified) {
198
+ unverifiedL0Entries.push(key);
199
+ continue;
200
+ }
201
+ const verifiedMs = Date.parse(e.last_verified);
202
+ if (!Number.isFinite(verifiedMs)) {
203
+ unverifiedL0Entries.push(key);
204
+ continue;
205
+ }
206
+ const ageDays = Math.floor((nowMs - verifiedMs) / (24 * 60 * 60 * 1000));
207
+ if (ageDays > STALE_VERIFIED_DAYS) {
208
+ staleL0Entries.push({ id: key, lastVerified: e.last_verified, ageDays });
209
+ }
210
+ }
211
+ staleL0Entries.sort((a, b) => b.ageDays - a.ageDays || (a.id < b.id ? -1 : 1));
212
+ unverifiedL0Entries.sort();
213
+ // Pre-memory funnel
214
+ const funnel = {
215
+ bySource: {
216
+ mcp: emptySource(),
217
+ import: emptySource(),
218
+ },
219
+ reviewOutcomes: {
220
+ approvedCommitted: 0,
221
+ approvedPushed: 0,
222
+ approvedPr: 0,
223
+ pushFailed: 0,
224
+ awaitingCommit: 0,
225
+ rejected: 0,
226
+ },
227
+ };
228
+ for (const ev of windowEvents) {
229
+ if (ev.type === 'propose') {
230
+ const p = ev;
231
+ const bucket = p.source === 'import' ? funnel.bySource.import : funnel.bySource.mcp;
232
+ if (p.outcome === 'staged')
233
+ bucket.staged++;
234
+ else if (p.outcome === 'duplicate_blocked')
235
+ bucket.duplicateBlocked++;
236
+ else if (p.outcome === 'validation_error')
237
+ bucket.validationError++;
238
+ else if (p.outcome === 'hygiene_blocked') {
239
+ if (p.hygiene_category === 'secret')
240
+ bucket.hygieneBlockedSecret++;
241
+ else
242
+ bucket.hygieneBlockedMachinePath++;
243
+ }
244
+ }
245
+ else if (ev.type === 'review_outcome') {
246
+ const r = ev;
247
+ if (r.outcome === 'approved_committed')
248
+ funnel.reviewOutcomes.approvedCommitted++;
249
+ else if (r.outcome === 'approved_pushed')
250
+ funnel.reviewOutcomes.approvedPushed++;
251
+ else if (r.outcome === 'approved_pr')
252
+ funnel.reviewOutcomes.approvedPr++;
253
+ else if (r.outcome === 'push_failed')
254
+ funnel.reviewOutcomes.pushFailed++;
255
+ else if (r.outcome === 'awaiting_commit')
256
+ funnel.reviewOutcomes.awaitingCommit++;
257
+ else if (r.outcome === 'rejected')
258
+ funnel.reviewOutcomes.rejected++;
259
+ }
260
+ }
261
+ let cache;
262
+ if (options.includeCache) {
263
+ const changedCompiles = compileEventsAll.filter((e) => e.changed && Date.parse(e.ts) >= windowCutoffMs);
264
+ cache = analyzeCacheLogs({
265
+ engine: options.engine,
266
+ logDir: options.logDir,
267
+ days,
268
+ nowMs,
269
+ userHome: options.userHome,
270
+ changedCompiles,
271
+ });
272
+ }
273
+ return {
274
+ schemaVersion: STATS_SCHEMA_VERSION,
275
+ packageVersion,
276
+ configured: true,
277
+ windowDays: days,
278
+ ledger: {
279
+ exists: metrics.exists,
280
+ coverageDays,
281
+ totalEvents: metrics.events.length,
282
+ windowEvents: windowEvents.length,
283
+ skippedLines: metrics.skippedLines,
284
+ },
285
+ corpus: {
286
+ activeEntries: activeGlobalEntries.length,
287
+ l0Entries: activeL0Entries.length,
288
+ corpusTokens,
289
+ l0Tokens,
290
+ tokenBudget: config.tokenBudget,
291
+ reductionPct,
292
+ budgetUtilizationPct,
293
+ ...(projectActiveEntries !== undefined ? { projectActiveEntries, projectTokens } : {}),
294
+ },
295
+ mcpSchema: {
296
+ tokens: mcpSchemaTokens,
297
+ target: MCP_SCHEMA_TOKEN_TARGET,
298
+ toolCount: MCP_TOOLS.length,
299
+ },
300
+ l0Stability: {
301
+ changesLast7Days,
302
+ changesInWindow,
303
+ churnWarning,
304
+ },
305
+ retrieval: {
306
+ nonEmptySearches: nonEmptySearchCount,
307
+ emptySearches,
308
+ getCalls: getCallCount,
309
+ getCallsPerSearch,
310
+ zeroResultCount,
311
+ zeroResultPct,
312
+ medianBm25LatencyMs,
313
+ },
314
+ entryTemperature: {
315
+ hotEntries,
316
+ coldWithheld,
317
+ ...(coldWithheldReason ? { coldWithheldReason } : {}),
318
+ coldL0Entries,
319
+ staleL0Entries,
320
+ unverifiedL0Entries,
321
+ },
322
+ funnel,
323
+ ...(cache ? { cache } : {}),
324
+ };
325
+ }
326
+ /**
327
+ * Closed allowlist serializer for `faber-memory stats --share`.
328
+ * Never includes paths, repo names, entry IDs, proposal IDs, model names, or summaries.
329
+ */
330
+ export function buildShareableBenchmark(report) {
331
+ const mcpSrc = report.funnel.bySource.mcp;
332
+ const impSrc = report.funnel.bySource.import;
333
+ const proposedMcp = mcpSrc.staged +
334
+ mcpSrc.duplicateBlocked +
335
+ mcpSrc.hygieneBlockedSecret +
336
+ mcpSrc.hygieneBlockedMachinePath +
337
+ mcpSrc.validationError;
338
+ const proposedImport = impSrc.staged +
339
+ impSrc.duplicateBlocked +
340
+ impSrc.hygieneBlockedSecret +
341
+ impSrc.hygieneBlockedMachinePath +
342
+ impSrc.validationError;
343
+ const out = {
344
+ schemaVersion: report.schemaVersion,
345
+ packageVersion: report.packageVersion,
346
+ windowDays: report.windowDays,
347
+ corpus: {
348
+ activeEntries: report.corpus.activeEntries,
349
+ l0Entries: report.corpus.l0Entries,
350
+ corpusTokens: report.corpus.corpusTokens,
351
+ l0Tokens: report.corpus.l0Tokens,
352
+ tokenBudget: report.corpus.tokenBudget,
353
+ reductionPct: report.corpus.reductionPct,
354
+ budgetUtilizationPct: report.corpus.budgetUtilizationPct,
355
+ },
356
+ mcpSchemaTokens: report.mcpSchema.tokens,
357
+ l0Stability: {
358
+ changesLast7Days: report.l0Stability.changesLast7Days,
359
+ changesInWindow: report.l0Stability.changesInWindow,
360
+ },
361
+ retrieval: {
362
+ nonEmptySearches: report.retrieval.nonEmptySearches,
363
+ getCalls: report.retrieval.getCalls,
364
+ getCallsPerSearch: report.retrieval.getCallsPerSearch,
365
+ zeroResultCount: report.retrieval.zeroResultCount,
366
+ zeroResultPct: report.retrieval.zeroResultPct,
367
+ medianBm25LatencyMs: report.retrieval.medianBm25LatencyMs,
368
+ },
369
+ funnel: {
370
+ proposedMcp,
371
+ proposedImport,
372
+ staged: mcpSrc.staged + impSrc.staged,
373
+ duplicateBlocked: mcpSrc.duplicateBlocked + impSrc.duplicateBlocked,
374
+ hygieneBlockedSecret: mcpSrc.hygieneBlockedSecret + impSrc.hygieneBlockedSecret,
375
+ hygieneBlockedMachinePath: mcpSrc.hygieneBlockedMachinePath + impSrc.hygieneBlockedMachinePath,
376
+ validationError: mcpSrc.validationError + impSrc.validationError,
377
+ approvedCommitted: report.funnel.reviewOutcomes.approvedCommitted,
378
+ approvedPushed: report.funnel.reviewOutcomes.approvedPushed,
379
+ approvedPr: report.funnel.reviewOutcomes.approvedPr,
380
+ pushFailed: report.funnel.reviewOutcomes.pushFailed,
381
+ awaitingCommit: report.funnel.reviewOutcomes.awaitingCommit,
382
+ rejected: report.funnel.reviewOutcomes.rejected,
383
+ },
384
+ };
385
+ if (report.cache && report.cache.engines.length > 0) {
386
+ const cacheObj = {};
387
+ for (const eng of report.cache.engines) {
388
+ if (eng.engine !== 'claude-code' && eng.engine !== 'antigravity')
389
+ continue;
390
+ if (!eng.foundDir || eng.unrecognizedFormat)
391
+ continue;
392
+ const entry = {
393
+ sessions: eng.sessions,
394
+ steps: eng.steps,
395
+ firstStepHitPct: eng.firstStepHitPct,
396
+ warmStepHitPct: eng.warmStepHitPct,
397
+ };
398
+ if (eng.engine === 'claude-code' && eng.correlation?.applicable) {
399
+ entry.eligibleSessions = eng.correlation.eligibleSessions;
400
+ entry.correlatedBreaks = eng.correlation.correlatedBreaks;
401
+ }
402
+ cacheObj[eng.engine] = entry;
403
+ }
404
+ if (Object.keys(cacheObj).length > 0) {
405
+ out.cache = cacheObj;
406
+ }
407
+ }
408
+ return out;
409
+ }
410
+ export function formatShareableMarkdown(card) {
411
+ const lines = [];
412
+ lines.push(`## @fabersep/memory v${card.packageVersion} — Local Benchmark`);
413
+ lines.push('');
414
+ lines.push('| Metric | Value |');
415
+ lines.push('| :--- | :--- |');
416
+ lines.push(`| Active global entries (L0 included) | ${card.corpus.activeEntries} (${card.corpus.l0Entries} in L0) |`);
417
+ lines.push(`| Context efficiency (team + personal) | ${card.corpus.l0Tokens} / ${card.corpus.corpusTokens} tokens (${card.corpus.reductionPct}% reduction) |`);
418
+ lines.push(`| L0 budget utilization | ${card.corpus.l0Tokens} / ${card.corpus.tokenBudget} tokens (${card.corpus.budgetUtilizationPct}%) |`);
419
+ lines.push(`| MCP 3-tool schema footprint | ~${card.mcpSchemaTokens} tokens |`);
420
+ lines.push(`| L0 hash changes (7d / ${card.windowDays}d) | ${card.l0Stability.changesLast7Days} / ${card.l0Stability.changesInWindow} |`);
421
+ lines.push(`| Retrieval (searches / get-per-search / zero-result) | ${card.retrieval.nonEmptySearches} / ${card.retrieval.getCallsPerSearch} / ${card.retrieval.zeroResultPct}% |`);
422
+ lines.push(`| Median BM25 search latency | ${card.retrieval.medianBm25LatencyMs !== null ? `${card.retrieval.medianBm25LatencyMs} ms` : 'n/a'} |`);
423
+ lines.push(`| Pre-memory funnel (staged / dupes / hygiene) | ${card.funnel.staged} / ${card.funnel.duplicateBlocked} / ${card.funnel.hygieneBlockedSecret + card.funnel.hygieneBlockedMachinePath} |`);
424
+ if (card.cache) {
425
+ for (const engineKey of ['claude-code', 'antigravity']) {
426
+ const eng = card.cache[engineKey];
427
+ if (!eng)
428
+ continue;
429
+ const corrSuffix = engineKey === 'claude-code' && eng.eligibleSessions !== undefined
430
+ ? `, ${eng.correlatedBreaks ?? 0}/${eng.eligibleSessions} L0-correlated breaks`
431
+ : '';
432
+ lines.push(`| Prompt cache (${engineKey}) | ${eng.sessions} sessions, ${eng.steps} steps, first-step ${eng.firstStepHitPct}%, warm-step ${eng.warmStepHitPct}%${corrSuffix} |`);
433
+ }
434
+ }
435
+ lines.push('');
436
+ lines.push(`_Window: last ${card.windowDays} days. Generated 100% locally with zero telemetry and zero identifiers or paths._`);
437
+ return lines.join('\n');
438
+ }
439
+ export function formatStatsReport(report) {
440
+ if (!report.configured) {
441
+ return [
442
+ c.bold('FaberSEP Memory Stats'),
443
+ c.yellow('No configuration found yet. Run `faber-memory setup` to initialize your memory root.'),
444
+ ].join('\n');
445
+ }
446
+ const lines = [];
447
+ lines.push(c.bold(`FaberSEP Memory Stats (window: ${report.windowDays}d, coverage: ${report.ledger.coverageDays}d)`));
448
+ lines.push(c.dim(hr('─', 64)));
449
+ // Context & token efficiency
450
+ lines.push(c.bold('Context & Token Efficiency (team + personal):'));
451
+ lines.push(` Active global entries: ${report.corpus.activeEntries} (${report.corpus.l0Entries} in L0)`);
452
+ lines.push(` Full-body corpus tokens: ~${report.corpus.corpusTokens}`);
453
+ lines.push(` Compiled L0 tokens: ~${report.corpus.l0Tokens} (${report.corpus.reductionPct}% reduction)`);
454
+ lines.push(` L0 budget utilization: ${report.corpus.l0Tokens} / ${report.corpus.tokenBudget} (${report.corpus.budgetUtilizationPct}%)`);
455
+ if (report.corpus.projectTokens !== undefined) {
456
+ lines.push(` Active project scope (informational, excluded from L0): ${report.corpus.projectActiveEntries} entries (~${report.corpus.projectTokens} tokens)`);
457
+ }
458
+ lines.push(` MCP 3-tool schema footprint: ~${report.mcpSchema.tokens} tokens (target <= ${report.mcpSchema.target})`);
459
+ // L0 stability
460
+ lines.push('');
461
+ lines.push(c.bold('L0 Stability (non-initial hash changes):'));
462
+ lines.push(` Last 7 days: ${report.l0Stability.changesLast7Days} | Last ${report.windowDays} days: ${report.l0Stability.changesInWindow}`);
463
+ if (report.l0Stability.churnWarning) {
464
+ lines.push(c.yellow(` Warning: High L0 cache churn (${report.l0Stability.changesLast7Days} hash changes in 7d > ${L0_CHURN_WARN_THRESHOLD}). Batch approvals at session end to protect prompt-cache reuse.`));
465
+ }
466
+ // Runtime metrics
467
+ lines.push('');
468
+ lines.push(c.bold('Runtime Retrieval & Governance:'));
469
+ if (!report.ledger.exists || report.ledger.windowEvents === 0) {
470
+ lines.push(c.dim(' No runtime usage metrics recorded yet. Metrics will appear after MCP or CLI usage.'));
471
+ }
472
+ else {
473
+ lines.push(` Non-empty searches: ${report.retrieval.nonEmptySearches} (empty-query listings: ${report.retrieval.emptySearches})`);
474
+ lines.push(` Get calls per search: ${report.retrieval.getCallsPerSearch} (${report.retrieval.getCalls} get calls)`);
475
+ lines.push(` Zero-result searches: ${report.retrieval.zeroResultCount} (${report.retrieval.zeroResultPct}%)`);
476
+ lines.push(` Median BM25 latency: ${report.retrieval.medianBm25LatencyMs !== null ? `${report.retrieval.medianBm25LatencyMs} ms` : 'n/a'}`);
477
+ }
478
+ // Entry temperature
479
+ lines.push('');
480
+ lines.push(c.bold('Entry Temperature:'));
481
+ if (report.entryTemperature.hotEntries.length > 0) {
482
+ lines.push(' Hot entries (top 10 by memory_get hits):');
483
+ for (const h of report.entryTemperature.hotEntries) {
484
+ lines.push(` - ${h.id}: ${h.hits}`);
485
+ }
486
+ }
487
+ else {
488
+ lines.push(' Hot entries: none recorded in window.');
489
+ }
490
+ if (report.entryTemperature.coldWithheld) {
491
+ lines.push(c.dim(` Cold L0 entries: withheld (${report.entryTemperature.coldWithheldReason})`));
492
+ }
493
+ else if (report.entryTemperature.coldL0Entries.length > 0) {
494
+ lines.push(` Cold L0 entries (0 hits in ${report.windowDays}d): ${report.entryTemperature.coldL0Entries.join(', ')}`);
495
+ }
496
+ else {
497
+ lines.push(' Cold L0 entries: none.');
498
+ }
499
+ if (report.entryTemperature.staleL0Entries.length > 0) {
500
+ lines.push(` Stale L0 entries (last_verified > ${STALE_VERIFIED_DAYS}d): ${report.entryTemperature.staleL0Entries
501
+ .map((s) => `${s.id} (${s.ageDays}d)`)
502
+ .join(', ')}`);
503
+ }
504
+ else {
505
+ lines.push(' Stale L0 entries: none.');
506
+ }
507
+ if (report.entryTemperature.unverifiedL0Entries.length > 0) {
508
+ lines.push(` Unverified L0 entries (missing last_verified): ${report.entryTemperature.unverifiedL0Entries.join(', ')}`);
509
+ }
510
+ // Pre-memory governance funnel
511
+ lines.push('');
512
+ lines.push(c.bold('Pre-Memory Funnel:'));
513
+ const m = report.funnel.bySource.mcp;
514
+ const imp = report.funnel.bySource.import;
515
+ lines.push(` MCP proposals: staged=${m.staged}, duplicate_blocked=${m.duplicateBlocked}, hygiene_blocked(secret=${m.hygieneBlockedSecret}, machine-path=${m.hygieneBlockedMachinePath}), validation_error=${m.validationError}`);
516
+ lines.push(` Import proposals: staged=${imp.staged}, duplicate_blocked=${imp.duplicateBlocked}, hygiene_blocked(secret=${imp.hygieneBlockedSecret}, machine-path=${imp.hygieneBlockedMachinePath}), validation_error=${imp.validationError}`);
517
+ const ro = report.funnel.reviewOutcomes;
518
+ lines.push(` Review outcomes: approved_committed=${ro.approvedCommitted}, approved_pushed=${ro.approvedPushed}, approved_pr=${ro.approvedPr}, push_failed=${ro.pushFailed}, awaiting_commit=${ro.awaitingCommit}, rejected=${ro.rejected}`);
519
+ // Cache report
520
+ if (report.cache) {
521
+ lines.push('');
522
+ lines.push(c.bold('Prompt-Cache Hit Rate (read-only local logs):'));
523
+ if (report.cache.unsupportedMessage) {
524
+ lines.push(c.yellow(` ${report.cache.unsupportedMessage}`));
525
+ }
526
+ else {
527
+ for (const eng of report.cache.engines) {
528
+ lines.push(` [${eng.engine}]`);
529
+ if (!eng.foundDir) {
530
+ lines.push(c.dim(' No session logs found (log directory missing).'));
531
+ continue;
532
+ }
533
+ if (eng.unrecognizedFormat) {
534
+ lines.push(c.yellow(' unrecognized log format (no recognized token counter fields).'));
535
+ continue;
536
+ }
537
+ if (eng.sessions === 0) {
538
+ lines.push(c.dim(' No matching sessions found in the selected window.'));
539
+ }
540
+ else {
541
+ lines.push(` Sessions: ${eng.sessions} | Steps: ${eng.steps} (first steps: ${eng.firstSteps}, warm steps <=5m TTL: ${eng.warmSteps}, idle-gap excluded: ${eng.idleGapExcludedSteps})`);
542
+ lines.push(` First-step cache hit: ${eng.firstStepHitPct}% | Warm-step cache hit: ${eng.warmStepHitPct}%`);
543
+ if (eng.byModel.length > 0) {
544
+ lines.push(' By model:');
545
+ for (const bm of eng.byModel) {
546
+ lines.push(` - ${bm.model}: ${bm.sessions} session(s), ${bm.steps} step(s), first-step ${bm.firstStepHitPct}%, warm-step ${bm.warmStepHitPct}%`);
547
+ }
548
+ }
549
+ }
550
+ if (eng.correlation) {
551
+ if (eng.correlation.applicable) {
552
+ lines.push(` L0 cache-break correlation: ${eng.correlation.correlatedBreaks} correlated break(s) out of ${eng.correlation.eligibleSessions} eligible session(s)`);
553
+ }
554
+ else if (eng.correlation.note) {
555
+ lines.push(c.dim(` Note: ${eng.correlation.note}`));
556
+ }
557
+ }
558
+ if (eng.skippedLines > 0) {
559
+ lines.push(c.dim(` Skipped malformed lines: ${eng.skippedLines}`));
560
+ }
561
+ }
562
+ }
563
+ }
564
+ return lines.join('\n');
565
+ }
@@ -1,3 +1,4 @@
1
+ import { CompileTrigger } from './metrics.js';
1
2
  import { UserConfig } from './types.js';
2
3
  export interface SyncResult {
3
4
  ok: boolean;
@@ -10,4 +11,5 @@ export declare function syncAllRoots(config: UserConfig, options?: {
10
11
  homeDir?: string;
11
12
  timeoutMs?: number;
12
13
  recompile?: boolean;
14
+ trigger?: CompileTrigger;
13
15
  }): Promise<SyncResult>;
package/dist/src/sync.js CHANGED
@@ -29,7 +29,7 @@ export async function syncAllRoots(config, options = {}) {
29
29
  }
30
30
  let recompiled = false;
31
31
  if (shouldRecompile && errors.length === 0) {
32
- const comp = compileGlobalL0(config, { homeDir });
32
+ const comp = compileGlobalL0(config, { homeDir, trigger: options.trigger || 'sync' });
33
33
  if (comp.ok) {
34
34
  recompiled = true;
35
35
  }
@@ -6,7 +6,7 @@ export type TeamSubmitMode = 'auto' | 'pr';
6
6
  export type ProposalAction = 'create' | 'update' | 'supersede';
7
7
  export type ProposalStatus = 'pending' | 'awaiting_commit' | 'push_failed';
8
8
  export type ProjectRootSource = 'mcp-roots' | 'cwd' | 'none';
9
- export declare const COMPILER_VERSION = "0.1.0";
9
+ export declare const COMPILER_VERSION: string;
10
10
  export declare const DEFAULT_TOKEN_BUDGET = 1500;
11
11
  export declare const DEFAULT_STALE_DAYS = 14;
12
12
  export declare const DEFAULT_SIMILARITY_THRESHOLD = 0.45;
package/dist/src/types.js CHANGED
@@ -1,4 +1,5 @@
1
- export const COMPILER_VERSION = '0.1.0';
1
+ import { getPackageVersion } from './version.js';
2
+ export const COMPILER_VERSION = getPackageVersion();
2
3
  export const DEFAULT_TOKEN_BUDGET = 1500;
3
4
  export const DEFAULT_STALE_DAYS = 14;
4
5
  export const DEFAULT_SIMILARITY_THRESHOLD = 0.45;
@@ -0,0 +1,19 @@
1
+ export declare const DOCS_TROUBLESHOOTING_URL = "https://github.com/fabersep/memory/blob/main/docs/troubleshooting.md";
2
+ export declare function troubleshootingLink(anchor: string): string;
3
+ export declare function shouldUseColor(stream?: NodeJS.WriteStream): boolean;
4
+ export declare const c: {
5
+ bold: (s: string, on?: boolean) => string;
6
+ dim: (s: string, on?: boolean) => string;
7
+ red: (s: string, on?: boolean) => string;
8
+ green: (s: string, on?: boolean) => string;
9
+ yellow: (s: string, on?: boolean) => string;
10
+ blue: (s: string, on?: boolean) => string;
11
+ magenta: (s: string, on?: boolean) => string;
12
+ cyan: (s: string, on?: boolean) => string;
13
+ };
14
+ export declare function hr(char?: string, width?: number): string;
15
+ export declare function normalizeTeamUrl(input: string): {
16
+ url: string;
17
+ normalized: boolean;
18
+ };
19
+ export declare function inferErrorAnchor(message: string): string | null;