@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.
@@ -3,7 +3,8 @@ import * as path from 'node:path';
3
3
  import { findNearDuplicates } from './bm25.js';
4
4
  import { getHomeDir } from './config.js';
5
5
  import { parseMarkdownWithFrontmatter, slugify } from './frontmatter.js';
6
- import { scanHygiene } from './hygiene.js';
6
+ import { normalizeMachinePaths, scanHygiene } from './hygiene.js';
7
+ import { appendMetric } from './metrics.js';
7
8
  import { approveProposalsBatch, createProposal, reconcileAwaitingCommitProposals, } from './proposals.js';
8
9
  import { loadAllScopes, resolveProjectRoot } from './store.js';
9
10
  import { VALID_TYPES } from './types.js';
@@ -95,6 +96,8 @@ export async function runImport(config, options) {
95
96
  const staged = [];
96
97
  const duplicates = [];
97
98
  const skippedHygiene = [];
99
+ const skippedIndex = [];
100
+ const normalizedPaths = [];
98
101
  const notes = [];
99
102
  if (options.from === 'claude-memory') {
100
103
  notes.push(CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE);
@@ -104,7 +107,12 @@ export async function runImport(config, options) {
104
107
  const files = collectMarkdownFiles(options.sourcePath);
105
108
  for (const filePath of files) {
106
109
  const base = path.basename(filePath);
107
- if (base.toLowerCase() === 'memory.md' || base.toLowerCase() === 'catalog.md' || base.toLowerCase() === 'readme.md') {
110
+ const lowerBase = base.toLowerCase();
111
+ if (lowerBase === 'memory.md' ||
112
+ lowerBase === 'catalog.md' ||
113
+ lowerBase === 'readme.md' ||
114
+ lowerBase === 'index.md') {
115
+ skippedIndex.push(filePath);
108
116
  continue;
109
117
  }
110
118
  const raw = fs.readFileSync(filePath, 'utf8');
@@ -164,16 +172,48 @@ export async function runImport(config, options) {
164
172
  }
165
173
  }
166
174
  for (const c of candidates) {
167
- const hygiene = scanHygiene(`${c.summary}\n${c.body}`);
175
+ let summary = c.summary;
176
+ let body = c.body;
177
+ if (options.normalizePaths) {
178
+ const sNorm = normalizeMachinePaths(summary);
179
+ const bNorm = normalizeMachinePaths(body);
180
+ summary = sNorm.content;
181
+ body = bNorm.content;
182
+ const total = sNorm.replacements + bNorm.replacements;
183
+ if (total > 0) {
184
+ normalizedPaths.push({ source: c.source, replacements: total });
185
+ }
186
+ }
187
+ const hygiene = scanHygiene(`${summary}\n${body}`);
168
188
  if (hygiene.length > 0) {
189
+ const hasSecret = hygiene.some((h) => h.category === 'secret');
190
+ appendMetric({
191
+ type: 'propose',
192
+ ts: new Date().toISOString(),
193
+ source: 'import',
194
+ scope: targetScope,
195
+ action: 'create',
196
+ outcome: 'hygiene_blocked',
197
+ hygiene_category: hasSecret ? 'secret' : 'machine-path',
198
+ }, homeDir);
169
199
  skippedHygiene.push({
170
200
  source: c.source,
171
201
  reason: hygiene.map((h) => h.message).join('; '),
202
+ snippet: hygiene[0].redactedSnippet,
203
+ anchor: hasSecret ? 'secrets-detected' : 'machine-specific-paths',
172
204
  });
173
205
  continue;
174
206
  }
175
- const dupes = findNearDuplicates(c.summary, c.body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
207
+ const dupes = findNearDuplicates(summary, body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
176
208
  if (dupes.length > 0) {
209
+ appendMetric({
210
+ type: 'propose',
211
+ ts: new Date().toISOString(),
212
+ source: 'import',
213
+ scope: targetScope,
214
+ action: 'create',
215
+ outcome: 'duplicate_blocked',
216
+ }, homeDir);
177
217
  duplicates.push({
178
218
  source: c.source,
179
219
  matchedId: dupes[0].id,
@@ -185,12 +225,20 @@ export async function runImport(config, options) {
185
225
  scope: targetScope,
186
226
  action: 'create',
187
227
  entryId: c.entryId,
188
- summary: c.summary,
228
+ summary,
189
229
  type: c.type,
190
230
  tags: c.tags,
191
- body: c.body,
231
+ body,
192
232
  projectRootPath: targetScope === 'project' ? projectRes.projectRoot : undefined,
193
233
  }, homeDir);
234
+ appendMetric({
235
+ type: 'propose',
236
+ ts: new Date().toISOString(),
237
+ source: 'import',
238
+ scope: targetScope,
239
+ action: 'create',
240
+ outcome: 'staged',
241
+ }, homeDir);
194
242
  staged.push(proposal);
195
243
  }
196
244
  const approvedIds = [];
@@ -206,6 +254,8 @@ export async function runImport(config, options) {
206
254
  approvedIds,
207
255
  duplicates,
208
256
  skippedHygiene,
257
+ skippedIndex,
258
+ normalizedPaths,
209
259
  notes,
210
260
  };
211
261
  }
@@ -11,3 +11,8 @@ export * from './sync.js';
11
11
  export * from './importer.js';
12
12
  export * from './init.js';
13
13
  export * from './mcp.js';
14
+ export * from './ui.js';
15
+ export * from './metrics.js';
16
+ export * from './cache-logs.js';
17
+ export * from './stats.js';
18
+ export * from './doctor.js';
package/dist/src/index.js CHANGED
@@ -11,3 +11,8 @@ export * from './sync.js';
11
11
  export * from './importer.js';
12
12
  export * from './init.js';
13
13
  export * from './mcp.js';
14
+ export * from './ui.js';
15
+ export * from './metrics.js';
16
+ export * from './cache-logs.js';
17
+ export * from './stats.js';
18
+ export * from './doctor.js';
@@ -40,3 +40,4 @@ export declare function planOrApplyInit(config: UserConfig, options?: {
40
40
  userHome?: string;
41
41
  }): InitPlanResult;
42
42
  export declare function formatUnifiedDiff(plan: FilePlan): string;
43
+ export declare function formatPlanBeforeAfter(plan: FilePlan, useColor?: boolean): string;
package/dist/src/init.js CHANGED
@@ -3,6 +3,7 @@ import * as os from 'node:os';
3
3
  import * as path from 'node:path';
4
4
  import { getCompiledL0Path, getHomeDir } from './config.js';
5
5
  import { compileGlobalL0 } from './compiler.js';
6
+ import { c, hr, shouldUseColor } from './ui.js';
6
7
  export const BLOCK_START = '<!-- faber-memory:start -->';
7
8
  export const BLOCK_END = '<!-- faber-memory:end -->';
8
9
  export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
@@ -136,7 +137,7 @@ export function planOrApplyInit(config, options = {}) {
136
137
  const backups = [];
137
138
  if (options.apply && !options.undo) {
138
139
  // Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
139
- const comp = compileGlobalL0(config, { homeDir });
140
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'init' });
140
141
  if (!comp.ok) {
141
142
  throw new Error(`L0 compilation failed before init --apply:\n${comp.errors.join('\n')}`);
142
143
  }
@@ -240,3 +241,40 @@ export function formatUnifiedDiff(plan) {
240
241
  }
241
242
  return out.join('\n');
242
243
  }
244
+ export function formatPlanBeforeAfter(plan, useColor = shouldUseColor()) {
245
+ const lines = [];
246
+ lines.push(c.dim(hr('═', 64), useColor));
247
+ lines.push(`${c.bold(c.cyan(`[${plan.engine}]`, useColor), useColor)} ${c.bold(plan.kind, useColor)} — ${plan.filePath}`);
248
+ lines.push(c.dim(hr('─', 64), useColor));
249
+ if (!plan.changed) {
250
+ lines.push(c.dim(' (no changes)', useColor));
251
+ return lines.join('\n');
252
+ }
253
+ const beforeLines = (plan.before ?? '').split('\n');
254
+ const afterLines = plan.after.split('\n');
255
+ const removed = beforeLines.filter((l) => l && !afterLines.includes(l));
256
+ const added = afterLines.filter((l) => l && !beforeLines.includes(l));
257
+ lines.push(c.bold(c.red('Before:', useColor), useColor));
258
+ if (plan.before === null) {
259
+ lines.push(c.dim(' (file does not exist yet)', useColor));
260
+ }
261
+ else if (removed.length === 0) {
262
+ lines.push(c.dim(' (existing content kept as-is)', useColor));
263
+ }
264
+ else {
265
+ for (const l of removed) {
266
+ lines.push(c.red(` - ${l}`, useColor));
267
+ }
268
+ }
269
+ lines.push('');
270
+ lines.push(c.bold(c.green('After:', useColor), useColor));
271
+ if (added.length === 0) {
272
+ lines.push(c.dim(' (removed faber-memory block/entry; remaining file preserved)', useColor));
273
+ }
274
+ else {
275
+ for (const l of added) {
276
+ lines.push(c.green(` + ${l}`, useColor));
277
+ }
278
+ }
279
+ return lines.join('\n');
280
+ }
package/dist/src/mcp.d.ts CHANGED
@@ -4,6 +4,96 @@ interface JsonRpcRequest {
4
4
  method: string;
5
5
  params?: Record<string, unknown>;
6
6
  }
7
+ export declare const MCP_TOOLS: readonly [{
8
+ readonly name: "memory_search";
9
+ readonly description: "Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.";
10
+ readonly inputSchema: {
11
+ readonly type: "object";
12
+ readonly properties: {
13
+ readonly query: {
14
+ readonly type: "string";
15
+ readonly description: "Keyword query; empty lists all.";
16
+ };
17
+ readonly scope: {
18
+ readonly type: "string";
19
+ readonly enum: readonly ["team", "personal", "project"];
20
+ };
21
+ readonly type: {
22
+ readonly type: "string";
23
+ readonly enum: readonly ["rule", "decision", "lesson", "preference", "reference"];
24
+ };
25
+ readonly include_pending: {
26
+ readonly type: "boolean";
27
+ readonly default: false;
28
+ };
29
+ };
30
+ };
31
+ }, {
32
+ readonly name: "memory_get";
33
+ readonly description: "Fetch full L2 Markdown body, frontmatter metadata, and links for one or more IDs.";
34
+ readonly inputSchema: {
35
+ readonly type: "object";
36
+ readonly properties: {
37
+ readonly ids: {
38
+ readonly type: "array";
39
+ readonly items: {
40
+ readonly type: "string";
41
+ };
42
+ readonly minItems: 1;
43
+ };
44
+ };
45
+ readonly required: readonly ["ids"];
46
+ };
47
+ }, {
48
+ readonly name: "memory_propose";
49
+ readonly description: "Submit a create, update, or supersede proposal to pre-memory for human approval.";
50
+ readonly inputSchema: {
51
+ readonly type: "object";
52
+ readonly properties: {
53
+ readonly action: {
54
+ readonly type: "string";
55
+ readonly enum: readonly ["create", "update", "supersede"];
56
+ };
57
+ readonly scope: {
58
+ readonly type: "string";
59
+ readonly enum: readonly ["team", "personal", "project"];
60
+ };
61
+ readonly summary: {
62
+ readonly type: "string";
63
+ };
64
+ readonly type: {
65
+ readonly type: "string";
66
+ readonly enum: readonly ["rule", "decision", "lesson", "preference", "reference"];
67
+ };
68
+ readonly body: {
69
+ readonly type: "string";
70
+ };
71
+ readonly target_id: {
72
+ readonly type: "string";
73
+ };
74
+ readonly entry_id: {
75
+ readonly type: "string";
76
+ };
77
+ readonly tags: {
78
+ readonly type: "array";
79
+ readonly items: {
80
+ readonly type: "string";
81
+ };
82
+ };
83
+ readonly l0: {
84
+ readonly type: "string";
85
+ readonly enum: readonly ["none", "line", "body"];
86
+ };
87
+ readonly force_new: {
88
+ readonly type: "boolean";
89
+ };
90
+ readonly reason: {
91
+ readonly type: "string";
92
+ };
93
+ };
94
+ readonly required: readonly ["action", "scope", "summary", "type", "body"];
95
+ };
96
+ }];
7
97
  export declare class FaberMemoryMcpServer {
8
98
  private readonly homeDir;
9
99
  private readonly cwd;
package/dist/src/mcp.js CHANGED
@@ -5,11 +5,12 @@ import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
5
5
  import { compileGlobalL0 } from './compiler.js';
6
6
  import { getHeadSha } from './git.js';
7
7
  import { formatHygieneErrors, scanHygiene } from './hygiene.js';
8
+ import { appendMetric, MAX_GET_FOUND_IDS } from './metrics.js';
8
9
  import { createProposal, reconcileAwaitingCommitProposals } from './proposals.js';
9
10
  import { loadAllScopes, resolveProjectRoot } from './store.js';
10
11
  import { syncAllRoots } from './sync.js';
11
12
  import { VALID_TYPES, } from './types.js';
12
- const MCP_TOOLS = [
13
+ export const MCP_TOOLS = [
13
14
  {
14
15
  name: 'memory_search',
15
16
  description: 'Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.',
@@ -76,12 +77,13 @@ export class FaberMemoryMcpServer {
76
77
  const config = loadConfig(this.homeDir);
77
78
  // Ensure compiled L0 exists on startup if missing
78
79
  if (!fs.existsSync(getCompiledL0Path(this.homeDir))) {
79
- compileGlobalL0(config, { homeDir: this.homeDir });
80
+ compileGlobalL0(config, { homeDir: this.homeDir, trigger: 'mcp-startup' });
80
81
  }
81
82
  this.startupPullPromise = syncAllRoots(config, {
82
83
  homeDir: this.homeDir,
83
84
  timeoutMs: this.startupPullTimeoutMs,
84
85
  recompile: true,
86
+ trigger: 'mcp-startup',
85
87
  })
86
88
  .then((res) => {
87
89
  if (res.warnings.length > 0) {
@@ -134,7 +136,18 @@ export class FaberMemoryMcpServer {
134
136
  const scope = typeof args.scope === 'string' ? args.scope : undefined;
135
137
  const type = typeof args.type === 'string' ? args.type : undefined;
136
138
  const includePending = Boolean(args.include_pending);
139
+ const t0 = performance.now();
137
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);
138
151
  const warnings = this.drainWarnings(loaded);
139
152
  const payload = {
140
153
  results,
@@ -156,6 +169,7 @@ export class FaberMemoryMcpServer {
156
169
  content: [{ type: 'text', text: JSON.stringify({ error: 'ids array is required' }) }],
157
170
  };
158
171
  }
172
+ const t0 = performance.now();
159
173
  const found = [];
160
174
  const notFound = [];
161
175
  for (const id of ids) {
@@ -183,6 +197,18 @@ export class FaberMemoryMcpServer {
183
197
  }
184
198
  }
185
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);
186
212
  const warnings = this.drainWarnings(loaded);
187
213
  return {
188
214
  content: [
@@ -206,46 +232,74 @@ export class FaberMemoryMcpServer {
206
232
  const l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
207
233
  const forceNew = Boolean(args.force_new);
208
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
+ };
209
252
  if (!['create', 'update', 'supersede'].includes(action)) {
253
+ recordPropose('validation_error');
210
254
  return errorResponse('Invalid action; expected create, update, or supersede.');
211
255
  }
212
256
  if (!['team', 'personal', 'project'].includes(scope)) {
257
+ recordPropose('validation_error');
213
258
  return errorResponse('Invalid scope; expected team, personal, or project.');
214
259
  }
215
260
  if (!summary) {
261
+ recordPropose('validation_error');
216
262
  return errorResponse('summary is required.');
217
263
  }
218
264
  if (!VALID_TYPES.includes(type)) {
265
+ recordPropose('validation_error');
219
266
  return errorResponse(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
220
267
  }
221
268
  if (!body) {
269
+ recordPropose('validation_error');
222
270
  return errorResponse('body is required.');
223
271
  }
224
272
  // Validate target_id for update / supersede (AC-08c1, AC-08c2)
225
273
  if (action === 'update' || action === 'supersede') {
226
274
  if (!targetId) {
275
+ recordPropose('validation_error');
227
276
  return errorResponse(`target_id is required when action is "${action}".`);
228
277
  }
229
278
  const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
230
279
  loaded.activeEntries.some((e) => e.id === targetId);
231
280
  if (!exists) {
281
+ recordPropose('validation_error');
232
282
  return errorResponse(`Target entry "${targetId}" not found in active memory.`);
233
283
  }
234
284
  }
235
285
  // Hygiene scan (AC-20a)
236
286
  const hygieneFindings = scanHygiene(`${summary}\n${body}`);
237
287
  if (hygieneFindings.length > 0) {
288
+ const hasSecret = hygieneFindings.some((f) => f.category === 'secret');
289
+ recordPropose('hygiene_blocked', hasSecret ? 'secret' : 'machine-path');
238
290
  return errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings });
239
291
  }
240
292
  // Near-duplicate check on create (AC-10, AC-11)
241
293
  if (action === 'create') {
242
294
  if (forceNew && !reason) {
295
+ recordPropose('validation_error');
243
296
  return errorResponse('A non-empty "reason" is required when force_new is true.');
244
297
  }
245
298
  if (!forceNew) {
246
299
  const pending = reconcileAwaitingCommitProposals(this.homeDir);
247
300
  const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
248
301
  if (matches.length > 0) {
302
+ recordPropose('duplicate_blocked');
249
303
  return errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
250
304
  matches: matches.map((m) => ({
251
305
  id: m.id,
@@ -273,6 +327,7 @@ export class FaberMemoryMcpServer {
273
327
  reason,
274
328
  projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
275
329
  }, this.homeDir);
330
+ recordPropose('staged');
276
331
  this.lastHeadSignature = '';
277
332
  const warnings = this.drainWarnings(loaded);
278
333
  return {
@@ -291,6 +346,7 @@ export class FaberMemoryMcpServer {
291
346
  };
292
347
  }
293
348
  catch (err) {
349
+ recordPropose('validation_error');
294
350
  return errorResponse(err instanceof Error ? err.message : String(err));
295
351
  }
296
352
  }
@@ -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;