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