@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.
@@ -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';
@@ -43,6 +44,11 @@ function inferSummary(raw, body, fallbackName) {
43
44
  .find((l) => l.length > 0);
44
45
  return (firstLine || fallbackName).slice(0, 140);
45
46
  }
47
+ // A heading with nothing under it but the next heading (e.g. a "# Rules" title
48
+ // above "## ..." sections) is not an entry of its own.
49
+ function hasSectionBody(section) {
50
+ return section.lines.slice(1).join('\n').trim().length > 0;
51
+ }
46
52
  function splitTopLevelHeadings(content) {
47
53
  const lines = content.replace(/\r\n/g, '\n').split('\n');
48
54
  const sections = [];
@@ -50,7 +56,7 @@ function splitTopLevelHeadings(content) {
50
56
  for (const line of lines) {
51
57
  const m = line.match(/^#{1,2}\s+(.+)$/);
52
58
  if (m) {
53
- if (current && current.lines.join('\n').trim()) {
59
+ if (current && hasSectionBody(current)) {
54
60
  sections.push(current);
55
61
  }
56
62
  current = { title: m[1].trim(), lines: [line] };
@@ -59,7 +65,7 @@ function splitTopLevelHeadings(content) {
59
65
  current.lines.push(line);
60
66
  }
61
67
  }
62
- if (current && current.lines.join('\n').trim()) {
68
+ if (current && hasSectionBody(current)) {
63
69
  sections.push(current);
64
70
  }
65
71
  return sections.map((s) => ({ title: s.title, body: s.lines.join('\n').trim() }));
@@ -95,6 +101,8 @@ export async function runImport(config, options) {
95
101
  const staged = [];
96
102
  const duplicates = [];
97
103
  const skippedHygiene = [];
104
+ const skippedIndex = [];
105
+ const normalizedPaths = [];
98
106
  const notes = [];
99
107
  if (options.from === 'claude-memory') {
100
108
  notes.push(CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE);
@@ -104,7 +112,12 @@ export async function runImport(config, options) {
104
112
  const files = collectMarkdownFiles(options.sourcePath);
105
113
  for (const filePath of files) {
106
114
  const base = path.basename(filePath);
107
- if (base.toLowerCase() === 'memory.md' || base.toLowerCase() === 'catalog.md' || base.toLowerCase() === 'readme.md') {
115
+ const lowerBase = base.toLowerCase();
116
+ if (lowerBase === 'memory.md' ||
117
+ lowerBase === 'catalog.md' ||
118
+ lowerBase === 'readme.md' ||
119
+ lowerBase === 'index.md') {
120
+ skippedIndex.push(filePath);
108
121
  continue;
109
122
  }
110
123
  const raw = fs.readFileSync(filePath, 'utf8');
@@ -164,16 +177,48 @@ export async function runImport(config, options) {
164
177
  }
165
178
  }
166
179
  for (const c of candidates) {
167
- const hygiene = scanHygiene(`${c.summary}\n${c.body}`);
180
+ let summary = c.summary;
181
+ let body = c.body;
182
+ if (options.normalizePaths) {
183
+ const sNorm = normalizeMachinePaths(summary);
184
+ const bNorm = normalizeMachinePaths(body);
185
+ summary = sNorm.content;
186
+ body = bNorm.content;
187
+ const total = sNorm.replacements + bNorm.replacements;
188
+ if (total > 0) {
189
+ normalizedPaths.push({ source: c.source, replacements: total });
190
+ }
191
+ }
192
+ const hygiene = scanHygiene(`${summary}\n${body}`);
168
193
  if (hygiene.length > 0) {
194
+ const hasSecret = hygiene.some((h) => h.category === 'secret');
195
+ appendMetric({
196
+ type: 'propose',
197
+ ts: new Date().toISOString(),
198
+ source: 'import',
199
+ scope: targetScope,
200
+ action: 'create',
201
+ outcome: 'hygiene_blocked',
202
+ hygiene_category: hasSecret ? 'secret' : 'machine-path',
203
+ }, homeDir);
169
204
  skippedHygiene.push({
170
205
  source: c.source,
171
206
  reason: hygiene.map((h) => h.message).join('; '),
207
+ snippet: hygiene[0].redactedSnippet,
208
+ anchor: hasSecret ? 'secrets-detected' : 'machine-specific-paths',
172
209
  });
173
210
  continue;
174
211
  }
175
- const dupes = findNearDuplicates(c.summary, c.body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
212
+ const dupes = findNearDuplicates(summary, body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
176
213
  if (dupes.length > 0) {
214
+ appendMetric({
215
+ type: 'propose',
216
+ ts: new Date().toISOString(),
217
+ source: 'import',
218
+ scope: targetScope,
219
+ action: 'create',
220
+ outcome: 'duplicate_blocked',
221
+ }, homeDir);
177
222
  duplicates.push({
178
223
  source: c.source,
179
224
  matchedId: dupes[0].id,
@@ -185,12 +230,20 @@ export async function runImport(config, options) {
185
230
  scope: targetScope,
186
231
  action: 'create',
187
232
  entryId: c.entryId,
188
- summary: c.summary,
233
+ summary,
189
234
  type: c.type,
190
235
  tags: c.tags,
191
- body: c.body,
236
+ body,
192
237
  projectRootPath: targetScope === 'project' ? projectRes.projectRoot : undefined,
193
238
  }, homeDir);
239
+ appendMetric({
240
+ type: 'propose',
241
+ ts: new Date().toISOString(),
242
+ source: 'import',
243
+ scope: targetScope,
244
+ action: 'create',
245
+ outcome: 'staged',
246
+ }, homeDir);
194
247
  staged.push(proposal);
195
248
  }
196
249
  const approvedIds = [];
@@ -206,6 +259,8 @@ export async function runImport(config, options) {
206
259
  approvedIds,
207
260
  duplicates,
208
261
  skippedHygiene,
262
+ skippedIndex,
263
+ normalizedPaths,
209
264
  notes,
210
265
  };
211
266
  }
@@ -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';
@@ -1,6 +1,7 @@
1
1
  import { UserConfig } from './types.js';
2
2
  export declare const BLOCK_START = "<!-- faber-memory:start -->";
3
3
  export declare const BLOCK_END = "<!-- faber-memory:end -->";
4
+ export declare const TOOL_GUIDANCE_LINE = "Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).";
4
5
  export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
5
6
  export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
6
7
  export interface EngineSpec {
@@ -40,3 +41,4 @@ export declare function planOrApplyInit(config: UserConfig, options?: {
40
41
  userHome?: string;
41
42
  }): InitPlanResult;
42
43
  export declare function formatUnifiedDiff(plan: FilePlan): string;
44
+ export declare function formatPlanBeforeAfter(plan: FilePlan, useColor?: boolean): string;
package/dist/src/init.js CHANGED
@@ -3,8 +3,10 @@ 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 -->';
9
+ export const TOOL_GUIDANCE_LINE = 'Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).';
8
10
  export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
9
11
  export function getEngineSpecs() {
10
12
  return {
@@ -14,7 +16,7 @@ export function getEngineSpecs() {
14
16
  gap: false,
15
17
  instructionFile: (home) => path.join(home, '.claude', 'CLAUDE.md'),
16
18
  mcpConfigFile: (home) => path.join(home, '.claude.json'),
17
- renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${BLOCK_END}`,
19
+ renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
18
20
  },
19
21
  'claude-desktop': {
20
22
  name: 'claude-desktop',
@@ -30,7 +32,7 @@ export function getEngineSpecs() {
30
32
  gap: false,
31
33
  instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
32
34
  mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
33
- renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path} for global L0 memory and use the faber-memory MCP tools (memory_search, memory_get, memory_propose) for deeper recall.\n${BLOCK_END}`,
35
+ renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path} (global L0 memory).\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
34
36
  },
35
37
  cursor: {
36
38
  name: 'cursor',
@@ -136,9 +138,9 @@ export function planOrApplyInit(config, options = {}) {
136
138
  const backups = [];
137
139
  if (options.apply && !options.undo) {
138
140
  // Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
139
- const comp = compileGlobalL0(config, { homeDir });
141
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'init' });
140
142
  if (!comp.ok) {
141
- throw new Error(`L0 compilation failed before init --apply:\n${comp.errors.join('\n')}`);
143
+ throw new Error(`L0 compilation failed before init:\n${comp.errors.join('\n')}`);
142
144
  }
143
145
  }
144
146
  for (const engineName of engines) {
@@ -240,3 +242,40 @@ export function formatUnifiedDiff(plan) {
240
242
  }
241
243
  return out.join('\n');
242
244
  }
245
+ export function formatPlanBeforeAfter(plan, useColor = shouldUseColor()) {
246
+ const lines = [];
247
+ lines.push(c.dim(hr('═', 64), useColor));
248
+ lines.push(`${c.bold(c.cyan(`[${plan.engine}]`, useColor), useColor)} ${c.bold(plan.kind, useColor)} — ${plan.filePath}`);
249
+ lines.push(c.dim(hr('─', 64), useColor));
250
+ if (!plan.changed) {
251
+ lines.push(c.dim(' (no changes)', useColor));
252
+ return lines.join('\n');
253
+ }
254
+ const beforeLines = (plan.before ?? '').split('\n');
255
+ const afterLines = plan.after.split('\n');
256
+ const removed = beforeLines.filter((l) => l && !afterLines.includes(l));
257
+ const added = afterLines.filter((l) => l && !beforeLines.includes(l));
258
+ lines.push(c.bold(c.red('Before:', useColor), useColor));
259
+ if (plan.before === null) {
260
+ lines.push(c.dim(' (file does not exist yet)', useColor));
261
+ }
262
+ else if (removed.length === 0) {
263
+ lines.push(c.dim(' (existing content kept as-is)', useColor));
264
+ }
265
+ else {
266
+ for (const l of removed) {
267
+ lines.push(c.red(` - ${l}`, useColor));
268
+ }
269
+ }
270
+ lines.push('');
271
+ lines.push(c.bold(c.green('After:', useColor), useColor));
272
+ if (added.length === 0) {
273
+ lines.push(c.dim(' (removed faber-memory block/entry; remaining file preserved)', useColor));
274
+ }
275
+ else {
276
+ for (const l of added) {
277
+ lines.push(c.green(` + ${l}`, useColor));
278
+ }
279
+ }
280
+ return lines.join('\n');
281
+ }
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: "Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.";
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;
@@ -67,7 +157,7 @@ export declare class FaberMemoryMcpServer {
67
157
  };
68
158
  }, {
69
159
  readonly name: "memory_propose";
70
- readonly description: "Submit a create, update, or supersede proposal to pre-memory for human approval.";
160
+ readonly description: "Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.";
71
161
  readonly inputSchema: {
72
162
  readonly type: "object";
73
163
  readonly properties: {
package/dist/src/mcp.js CHANGED
@@ -5,11 +5,13 @@ 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';
12
+ import { getPackageVersion } from './version.js';
11
13
  import { VALID_TYPES, } from './types.js';
12
- const MCP_TOOLS = [
14
+ export const MCP_TOOLS = [
13
15
  {
14
16
  name: 'memory_search',
15
17
  description: 'Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.',
@@ -36,7 +38,7 @@ const MCP_TOOLS = [
36
38
  },
37
39
  {
38
40
  name: 'memory_propose',
39
- description: 'Submit a create, update, or supersede proposal to pre-memory for human approval.',
41
+ description: 'Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.',
40
42
  inputSchema: {
41
43
  type: 'object',
42
44
  properties: {
@@ -76,12 +78,13 @@ export class FaberMemoryMcpServer {
76
78
  const config = loadConfig(this.homeDir);
77
79
  // Ensure compiled L0 exists on startup if missing
78
80
  if (!fs.existsSync(getCompiledL0Path(this.homeDir))) {
79
- compileGlobalL0(config, { homeDir: this.homeDir });
81
+ compileGlobalL0(config, { homeDir: this.homeDir, trigger: 'mcp-startup' });
80
82
  }
81
83
  this.startupPullPromise = syncAllRoots(config, {
82
84
  homeDir: this.homeDir,
83
85
  timeoutMs: this.startupPullTimeoutMs,
84
86
  recompile: true,
87
+ trigger: 'mcp-startup',
85
88
  })
86
89
  .then((res) => {
87
90
  if (res.warnings.length > 0) {
@@ -134,7 +137,18 @@ export class FaberMemoryMcpServer {
134
137
  const scope = typeof args.scope === 'string' ? args.scope : undefined;
135
138
  const type = typeof args.type === 'string' ? args.type : undefined;
136
139
  const includePending = Boolean(args.include_pending);
140
+ const t0 = performance.now();
137
141
  const results = this.index.search(query, { scope, type, includePending });
142
+ const latencyMs = Math.round((performance.now() - t0) * 100) / 100;
143
+ appendMetric({
144
+ type: 'search',
145
+ ts: new Date().toISOString(),
146
+ ...(scope ? { scope } : {}),
147
+ result_count: results.length,
148
+ zero_result: results.length === 0,
149
+ empty_query: query.trim().length === 0,
150
+ latency_ms: latencyMs,
151
+ }, this.homeDir);
138
152
  const warnings = this.drainWarnings(loaded);
139
153
  const payload = {
140
154
  results,
@@ -156,6 +170,7 @@ export class FaberMemoryMcpServer {
156
170
  content: [{ type: 'text', text: JSON.stringify({ error: 'ids array is required' }) }],
157
171
  };
158
172
  }
173
+ const t0 = performance.now();
159
174
  const found = [];
160
175
  const notFound = [];
161
176
  for (const id of ids) {
@@ -183,6 +198,18 @@ export class FaberMemoryMcpServer {
183
198
  }
184
199
  }
185
200
  }
201
+ const latencyMs = Math.round((performance.now() - t0) * 100) / 100;
202
+ const allFoundIds = found.map((e) => `${e.scope}:${e.id}`);
203
+ const idsTruncated = allFoundIds.length > MAX_GET_FOUND_IDS;
204
+ appendMetric({
205
+ type: 'get',
206
+ ts: new Date().toISOString(),
207
+ found_ids: idsTruncated ? allFoundIds.slice(0, MAX_GET_FOUND_IDS) : allFoundIds,
208
+ ...(idsTruncated ? { ids_truncated: true } : {}),
209
+ found_count: found.length,
210
+ not_found_count: notFound.length,
211
+ latency_ms: latencyMs,
212
+ }, this.homeDir);
186
213
  const warnings = this.drainWarnings(loaded);
187
214
  return {
188
215
  content: [
@@ -206,46 +233,74 @@ export class FaberMemoryMcpServer {
206
233
  const l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
207
234
  const forceNew = Boolean(args.force_new);
208
235
  const reason = typeof args.reason === 'string' ? args.reason.trim() : undefined;
236
+ const metricScope = ['team', 'personal', 'project'].includes(scope)
237
+ ? scope
238
+ : 'personal';
239
+ const metricAction = ['create', 'update', 'supersede'].includes(action)
240
+ ? action
241
+ : 'create';
242
+ const recordPropose = (outcome, hygieneCategory) => {
243
+ appendMetric({
244
+ type: 'propose',
245
+ ts: new Date().toISOString(),
246
+ source: 'mcp',
247
+ scope: metricScope,
248
+ action: metricAction,
249
+ outcome,
250
+ ...(hygieneCategory ? { hygiene_category: hygieneCategory } : {}),
251
+ }, this.homeDir);
252
+ };
209
253
  if (!['create', 'update', 'supersede'].includes(action)) {
254
+ recordPropose('validation_error');
210
255
  return errorResponse('Invalid action; expected create, update, or supersede.');
211
256
  }
212
257
  if (!['team', 'personal', 'project'].includes(scope)) {
258
+ recordPropose('validation_error');
213
259
  return errorResponse('Invalid scope; expected team, personal, or project.');
214
260
  }
215
261
  if (!summary) {
262
+ recordPropose('validation_error');
216
263
  return errorResponse('summary is required.');
217
264
  }
218
265
  if (!VALID_TYPES.includes(type)) {
266
+ recordPropose('validation_error');
219
267
  return errorResponse(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
220
268
  }
221
269
  if (!body) {
270
+ recordPropose('validation_error');
222
271
  return errorResponse('body is required.');
223
272
  }
224
273
  // Validate target_id for update / supersede (AC-08c1, AC-08c2)
225
274
  if (action === 'update' || action === 'supersede') {
226
275
  if (!targetId) {
276
+ recordPropose('validation_error');
227
277
  return errorResponse(`target_id is required when action is "${action}".`);
228
278
  }
229
279
  const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
230
280
  loaded.activeEntries.some((e) => e.id === targetId);
231
281
  if (!exists) {
282
+ recordPropose('validation_error');
232
283
  return errorResponse(`Target entry "${targetId}" not found in active memory.`);
233
284
  }
234
285
  }
235
286
  // Hygiene scan (AC-20a)
236
287
  const hygieneFindings = scanHygiene(`${summary}\n${body}`);
237
288
  if (hygieneFindings.length > 0) {
289
+ const hasSecret = hygieneFindings.some((f) => f.category === 'secret');
290
+ recordPropose('hygiene_blocked', hasSecret ? 'secret' : 'machine-path');
238
291
  return errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings });
239
292
  }
240
293
  // Near-duplicate check on create (AC-10, AC-11)
241
294
  if (action === 'create') {
242
295
  if (forceNew && !reason) {
296
+ recordPropose('validation_error');
243
297
  return errorResponse('A non-empty "reason" is required when force_new is true.');
244
298
  }
245
299
  if (!forceNew) {
246
300
  const pending = reconcileAwaitingCommitProposals(this.homeDir);
247
301
  const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
248
302
  if (matches.length > 0) {
303
+ recordPropose('duplicate_blocked');
249
304
  return errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
250
305
  matches: matches.map((m) => ({
251
306
  id: m.id,
@@ -273,6 +328,7 @@ export class FaberMemoryMcpServer {
273
328
  reason,
274
329
  projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
275
330
  }, this.homeDir);
331
+ recordPropose('staged');
276
332
  this.lastHeadSignature = '';
277
333
  const warnings = this.drainWarnings(loaded);
278
334
  return {
@@ -291,6 +347,7 @@ export class FaberMemoryMcpServer {
291
347
  };
292
348
  }
293
349
  catch (err) {
350
+ recordPropose('validation_error');
294
351
  return errorResponse(err instanceof Error ? err.message : String(err));
295
352
  }
296
353
  }
@@ -308,7 +365,7 @@ export class FaberMemoryMcpServer {
308
365
  },
309
366
  serverInfo: {
310
367
  name: '@fabersep/memory',
311
- version: '0.1.0',
368
+ version: getPackageVersion(),
312
369
  },
313
370
  },
314
371
  };
@@ -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;