@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,179 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { getHomeDir, getStateDir } from './config.js';
5
+ export const MAX_METRIC_LINE_BYTES = 4096;
6
+ export const MAX_GET_FOUND_IDS = 50;
7
+ export const METRICS_RETENTION_DAYS = 90;
8
+ export const METRICS_MAX_BYTES = 10 * 1024 * 1024; // 10 MB
9
+ export const METRICS_TRIM_TARGET_BYTES = 8 * 1024 * 1024; // 8 MB
10
+ export const METRICS_PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
11
+ export function getMetricsPath(homeDir = getHomeDir()) {
12
+ return path.join(getStateDir(homeDir), 'metrics.jsonl');
13
+ }
14
+ export function getMetricsPrunedPath(homeDir = getHomeDir()) {
15
+ return path.join(getStateDir(homeDir), 'metrics.pruned');
16
+ }
17
+ export function getMetricsLockPath(homeDir = getHomeDir()) {
18
+ return path.join(getStateDir(homeDir), 'metrics.lock');
19
+ }
20
+ function serializeBoundedEvent(event) {
21
+ let line = JSON.stringify(event) + '\n';
22
+ if (Buffer.byteLength(line, 'utf8') <= MAX_METRIC_LINE_BYTES) {
23
+ return line;
24
+ }
25
+ if (event.type === 'get' && event.found_ids.length > 0) {
26
+ const trimmedIds = [...event.found_ids];
27
+ while (trimmedIds.length > 0) {
28
+ trimmedIds.pop();
29
+ const candidate = {
30
+ ...event,
31
+ found_ids: trimmedIds,
32
+ ids_truncated: true,
33
+ };
34
+ line = JSON.stringify(candidate) + '\n';
35
+ if (Buffer.byteLength(line, 'utf8') <= MAX_METRIC_LINE_BYTES) {
36
+ return line;
37
+ }
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ export function appendMetric(event, homeDir = getHomeDir()) {
43
+ try {
44
+ const stateDir = getStateDir(homeDir);
45
+ fs.mkdirSync(stateDir, { recursive: true });
46
+ const line = serializeBoundedEvent(event);
47
+ if (!line)
48
+ return;
49
+ const metricsPath = getMetricsPath(homeDir);
50
+ fs.appendFileSync(metricsPath, line, 'utf8');
51
+ maybePruneMetrics(homeDir);
52
+ }
53
+ catch {
54
+ // Non-blocking fault tolerance: never fail MCP tool calls or CLI commands.
55
+ }
56
+ }
57
+ export function maybePruneMetrics(homeDir = getHomeDir(), options = {}) {
58
+ try {
59
+ const metricsPath = getMetricsPath(homeDir);
60
+ if (!fs.existsSync(metricsPath))
61
+ return false;
62
+ const nowMs = options.nowMs ?? Date.now();
63
+ const maxBytes = options.maxBytes ?? METRICS_MAX_BYTES;
64
+ const trimTargetBytes = options.trimTargetBytes ?? METRICS_TRIM_TARGET_BYTES;
65
+ const retentionDays = options.retentionDays ?? METRICS_RETENTION_DAYS;
66
+ const stat = fs.statSync(metricsPath);
67
+ const oversized = stat.size > maxBytes;
68
+ const prunedMarkerPath = getMetricsPrunedPath(homeDir);
69
+ let pruneIntervalElapsed = true;
70
+ if (fs.existsSync(prunedMarkerPath)) {
71
+ try {
72
+ const markerStat = fs.statSync(prunedMarkerPath);
73
+ pruneIntervalElapsed = nowMs - markerStat.mtimeMs >= METRICS_PRUNE_INTERVAL_MS;
74
+ }
75
+ catch {
76
+ pruneIntervalElapsed = true;
77
+ }
78
+ }
79
+ if (!oversized && !pruneIntervalElapsed) {
80
+ return false;
81
+ }
82
+ const lockDir = getMetricsLockPath(homeDir);
83
+ try {
84
+ // Single non-blocking attempt; if busy, skip pruning for this call.
85
+ fs.mkdirSync(lockDir);
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ try {
91
+ const raw = fs.readFileSync(metricsPath, 'utf8');
92
+ const cutoffMs = nowMs - retentionDays * 24 * 60 * 60 * 1000;
93
+ const lines = raw.split('\n');
94
+ const keptLines = [];
95
+ for (const rawLine of lines) {
96
+ const trimmed = rawLine.trim();
97
+ if (!trimmed)
98
+ continue;
99
+ try {
100
+ const parsed = JSON.parse(trimmed);
101
+ if (typeof parsed.ts !== 'string' || typeof parsed.type !== 'string')
102
+ continue;
103
+ const tsMs = Date.parse(parsed.ts);
104
+ if (!Number.isFinite(tsMs))
105
+ continue;
106
+ if (tsMs < cutoffMs)
107
+ continue;
108
+ keptLines.push(trimmed);
109
+ }
110
+ catch {
111
+ // Drop malformed lines during pruning.
112
+ }
113
+ }
114
+ // If still exceeding maxBytes, trim oldest records down to trimTargetBytes.
115
+ const lineBytes = keptLines.map((l) => Buffer.byteLength(l, 'utf8') + 1);
116
+ let totalBytes = lineBytes.reduce((sum, n) => sum + n, 0);
117
+ let startIdx = 0;
118
+ if (totalBytes > maxBytes) {
119
+ while (startIdx < keptLines.length && totalBytes > trimTargetBytes) {
120
+ totalBytes -= lineBytes[startIdx];
121
+ startIdx++;
122
+ }
123
+ }
124
+ const finalContent = startIdx < keptLines.length ? keptLines.slice(startIdx).join('\n') + '\n' : '';
125
+ const tmpPath = `${metricsPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
126
+ fs.writeFileSync(tmpPath, finalContent, 'utf8');
127
+ fs.renameSync(tmpPath, metricsPath);
128
+ fs.writeFileSync(prunedMarkerPath, new Date(nowMs).toISOString() + '\n', 'utf8');
129
+ return true;
130
+ }
131
+ finally {
132
+ try {
133
+ fs.rmSync(lockDir, { recursive: true, force: true });
134
+ }
135
+ catch {
136
+ // Ignore cleanup errors
137
+ }
138
+ }
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ export function readMetrics(homeDir = getHomeDir()) {
145
+ const metricsPath = getMetricsPath(homeDir);
146
+ if (!fs.existsSync(metricsPath)) {
147
+ return { exists: false, events: [], skippedLines: 0 };
148
+ }
149
+ let raw;
150
+ try {
151
+ raw = fs.readFileSync(metricsPath, 'utf8');
152
+ }
153
+ catch {
154
+ return { exists: true, events: [], skippedLines: 0 };
155
+ }
156
+ const events = [];
157
+ let skippedLines = 0;
158
+ for (const rawLine of raw.split('\n')) {
159
+ const trimmed = rawLine.trim();
160
+ if (!trimmed)
161
+ continue;
162
+ try {
163
+ const parsed = JSON.parse(trimmed);
164
+ if (!parsed ||
165
+ typeof parsed !== 'object' ||
166
+ typeof parsed.type !== 'string' ||
167
+ typeof parsed.ts !== 'string' ||
168
+ !Number.isFinite(Date.parse(parsed.ts))) {
169
+ skippedLines++;
170
+ continue;
171
+ }
172
+ events.push(parsed);
173
+ }
174
+ catch {
175
+ skippedLines++;
176
+ }
177
+ }
178
+ return { exists: true, events, skippedLines };
179
+ }
@@ -5,6 +5,7 @@ import { compileGlobalL0 } from './compiler.js';
5
5
  import { parseMarkdownWithFrontmatter, serializeEntryMarkdown, slugify, } from './frontmatter.js';
6
6
  import { buildCompareUrl, createThrowawayWorktree, getDefaultBranch, getRemoteUrl, gitCommitFiles, gitPullFfOnly, gitSync, isBranchProtectionRejection, readHeadFile, removeThrowawayWorktree, } from './git.js';
7
7
  import { formatHygieneErrors, scanHygiene } from './hygiene.js';
8
+ import { appendMetric } from './metrics.js';
8
9
  import { PROJECT_MEMORY_REL_DIR } from './store.js';
9
10
  export const CACHE_GUIDANCE_NOTE = 'Note: Updated L0 applies to new sessions; batching reviews at session end maximizes prompt-cache reuse.';
10
11
  export function saveProposal(proposal, homeDir = getHomeDir()) {
@@ -115,6 +116,12 @@ export function rejectProposal(id, homeDir = getHomeDir()) {
115
116
  throw new Error(`Proposal "${id}" not found in pre-memory.`);
116
117
  }
117
118
  deleteProposal(proposal, homeDir);
119
+ appendMetric({
120
+ type: 'review_outcome',
121
+ ts: new Date().toISOString(),
122
+ scope: proposal.scope,
123
+ outcome: 'rejected',
124
+ }, homeDir);
118
125
  return proposal;
119
126
  }
120
127
  function applyProposalFilesToDir(repoDir, subDir, proposal) {
@@ -211,8 +218,14 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
211
218
  for (const p of personalProps) {
212
219
  deleteProposal(p, homeDir);
213
220
  approvedIds.push(p.id);
221
+ appendMetric({
222
+ type: 'review_outcome',
223
+ ts: new Date().toISOString(),
224
+ scope: 'personal',
225
+ outcome: 'approved_committed',
226
+ }, homeDir);
214
227
  }
215
- const comp = compileGlobalL0(config, { homeDir });
228
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'approve' });
216
229
  if (!comp.ok) {
217
230
  errors.push(...comp.errors);
218
231
  return { ok: false, approvedIds, messages, errors };
@@ -233,6 +246,12 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
233
246
  p.targetFilePath = touched[0];
234
247
  saveProposal(p, homeDir);
235
248
  approvedIds.push(p.id);
249
+ appendMetric({
250
+ type: 'review_outcome',
251
+ ts: new Date().toISOString(),
252
+ scope: 'project',
253
+ outcome: 'awaiting_commit',
254
+ }, homeDir);
236
255
  messages.push(`Staged project memory file ${touched[0]} (uncommitted). Run: git add ${touched.join(' ')} && git commit -m "memory: ${p.entryId}"`);
237
256
  }
238
257
  if (errors.length > 0) {
@@ -294,12 +313,18 @@ async function approveTeamBatch(config, root, teamProps, homeDir, overrideMode)
294
313
  if (directPush.ok) {
295
314
  for (const p of teamProps) {
296
315
  deleteProposal(p, homeDir);
316
+ appendMetric({
317
+ type: 'review_outcome',
318
+ ts: new Date().toISOString(),
319
+ scope: 'team',
320
+ outcome: 'approved_pushed',
321
+ }, homeDir);
297
322
  }
298
323
  // Sync serving clone & recompile L0
299
324
  const pull = await gitPullFfOnly(root.path, 5000);
300
325
  let recompiledL0 = false;
301
326
  if (pull.ok) {
302
- const comp = compileGlobalL0(config, { homeDir });
327
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'approve' });
303
328
  if (comp.ok)
304
329
  recompiledL0 = true;
305
330
  }
@@ -343,6 +368,12 @@ async function approveTeamBatch(config, root, teamProps, homeDir, overrideMode)
343
368
  const compareUrl = buildCompareUrl(remoteUrl, defaultBranch, branchName);
344
369
  for (const p of teamProps) {
345
370
  deleteProposal(p, homeDir);
371
+ appendMetric({
372
+ type: 'review_outcome',
373
+ ts: new Date().toISOString(),
374
+ scope: 'team',
375
+ outcome: 'approved_pr',
376
+ }, homeDir);
346
377
  }
347
378
  return {
348
379
  ok: true,
@@ -378,6 +409,12 @@ function markPushFailed(proposals, error, homeDir) {
378
409
  p.status = 'push_failed';
379
410
  p.error = error;
380
411
  saveProposal(p, homeDir);
412
+ appendMetric({
413
+ type: 'review_outcome',
414
+ ts: new Date().toISOString(),
415
+ scope: p.scope,
416
+ outcome: 'push_failed',
417
+ }, homeDir);
381
418
  }
382
419
  }, homeDir);
383
420
  }
@@ -0,0 +1,166 @@
1
+ import { CacheAnalysisResult, CacheEngineOption } from './cache-logs.js';
2
+ import { getPackageVersion } from './version.js';
3
+ export { getPackageVersion };
4
+ export declare const STATS_SCHEMA_VERSION = 1;
5
+ export declare const MCP_SCHEMA_TOKEN_TARGET = 500;
6
+ export declare const STALE_VERIFIED_DAYS = 90;
7
+ export declare const L0_CHURN_WARN_THRESHOLD = 5;
8
+ export declare function validateDaysArg(raw: unknown): {
9
+ ok: true;
10
+ days: number;
11
+ } | {
12
+ ok: false;
13
+ error: string;
14
+ };
15
+ export interface StatsReport {
16
+ schemaVersion: number;
17
+ packageVersion: string;
18
+ configured: boolean;
19
+ windowDays: number;
20
+ ledger: {
21
+ exists: boolean;
22
+ coverageDays: number;
23
+ totalEvents: number;
24
+ windowEvents: number;
25
+ skippedLines: number;
26
+ };
27
+ corpus: {
28
+ activeEntries: number;
29
+ l0Entries: number;
30
+ corpusTokens: number;
31
+ l0Tokens: number;
32
+ tokenBudget: number;
33
+ reductionPct: number;
34
+ budgetUtilizationPct: number;
35
+ projectActiveEntries?: number;
36
+ projectTokens?: number;
37
+ };
38
+ mcpSchema: {
39
+ tokens: number;
40
+ target: number;
41
+ toolCount: number;
42
+ };
43
+ l0Stability: {
44
+ changesLast7Days: number;
45
+ changesInWindow: number;
46
+ churnWarning: boolean;
47
+ };
48
+ retrieval: {
49
+ nonEmptySearches: number;
50
+ emptySearches: number;
51
+ getCalls: number;
52
+ getCallsPerSearch: number;
53
+ zeroResultCount: number;
54
+ zeroResultPct: number;
55
+ medianBm25LatencyMs: number | null;
56
+ };
57
+ entryTemperature: {
58
+ hotEntries: {
59
+ id: string;
60
+ hits: number;
61
+ }[];
62
+ coldWithheld: boolean;
63
+ coldWithheldReason?: string;
64
+ coldL0Entries: string[];
65
+ staleL0Entries: {
66
+ id: string;
67
+ lastVerified: string;
68
+ ageDays: number;
69
+ }[];
70
+ unverifiedL0Entries: string[];
71
+ };
72
+ funnel: {
73
+ bySource: {
74
+ mcp: {
75
+ staged: number;
76
+ duplicateBlocked: number;
77
+ hygieneBlockedSecret: number;
78
+ hygieneBlockedMachinePath: number;
79
+ validationError: number;
80
+ };
81
+ import: {
82
+ staged: number;
83
+ duplicateBlocked: number;
84
+ hygieneBlockedSecret: number;
85
+ hygieneBlockedMachinePath: number;
86
+ validationError: number;
87
+ };
88
+ };
89
+ reviewOutcomes: {
90
+ approvedCommitted: number;
91
+ approvedPushed: number;
92
+ approvedPr: number;
93
+ pushFailed: number;
94
+ awaitingCommit: number;
95
+ rejected: number;
96
+ };
97
+ };
98
+ cache?: CacheAnalysisResult;
99
+ }
100
+ export interface ShareableBenchmarkJson {
101
+ schemaVersion: number;
102
+ packageVersion: string;
103
+ windowDays: number;
104
+ corpus: {
105
+ activeEntries: number;
106
+ l0Entries: number;
107
+ corpusTokens: number;
108
+ l0Tokens: number;
109
+ tokenBudget: number;
110
+ reductionPct: number;
111
+ budgetUtilizationPct: number;
112
+ };
113
+ mcpSchemaTokens: number;
114
+ l0Stability: {
115
+ changesLast7Days: number;
116
+ changesInWindow: number;
117
+ };
118
+ retrieval: {
119
+ nonEmptySearches: number;
120
+ getCalls: number;
121
+ getCallsPerSearch: number;
122
+ zeroResultCount: number;
123
+ zeroResultPct: number;
124
+ medianBm25LatencyMs: number | null;
125
+ };
126
+ funnel: {
127
+ proposedMcp: number;
128
+ proposedImport: number;
129
+ staged: number;
130
+ duplicateBlocked: number;
131
+ hygieneBlockedSecret: number;
132
+ hygieneBlockedMachinePath: number;
133
+ validationError: number;
134
+ approvedCommitted: number;
135
+ approvedPushed: number;
136
+ approvedPr: number;
137
+ pushFailed: number;
138
+ awaitingCommit: number;
139
+ rejected: number;
140
+ };
141
+ cache?: Partial<Record<'claude-code' | 'antigravity', {
142
+ sessions: number;
143
+ steps: number;
144
+ firstStepHitPct: number;
145
+ warmStepHitPct: number;
146
+ eligibleSessions?: number;
147
+ correlatedBreaks?: number;
148
+ }>>;
149
+ }
150
+ export declare function computeStats(options?: {
151
+ days?: number;
152
+ includeCache?: boolean;
153
+ engine?: CacheEngineOption;
154
+ logDir?: string;
155
+ homeDir?: string;
156
+ userHome?: string;
157
+ cwd?: string;
158
+ nowMs?: number;
159
+ }): StatsReport;
160
+ /**
161
+ * Closed allowlist serializer for `faber-memory stats --share`.
162
+ * Never includes paths, repo names, entry IDs, proposal IDs, model names, or summaries.
163
+ */
164
+ export declare function buildShareableBenchmark(report: StatsReport): ShareableBenchmarkJson;
165
+ export declare function formatShareableMarkdown(card: ShareableBenchmarkJson): string;
166
+ export declare function formatStatsReport(report: StatsReport): string;