@fabersep/memory 0.0.0-stage → 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.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +399 -2
  3. package/dist/src/bm25.d.ts +26 -0
  4. package/dist/src/bm25.js +183 -0
  5. package/dist/src/cache-logs.d.ts +47 -0
  6. package/dist/src/cache-logs.js +433 -0
  7. package/dist/src/cli.d.ts +2 -0
  8. package/dist/src/cli.js +701 -0
  9. package/dist/src/compiler.d.ts +23 -0
  10. package/dist/src/compiler.js +211 -0
  11. package/dist/src/config.d.ts +20 -0
  12. package/dist/src/config.js +134 -0
  13. package/dist/src/doctor.d.ts +23 -0
  14. package/dist/src/doctor.js +447 -0
  15. package/dist/src/frontmatter.d.ts +22 -0
  16. package/dist/src/frontmatter.js +199 -0
  17. package/dist/src/git.d.ts +33 -0
  18. package/dist/src/git.js +251 -0
  19. package/dist/src/hygiene.d.ts +7 -0
  20. package/dist/src/hygiene.js +89 -0
  21. package/dist/src/importer.d.ts +34 -0
  22. package/dist/src/importer.js +261 -0
  23. package/dist/src/index.d.ts +18 -0
  24. package/dist/src/index.js +18 -0
  25. package/dist/src/init.d.ts +43 -0
  26. package/dist/src/init.js +280 -0
  27. package/dist/src/mcp.d.ts +218 -0
  28. package/dist/src/mcp.js +437 -0
  29. package/dist/src/metrics.d.ts +72 -0
  30. package/dist/src/metrics.js +179 -0
  31. package/dist/src/proposals.d.ts +34 -0
  32. package/dist/src/proposals.js +420 -0
  33. package/dist/src/stats.d.ts +165 -0
  34. package/dist/src/stats.js +579 -0
  35. package/dist/src/store.d.ts +23 -0
  36. package/dist/src/store.js +161 -0
  37. package/dist/src/sync.d.ts +15 -0
  38. package/dist/src/sync.js +47 -0
  39. package/dist/src/types.d.ts +100 -0
  40. package/dist/src/types.js +17 -0
  41. package/dist/src/ui.d.ts +19 -0
  42. package/dist/src/ui.js +74 -0
  43. package/package.json +50 -4
@@ -0,0 +1,437 @@
1
+ import * as fs from 'node:fs';
2
+ import * as readline from 'node:readline';
3
+ import { BM25Index, findNearDuplicates } from './bm25.js';
4
+ import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
5
+ import { compileGlobalL0 } from './compiler.js';
6
+ import { getHeadSha } from './git.js';
7
+ import { formatHygieneErrors, scanHygiene } from './hygiene.js';
8
+ import { appendMetric, MAX_GET_FOUND_IDS } from './metrics.js';
9
+ import { createProposal, reconcileAwaitingCommitProposals } from './proposals.js';
10
+ import { loadAllScopes, resolveProjectRoot } from './store.js';
11
+ import { syncAllRoots } from './sync.js';
12
+ import { VALID_TYPES, } from './types.js';
13
+ export const MCP_TOOLS = [
14
+ {
15
+ name: 'memory_search',
16
+ description: 'Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: {
20
+ query: { type: 'string', description: 'Keyword query; empty lists all.' },
21
+ scope: { type: 'string', enum: ['team', 'personal', 'project'] },
22
+ type: { type: 'string', enum: ['rule', 'decision', 'lesson', 'preference', 'reference'] },
23
+ include_pending: { type: 'boolean', default: false },
24
+ },
25
+ },
26
+ },
27
+ {
28
+ name: 'memory_get',
29
+ description: 'Fetch full L2 Markdown body, frontmatter metadata, and links for one or more IDs.',
30
+ inputSchema: {
31
+ type: 'object',
32
+ properties: {
33
+ ids: { type: 'array', items: { type: 'string' }, minItems: 1 },
34
+ },
35
+ required: ['ids'],
36
+ },
37
+ },
38
+ {
39
+ name: 'memory_propose',
40
+ description: 'Submit a create, update, or supersede proposal to pre-memory for human approval.',
41
+ inputSchema: {
42
+ type: 'object',
43
+ properties: {
44
+ action: { type: 'string', enum: ['create', 'update', 'supersede'] },
45
+ scope: { type: 'string', enum: ['team', 'personal', 'project'] },
46
+ summary: { type: 'string' },
47
+ type: { type: 'string', enum: ['rule', 'decision', 'lesson', 'preference', 'reference'] },
48
+ body: { type: 'string' },
49
+ target_id: { type: 'string' },
50
+ entry_id: { type: 'string' },
51
+ tags: { type: 'array', items: { type: 'string' } },
52
+ l0: { type: 'string', enum: ['none', 'line', 'body'] },
53
+ force_new: { type: 'boolean' },
54
+ reason: { type: 'string' },
55
+ },
56
+ required: ['action', 'scope', 'summary', 'type', 'body'],
57
+ },
58
+ },
59
+ ];
60
+ export class FaberMemoryMcpServer {
61
+ homeDir;
62
+ cwd;
63
+ startupPullTimeoutMs;
64
+ mcpRoots;
65
+ index = new BM25Index();
66
+ lastHeadSignature = '';
67
+ lastLoaded = null;
68
+ startupWarnings = [];
69
+ startupPullPromise = null;
70
+ constructor(options = {}) {
71
+ this.homeDir = options.homeDir || getHomeDir();
72
+ this.cwd = options.cwd || process.cwd();
73
+ this.mcpRoots = options.mcpRoots;
74
+ this.startupPullTimeoutMs = options.startupPullTimeoutMs ?? 5000;
75
+ }
76
+ startNonBlockingSync() {
77
+ const config = loadConfig(this.homeDir);
78
+ // Ensure compiled L0 exists on startup if missing
79
+ if (!fs.existsSync(getCompiledL0Path(this.homeDir))) {
80
+ compileGlobalL0(config, { homeDir: this.homeDir, trigger: 'mcp-startup' });
81
+ }
82
+ this.startupPullPromise = syncAllRoots(config, {
83
+ homeDir: this.homeDir,
84
+ timeoutMs: this.startupPullTimeoutMs,
85
+ recompile: true,
86
+ trigger: 'mcp-startup',
87
+ })
88
+ .then((res) => {
89
+ if (res.warnings.length > 0) {
90
+ this.startupWarnings.push(...res.warnings);
91
+ }
92
+ })
93
+ .catch((err) => {
94
+ this.startupWarnings.push(`Startup sync failed: ${err instanceof Error ? err.message : String(err)}`);
95
+ });
96
+ }
97
+ async waitForStartupSyncForTest() {
98
+ if (this.startupPullPromise) {
99
+ await this.startupPullPromise;
100
+ }
101
+ }
102
+ setMcpRoots(roots) {
103
+ this.mcpRoots = roots;
104
+ this.lastHeadSignature = '';
105
+ }
106
+ refreshIndexIfNeeded() {
107
+ const config = loadConfig(this.homeDir);
108
+ const projectRes = resolveProjectRoot(this.mcpRoots, this.cwd);
109
+ const pending = reconcileAwaitingCommitProposals(this.homeDir);
110
+ const teamSha = config.roots.team ? getHeadSha(config.roots.team.path) : '';
111
+ const personalSha = config.roots.personal ? getHeadSha(config.roots.personal.path) : '';
112
+ const projectSha = projectRes.source !== 'none' && projectRes.projectRoot
113
+ ? getHeadSha(projectRes.projectRoot)
114
+ : '';
115
+ const pendingSig = pending.map((p) => `${p.id}:${p.status}`).join(',');
116
+ const sig = `${teamSha}|${personalSha}|${projectSha}|${projectRes.source}|${pendingSig}`;
117
+ if (sig !== this.lastHeadSignature || !this.lastLoaded) {
118
+ this.lastLoaded = loadAllScopes(config, projectRes);
119
+ this.index.rebuild(this.lastLoaded.activeEntries, pending);
120
+ this.lastHeadSignature = sig;
121
+ }
122
+ return { config, loaded: this.lastLoaded };
123
+ }
124
+ drainWarnings(loaded) {
125
+ const warnings = [...this.startupWarnings, ...loaded.uncommittedWarnings, ...loaded.shadowWarnings];
126
+ this.startupWarnings = [];
127
+ return warnings;
128
+ }
129
+ listTools() {
130
+ return MCP_TOOLS;
131
+ }
132
+ handleToolCall(name, args = {}) {
133
+ if (name === 'memory_search') {
134
+ const { loaded } = this.refreshIndexIfNeeded();
135
+ const query = typeof args.query === 'string' ? args.query : '';
136
+ const scope = typeof args.scope === 'string' ? args.scope : undefined;
137
+ const type = typeof args.type === 'string' ? args.type : undefined;
138
+ const includePending = Boolean(args.include_pending);
139
+ const t0 = performance.now();
140
+ const results = this.index.search(query, { scope, type, includePending });
141
+ const latencyMs = Math.round((performance.now() - t0) * 100) / 100;
142
+ appendMetric({
143
+ type: 'search',
144
+ ts: new Date().toISOString(),
145
+ ...(scope ? { scope } : {}),
146
+ result_count: results.length,
147
+ zero_result: results.length === 0,
148
+ empty_query: query.trim().length === 0,
149
+ latency_ms: latencyMs,
150
+ }, this.homeDir);
151
+ const warnings = this.drainWarnings(loaded);
152
+ const payload = {
153
+ results,
154
+ metadata: {
155
+ project_root_source: loaded.projectResolution.source,
156
+ warnings,
157
+ },
158
+ };
159
+ return {
160
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
161
+ };
162
+ }
163
+ if (name === 'memory_get') {
164
+ const { loaded } = this.refreshIndexIfNeeded();
165
+ const ids = Array.isArray(args.ids) ? args.ids.map(String) : [];
166
+ if (ids.length === 0) {
167
+ return {
168
+ isError: true,
169
+ content: [{ type: 'text', text: JSON.stringify({ error: 'ids array is required' }) }],
170
+ };
171
+ }
172
+ const t0 = performance.now();
173
+ const found = [];
174
+ const notFound = [];
175
+ for (const id of ids) {
176
+ const matches = loaded.allEntries.filter((e) => e.id === id);
177
+ if (matches.length === 0) {
178
+ notFound.push(id);
179
+ }
180
+ else {
181
+ for (const e of matches) {
182
+ found.push({
183
+ id: e.id,
184
+ scope: e.scope,
185
+ type: e.type,
186
+ summary: e.summary,
187
+ tags: e.tags,
188
+ status: e.status,
189
+ superseded_by: e.superseded_by,
190
+ l0: e.l0,
191
+ last_verified: e.last_verified,
192
+ body: e.body,
193
+ links: e.links,
194
+ shadowed: e.shadowed,
195
+ shadow_warning: e.shadowWarning,
196
+ });
197
+ }
198
+ }
199
+ }
200
+ const latencyMs = Math.round((performance.now() - t0) * 100) / 100;
201
+ const allFoundIds = found.map((e) => `${e.scope}:${e.id}`);
202
+ const idsTruncated = allFoundIds.length > MAX_GET_FOUND_IDS;
203
+ appendMetric({
204
+ type: 'get',
205
+ ts: new Date().toISOString(),
206
+ found_ids: idsTruncated ? allFoundIds.slice(0, MAX_GET_FOUND_IDS) : allFoundIds,
207
+ ...(idsTruncated ? { ids_truncated: true } : {}),
208
+ found_count: found.length,
209
+ not_found_count: notFound.length,
210
+ latency_ms: latencyMs,
211
+ }, this.homeDir);
212
+ const warnings = this.drainWarnings(loaded);
213
+ return {
214
+ content: [
215
+ {
216
+ type: 'text',
217
+ text: JSON.stringify({ entries: found, not_found: notFound, warnings }, null, 2),
218
+ },
219
+ ],
220
+ };
221
+ }
222
+ if (name === 'memory_propose') {
223
+ const { config, loaded } = this.refreshIndexIfNeeded();
224
+ const action = String(args.action || '');
225
+ const scope = String(args.scope || '');
226
+ const summary = typeof args.summary === 'string' ? args.summary.trim() : '';
227
+ const type = String(args.type || '');
228
+ const body = typeof args.body === 'string' ? args.body.trim() : '';
229
+ const targetId = typeof args.target_id === 'string' ? args.target_id.trim() : undefined;
230
+ const entryId = typeof args.entry_id === 'string' ? args.entry_id.trim() : undefined;
231
+ const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
232
+ const l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
233
+ const forceNew = Boolean(args.force_new);
234
+ const reason = typeof args.reason === 'string' ? args.reason.trim() : undefined;
235
+ const metricScope = ['team', 'personal', 'project'].includes(scope)
236
+ ? scope
237
+ : 'personal';
238
+ const metricAction = ['create', 'update', 'supersede'].includes(action)
239
+ ? action
240
+ : 'create';
241
+ const recordPropose = (outcome, hygieneCategory) => {
242
+ appendMetric({
243
+ type: 'propose',
244
+ ts: new Date().toISOString(),
245
+ source: 'mcp',
246
+ scope: metricScope,
247
+ action: metricAction,
248
+ outcome,
249
+ ...(hygieneCategory ? { hygiene_category: hygieneCategory } : {}),
250
+ }, this.homeDir);
251
+ };
252
+ if (!['create', 'update', 'supersede'].includes(action)) {
253
+ recordPropose('validation_error');
254
+ return errorResponse('Invalid action; expected create, update, or supersede.');
255
+ }
256
+ if (!['team', 'personal', 'project'].includes(scope)) {
257
+ recordPropose('validation_error');
258
+ return errorResponse('Invalid scope; expected team, personal, or project.');
259
+ }
260
+ if (!summary) {
261
+ recordPropose('validation_error');
262
+ return errorResponse('summary is required.');
263
+ }
264
+ if (!VALID_TYPES.includes(type)) {
265
+ recordPropose('validation_error');
266
+ return errorResponse(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
267
+ }
268
+ if (!body) {
269
+ recordPropose('validation_error');
270
+ return errorResponse('body is required.');
271
+ }
272
+ // Validate target_id for update / supersede (AC-08c1, AC-08c2)
273
+ if (action === 'update' || action === 'supersede') {
274
+ if (!targetId) {
275
+ recordPropose('validation_error');
276
+ return errorResponse(`target_id is required when action is "${action}".`);
277
+ }
278
+ const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
279
+ loaded.activeEntries.some((e) => e.id === targetId);
280
+ if (!exists) {
281
+ recordPropose('validation_error');
282
+ return errorResponse(`Target entry "${targetId}" not found in active memory.`);
283
+ }
284
+ }
285
+ // Hygiene scan (AC-20a)
286
+ const hygieneFindings = scanHygiene(`${summary}\n${body}`);
287
+ if (hygieneFindings.length > 0) {
288
+ const hasSecret = hygieneFindings.some((f) => f.category === 'secret');
289
+ recordPropose('hygiene_blocked', hasSecret ? 'secret' : 'machine-path');
290
+ return errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings });
291
+ }
292
+ // Near-duplicate check on create (AC-10, AC-11)
293
+ if (action === 'create') {
294
+ if (forceNew && !reason) {
295
+ recordPropose('validation_error');
296
+ return errorResponse('A non-empty "reason" is required when force_new is true.');
297
+ }
298
+ if (!forceNew) {
299
+ const pending = reconcileAwaitingCommitProposals(this.homeDir);
300
+ const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
301
+ if (matches.length > 0) {
302
+ recordPropose('duplicate_blocked');
303
+ return errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
304
+ matches: matches.map((m) => ({
305
+ id: m.id,
306
+ scope: m.scope,
307
+ summary: m.summary,
308
+ pending: m.pending,
309
+ similarity: m.similarity,
310
+ })),
311
+ });
312
+ }
313
+ }
314
+ }
315
+ try {
316
+ const proposal = createProposal(config, {
317
+ scope,
318
+ action,
319
+ entryId,
320
+ targetId,
321
+ summary,
322
+ type,
323
+ tags,
324
+ l0,
325
+ body,
326
+ forceNew,
327
+ reason,
328
+ projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
329
+ }, this.homeDir);
330
+ recordPropose('staged');
331
+ this.lastHeadSignature = '';
332
+ const warnings = this.drainWarnings(loaded);
333
+ return {
334
+ content: [
335
+ {
336
+ type: 'text',
337
+ text: JSON.stringify({
338
+ status: 'staged',
339
+ proposal_id: proposal.id,
340
+ entry_id: proposal.entryId,
341
+ scope: proposal.scope,
342
+ warnings,
343
+ }, null, 2),
344
+ },
345
+ ],
346
+ };
347
+ }
348
+ catch (err) {
349
+ recordPropose('validation_error');
350
+ return errorResponse(err instanceof Error ? err.message : String(err));
351
+ }
352
+ }
353
+ return errorResponse(`Unknown tool: ${name}`);
354
+ }
355
+ handleJsonRpc(req) {
356
+ if (req.method === 'initialize') {
357
+ return {
358
+ jsonrpc: '2.0',
359
+ id: req.id ?? null,
360
+ result: {
361
+ protocolVersion: '2024-11-05',
362
+ capabilities: {
363
+ tools: { listChanged: false },
364
+ },
365
+ serverInfo: {
366
+ name: '@fabersep/memory',
367
+ version: '0.1.0',
368
+ },
369
+ },
370
+ };
371
+ }
372
+ if (req.method === 'notifications/initialized') {
373
+ return null;
374
+ }
375
+ if (req.method === 'ping') {
376
+ return { jsonrpc: '2.0', id: req.id ?? null, result: {} };
377
+ }
378
+ if (req.method === 'tools/list') {
379
+ return {
380
+ jsonrpc: '2.0',
381
+ id: req.id ?? null,
382
+ result: { tools: this.listTools() },
383
+ };
384
+ }
385
+ if (req.method === 'tools/call') {
386
+ const params = req.params || {};
387
+ const toolName = String(params.name || '');
388
+ const toolArgs = params.arguments || {};
389
+ const res = this.handleToolCall(toolName, toolArgs);
390
+ return {
391
+ jsonrpc: '2.0',
392
+ id: req.id ?? null,
393
+ result: res,
394
+ };
395
+ }
396
+ if (req.id === undefined)
397
+ return null;
398
+ return {
399
+ jsonrpc: '2.0',
400
+ id: req.id,
401
+ error: { code: -32601, message: `Method not found: ${req.method}` },
402
+ };
403
+ }
404
+ serveStdio() {
405
+ this.startNonBlockingSync();
406
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
407
+ rl.on('line', (line) => {
408
+ const trimmed = line.trim();
409
+ if (!trimmed)
410
+ return;
411
+ try {
412
+ const req = JSON.parse(trimmed);
413
+ const resp = this.handleJsonRpc(req);
414
+ if (resp) {
415
+ process.stdout.write(JSON.stringify(resp) + '\n');
416
+ }
417
+ }
418
+ catch (err) {
419
+ const errResp = {
420
+ jsonrpc: '2.0',
421
+ id: null,
422
+ error: {
423
+ code: -32700,
424
+ message: `Parse error: ${err instanceof Error ? err.message : String(err)}`,
425
+ },
426
+ };
427
+ process.stdout.write(JSON.stringify(errResp) + '\n');
428
+ }
429
+ });
430
+ }
431
+ }
432
+ function errorResponse(message, extra) {
433
+ return {
434
+ isError: true,
435
+ content: [{ type: 'text', text: JSON.stringify({ error: message, ...extra }, null, 2) }],
436
+ };
437
+ }
@@ -0,0 +1,72 @@
1
+ import { ProposalAction, Scope } from './types.js';
2
+ export type CompileTrigger = 'cli' | 'sync' | 'mcp-startup' | 'approve' | 'init';
3
+ export type ProposeSource = 'mcp' | 'import';
4
+ export type ProposeOutcome = 'staged' | 'duplicate_blocked' | 'hygiene_blocked' | 'validation_error';
5
+ export type ReviewOutcome = 'approved_committed' | 'approved_pushed' | 'approved_pr' | 'push_failed' | 'awaiting_commit' | 'rejected';
6
+ export interface CompileMetricEvent {
7
+ type: 'compile';
8
+ ts: string;
9
+ trigger: CompileTrigger;
10
+ initial: boolean;
11
+ changed: boolean;
12
+ l0_sha256: string;
13
+ l0_tokens: number;
14
+ corpus_tokens: number;
15
+ active_entries: number;
16
+ }
17
+ export interface SearchMetricEvent {
18
+ type: 'search';
19
+ ts: string;
20
+ scope?: Scope;
21
+ result_count: number;
22
+ zero_result: boolean;
23
+ empty_query: boolean;
24
+ latency_ms: number;
25
+ }
26
+ export interface GetMetricEvent {
27
+ type: 'get';
28
+ ts: string;
29
+ found_ids: string[];
30
+ ids_truncated?: boolean;
31
+ found_count: number;
32
+ not_found_count: number;
33
+ latency_ms: number;
34
+ }
35
+ export interface ProposeMetricEvent {
36
+ type: 'propose';
37
+ ts: string;
38
+ source: ProposeSource;
39
+ scope: Scope;
40
+ action: ProposalAction;
41
+ outcome: ProposeOutcome;
42
+ hygiene_category?: 'secret' | 'machine-path';
43
+ }
44
+ export interface ReviewOutcomeMetricEvent {
45
+ type: 'review_outcome';
46
+ ts: string;
47
+ scope: Scope;
48
+ outcome: ReviewOutcome;
49
+ }
50
+ export type MetricEvent = CompileMetricEvent | SearchMetricEvent | GetMetricEvent | ProposeMetricEvent | ReviewOutcomeMetricEvent;
51
+ export declare const MAX_METRIC_LINE_BYTES = 4096;
52
+ export declare const MAX_GET_FOUND_IDS = 50;
53
+ export declare const METRICS_RETENTION_DAYS = 90;
54
+ export declare const METRICS_MAX_BYTES: number;
55
+ export declare const METRICS_TRIM_TARGET_BYTES: number;
56
+ export declare const METRICS_PRUNE_INTERVAL_MS: number;
57
+ export declare function getMetricsPath(homeDir?: string): string;
58
+ export declare function getMetricsPrunedPath(homeDir?: string): string;
59
+ export declare function getMetricsLockPath(homeDir?: string): string;
60
+ export declare function appendMetric(event: MetricEvent, homeDir?: string): void;
61
+ export declare function maybePruneMetrics(homeDir?: string, options?: {
62
+ nowMs?: number;
63
+ maxBytes?: number;
64
+ trimTargetBytes?: number;
65
+ retentionDays?: number;
66
+ }): boolean;
67
+ export interface ReadMetricsResult {
68
+ exists: boolean;
69
+ events: MetricEvent[];
70
+ skippedLines: number;
71
+ }
72
+ export declare function readMetrics(homeDir?: string): ReadMetricsResult;
@@ -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
+ }