@fabersep/memory 0.5.1 → 0.6.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.
package/dist/src/init.js CHANGED
@@ -1,54 +1,20 @@
1
+ import { engines as historyEngines, historyKeep, InstructionHistory, withHistoryLock } from './instruction-history.js';
1
2
  import * as fs from 'node:fs';
2
- 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
6
  import { c, hr, shouldUseColor } from './ui.js';
7
- export const BLOCK_START = '<!-- faber-memory:start -->';
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). When the user explicitly asks you to remember something, call memory_propose with source "user" and their exact words in user_quote; it is saved at once.';
10
- export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
11
- export function getEngineSpecs() {
12
- return {
13
- 'claude-code': {
14
- name: 'claude-code',
15
- verifiedImport: true,
16
- gap: false,
17
- instructionFile: (home) => path.join(home, '.claude', 'CLAUDE.md'),
18
- mcpConfigFile: (home) => path.join(home, '.claude.json'),
19
- renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
20
- },
21
- 'claude-desktop': {
22
- name: 'claude-desktop',
23
- verifiedImport: false,
24
- gap: false,
25
- mcpConfigFile: (home) => process.platform === 'darwin'
26
- ? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
27
- : path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
28
- },
29
- antigravity: {
30
- name: 'antigravity',
31
- verifiedImport: true,
32
- gap: false,
33
- instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
34
- mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
35
- renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path} (global L0 memory).\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
36
- },
37
- cursor: {
38
- name: 'cursor',
39
- verifiedImport: false,
40
- gap: true,
41
- mcpConfigFile: (home) => path.join(home, '.cursor', 'mcp.json'),
42
- },
43
- codex: {
44
- name: 'codex',
45
- verifiedImport: false,
46
- gap: true,
47
- },
48
- };
49
- }
50
- export function getUserHome() {
51
- return process.env.FABER_USER_HOME || os.homedir();
7
+ import { BLOCK_START, BLOCK_END, getEngineSpecs, getUserHome, PROJECT_HINT_LINE } from './engines.js';
8
+ export * from './engines.js';
9
+ function instructionBytes(filePath) {
10
+ try {
11
+ return fs.readFileSync(filePath);
12
+ }
13
+ catch (e) {
14
+ if (e instanceof Error && 'code' in e && e.code === 'ENOENT')
15
+ return null;
16
+ throw e;
17
+ }
52
18
  }
53
19
  export function upsertManagedBlock(existing, block) {
54
20
  const escapedStart = escapeRegex(BLOCK_START);
@@ -78,27 +44,56 @@ export function removeManagedBlock(existing) {
78
44
  function escapeRegex(s) {
79
45
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
80
46
  }
47
+ const MCP_COMMAND = 'npx';
48
+ const MCP_ARGS = ['-y', '@fabersep/memory', 'serve'];
49
+ function parseJsonObject(raw) {
50
+ if (!raw || !raw.trim())
51
+ return null;
52
+ try {
53
+ const parsed = JSON.parse(raw);
54
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
55
+ ? parsed
56
+ : null;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ function getJsonMcpEntry(raw) {
63
+ const obj = parseJsonObject(raw);
64
+ const servers = obj?.mcpServers;
65
+ if (!servers || typeof servers !== 'object')
66
+ return undefined;
67
+ return servers['faber-memory'];
68
+ }
69
+ function isWantedMcpEntry(entry) {
70
+ if (!entry || typeof entry !== 'object')
71
+ return false;
72
+ const e = entry;
73
+ return (e.command === MCP_COMMAND &&
74
+ Array.isArray(e.args) &&
75
+ JSON.stringify(e.args) === JSON.stringify(MCP_ARGS));
76
+ }
81
77
  function upsertMcpJson(existingRaw) {
82
- let obj = {};
83
- if (existingRaw && existingRaw.trim()) {
84
- try {
85
- obj = JSON.parse(existingRaw);
86
- }
87
- catch {
88
- obj = {};
89
- }
78
+ // Leave the file byte-for-byte alone when the entry is already right, so a
79
+ // second init never rewrites (and reformats) a file the assistant owns.
80
+ if (existingRaw !== null && isWantedMcpEntry(getJsonMcpEntry(existingRaw))) {
81
+ return existingRaw;
90
82
  }
83
+ const obj = parseJsonObject(existingRaw) ?? {};
91
84
  const servers = obj.mcpServers && typeof obj.mcpServers === 'object'
92
85
  ? { ...obj.mcpServers }
93
86
  : {};
94
87
  servers['faber-memory'] = {
95
- command: 'npx',
96
- args: ['-y', '@fabersep/memory', 'serve'],
88
+ command: MCP_COMMAND,
89
+ args: [...MCP_ARGS],
97
90
  };
98
91
  obj.mcpServers = servers;
99
92
  return JSON.stringify(obj, null, 2) + '\n';
100
93
  }
101
94
  function removeMcpJson(existingRaw) {
95
+ if (getJsonMcpEntry(existingRaw) === undefined)
96
+ return existingRaw;
102
97
  let obj = {};
103
98
  try {
104
99
  obj = JSON.parse(existingRaw);
@@ -113,6 +108,46 @@ function removeMcpJson(existingRaw) {
113
108
  }
114
109
  return JSON.stringify(obj, null, 2) + '\n';
115
110
  }
111
+ // Codex keeps MCP servers in TOML (`[mcp_servers.<name>]`). The Codex app
112
+ // rewrites config.toml itself and drops comments, so the table header is the
113
+ // only marker init relies on; zero-dependency line handling, no TOML parser.
114
+ const TOML_FABER_TABLE = /^\s*\[\s*mcp_servers\s*\.\s*(?:faber-memory|"faber-memory"|'faber-memory')\s*(\]|\.)/;
115
+ const TOML_ANY_TABLE = /^\s*\[/;
116
+ export function renderCodexTomlTable() {
117
+ return [
118
+ '[mcp_servers.faber-memory]',
119
+ `command = ${JSON.stringify(MCP_COMMAND)}`,
120
+ `args = [${MCP_ARGS.map((a) => JSON.stringify(a)).join(', ')}]`,
121
+ ].join('\n');
122
+ }
123
+ export function hasCodexTomlEntry(raw) {
124
+ return Boolean(raw) && raw.split('\n').some((l) => TOML_FABER_TABLE.test(l));
125
+ }
126
+ export function upsertMcpToml(existingRaw) {
127
+ // An existing faber-memory table (ours, or edited by the user or the app) is kept as-is.
128
+ if (existingRaw !== null && hasCodexTomlEntry(existingRaw))
129
+ return existingRaw;
130
+ const trimmed = (existingRaw ?? '').trimEnd();
131
+ return trimmed ? `${trimmed}\n\n${renderCodexTomlTable()}\n` : `${renderCodexTomlTable()}\n`;
132
+ }
133
+ export function removeMcpToml(existingRaw) {
134
+ if (!hasCodexTomlEntry(existingRaw))
135
+ return existingRaw;
136
+ const out = [];
137
+ let skipping = false;
138
+ for (const line of existingRaw.split('\n')) {
139
+ if (TOML_FABER_TABLE.test(line)) {
140
+ skipping = true;
141
+ continue;
142
+ }
143
+ if (skipping && TOML_ANY_TABLE.test(line))
144
+ skipping = false;
145
+ if (!skipping)
146
+ out.push(line);
147
+ }
148
+ const next = out.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd();
149
+ return next ? `${next}\n` : '';
150
+ }
116
151
  export function detectTargetEngines(userHome, requested) {
117
152
  if (requested && requested.length > 0)
118
153
  return requested;
@@ -123,6 +158,8 @@ export function detectTargetEngines(userHome, requested) {
123
158
  detected.push('antigravity');
124
159
  if (fs.existsSync(path.join(userHome, '.cursor')))
125
160
  detected.push('cursor');
161
+ if (fs.existsSync(path.join(userHome, '.codex')))
162
+ detected.push('codex');
126
163
  if (detected.length === 0)
127
164
  detected.push('claude-code');
128
165
  return detected;
@@ -135,6 +172,7 @@ export function planOrApplyInit(config, options = {}) {
135
172
  const compiledL0Path = getCompiledL0Path(homeDir);
136
173
  const notes = [];
137
174
  const plans = [];
175
+ const originalInstructions = new Map();
138
176
  const backups = [];
139
177
  if (options.apply && !options.undo) {
140
178
  // Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
@@ -152,8 +190,8 @@ export function planOrApplyInit(config, options = {}) {
152
190
  }
153
191
  if (spec.instructionFile && spec.renderBlock && !spec.gap) {
154
192
  const filePath = spec.instructionFile(userHome);
155
- const exists = fs.existsSync(filePath);
156
- const before = exists ? fs.readFileSync(filePath, 'utf8') : null;
193
+ const original = instructionBytes(filePath);
194
+ const before = original?.toString('utf8') ?? null;
157
195
  const after = options.undo
158
196
  ? before !== null
159
197
  ? removeManagedBlock(before)
@@ -167,23 +205,31 @@ export function planOrApplyInit(config, options = {}) {
167
205
  before,
168
206
  after,
169
207
  changed,
208
+ action: planAction(changed, Boolean(options.undo), (before ?? '').includes(BLOCK_START)),
170
209
  };
171
210
  if (options.undo && fs.existsSync(`${filePath}.bak`)) {
172
211
  plan.backupPath = `${filePath}.bak`;
173
212
  backups.push(`${filePath}.bak`);
174
213
  }
214
+ originalInstructions.set(plan, original);
175
215
  plans.push(plan);
176
216
  }
177
217
  if (spec.mcpConfigFile) {
178
218
  const filePath = spec.mcpConfigFile(userHome);
179
219
  const exists = fs.existsSync(filePath);
180
220
  const before = exists ? fs.readFileSync(filePath, 'utf8') : null;
221
+ const toml = spec.mcpFormat === 'toml';
181
222
  const after = options.undo
182
223
  ? before !== null
183
- ? removeMcpJson(before)
224
+ ? toml
225
+ ? removeMcpToml(before)
226
+ : removeMcpJson(before)
184
227
  : ''
185
- : upsertMcpJson(before);
228
+ : toml
229
+ ? upsertMcpToml(before)
230
+ : upsertMcpJson(before);
186
231
  const changed = (before ?? '') !== after;
232
+ const hadEntry = toml ? hasCodexTomlEntry(before) : getJsonMcpEntry(before) !== undefined;
187
233
  const plan = {
188
234
  filePath,
189
235
  kind: 'mcp-config',
@@ -191,6 +237,7 @@ export function planOrApplyInit(config, options = {}) {
191
237
  before,
192
238
  after,
193
239
  changed,
240
+ action: planAction(changed, Boolean(options.undo), hadEntry),
194
241
  };
195
242
  if (options.undo && fs.existsSync(`${filePath}.bak`)) {
196
243
  plan.backupPath = `${filePath}.bak`;
@@ -200,22 +247,70 @@ export function planOrApplyInit(config, options = {}) {
200
247
  }
201
248
  }
202
249
  if (options.apply || options.undo) {
250
+ const historyErrors = new Set();
251
+ let retention;
203
252
  for (const p of plans) {
204
253
  if (!p.changed)
205
254
  continue;
206
255
  if (options.undo && p.before === null)
207
256
  continue;
208
- fs.mkdirSync(path.dirname(p.filePath), { recursive: true });
209
- if (!options.undo && p.before !== null) {
210
- const bakPath = `${p.filePath}.bak`;
211
- if (!fs.existsSync(bakPath)) {
212
- fs.writeFileSync(bakPath, p.before, 'utf8');
213
- p.backupPath = bakPath;
214
- backups.push(bakPath);
257
+ const write = () => {
258
+ fs.mkdirSync(path.dirname(p.filePath), { recursive: true });
259
+ if (!options.undo && p.before !== null) {
260
+ const bakPath = `${p.filePath}.bak`;
261
+ if (!fs.existsSync(bakPath)) {
262
+ fs.writeFileSync(bakPath, p.before, 'utf8');
263
+ p.backupPath = bakPath;
264
+ backups.push(bakPath);
265
+ }
215
266
  }
267
+ fs.writeFileSync(p.filePath, p.after, 'utf8');
268
+ };
269
+ const engine = historyEngines.find(name => name === p.engine);
270
+ if (!engine || p.kind !== 'instruction' || options.resetting) {
271
+ write();
272
+ continue;
273
+ }
274
+ const trigger = options.undo ? 'init-undo' : 'init';
275
+ const original = originalInstructions.get(p) ?? null;
276
+ const verifyPlan = () => {
277
+ const current = instructionBytes(p.filePath);
278
+ if (original !== current && (original === null || current === null || !original.equals(current)))
279
+ throw new Error('Instruction file changed. Re-run init: ' + p.filePath);
280
+ };
281
+ let entered = false;
282
+ try {
283
+ withHistoryLock(homeDir, () => {
284
+ entered = true;
285
+ const keep = retention ??= historyKeep(config);
286
+ const snapshot = (promote) => {
287
+ try {
288
+ const history = new InstructionHistory(homeDir, engine, userHome);
289
+ if (!promote)
290
+ history.recoverRestore(history.live());
291
+ history.snapshot(trigger, keep, promote);
292
+ }
293
+ catch (e) {
294
+ historyErrors.add(String(e));
295
+ }
296
+ };
297
+ verifyPlan();
298
+ snapshot(false);
299
+ verifyPlan();
300
+ write();
301
+ snapshot(true);
302
+ });
303
+ }
304
+ catch (e) {
305
+ if (entered)
306
+ throw e;
307
+ historyErrors.add(String(e));
308
+ verifyPlan();
309
+ write();
216
310
  }
217
- fs.writeFileSync(p.filePath, p.after, 'utf8');
218
311
  }
312
+ if (historyErrors.size)
313
+ console.error('Instruction history: ' + [...historyErrors].join('\n'));
219
314
  }
220
315
  return {
221
316
  plans,
@@ -224,6 +319,13 @@ export function planOrApplyInit(config, options = {}) {
224
319
  projectHint: options.projectHint ? PROJECT_HINT_LINE : undefined,
225
320
  };
226
321
  }
322
+ function planAction(changed, undo, hadEntry) {
323
+ if (!changed)
324
+ return 'unchanged';
325
+ if (undo)
326
+ return 'removed';
327
+ return hadEntry ? 'updated' : 'added';
328
+ }
227
329
  export function formatUnifiedDiff(plan) {
228
330
  const beforeLines = (plan.before ?? '').split('\n');
229
331
  const afterLines = plan.after.split('\n');
@@ -248,7 +350,8 @@ export function formatPlanBeforeAfter(plan, useColor = shouldUseColor()) {
248
350
  lines.push(`${c.bold(c.cyan(`[${plan.engine}]`, useColor), useColor)} ${c.bold(plan.kind, useColor)} — ${plan.filePath}`);
249
351
  lines.push(c.dim(hr('─', 64), useColor));
250
352
  if (!plan.changed) {
251
- lines.push(c.dim(' (no changes)', useColor));
353
+ const present = (plan.before ?? '').includes(plan.kind === 'instruction' ? BLOCK_START : 'faber-memory');
354
+ lines.push(c.dim(present ? ' (no changes: the faber-memory part is already in place)' : ' (no changes)', useColor));
252
355
  return lines.join('\n');
253
356
  }
254
357
  const beforeLines = (plan.before ?? '').split('\n');
@@ -260,7 +363,7 @@ export function formatPlanBeforeAfter(plan, useColor = shouldUseColor()) {
260
363
  lines.push(c.dim(' (file does not exist yet)', useColor));
261
364
  }
262
365
  else if (removed.length === 0) {
263
- lines.push(c.dim(' (existing content kept as-is)', useColor));
366
+ lines.push(c.dim(' (no lines removed)', useColor));
264
367
  }
265
368
  else {
266
369
  for (const l of removed) {
@@ -270,12 +373,48 @@ export function formatPlanBeforeAfter(plan, useColor = shouldUseColor()) {
270
373
  lines.push('');
271
374
  lines.push(c.bold(c.green('After:', useColor), useColor));
272
375
  if (added.length === 0) {
273
- lines.push(c.dim(' (removed faber-memory block/entry; remaining file preserved)', useColor));
376
+ lines.push(c.dim(' (no lines added)', useColor));
274
377
  }
275
378
  else {
276
379
  for (const l of added) {
277
380
  lines.push(c.green(` + ${l}`, useColor));
278
381
  }
279
382
  }
383
+ if (plan.backupPath) {
384
+ lines.push('');
385
+ lines.push(c.dim(`Backup: ${plan.backupPath}`, useColor));
386
+ }
280
387
  return lines.join('\n');
281
388
  }
389
+ const SUMMARY_TEXT = {
390
+ apply: { connect: 'connected', update: 'updated', same: 'already connected, nothing changed' },
391
+ preview: {
392
+ connect: 'would be connected',
393
+ update: 'would be updated',
394
+ same: 'already connected, nothing to change',
395
+ },
396
+ undo: { connect: 'disconnected', update: 'disconnected', same: 'was not connected' },
397
+ };
398
+ /** One plain line per assistant: what init did (or would do) there. */
399
+ export function formatInitSummary(plans, mode, useColor = shouldUseColor()) {
400
+ const specs = getEngineSpecs();
401
+ const engines = [...new Set(plans.map((p) => p.engine))];
402
+ if (engines.length === 0)
403
+ return c.dim(' No assistants found to connect.', useColor);
404
+ const width = Math.max(...engines.map((e) => (specs[e]?.label ?? e).length)) + 2;
405
+ return engines
406
+ .map((engine) => {
407
+ const mine = plans.filter((p) => p.engine === engine);
408
+ const actions = mine.map((p) => p.action ?? (p.changed ? 'updated' : 'unchanged'));
409
+ const key = actions.every((a) => a === 'unchanged')
410
+ ? 'same'
411
+ : actions.some((a) => a === 'added')
412
+ ? 'connect'
413
+ : 'update';
414
+ const label = (specs[engine]?.label ?? engine).padEnd(width);
415
+ const toolsOnly = specs[engine]?.gap && mode !== 'undo' ? ' (memory tools only)' : '';
416
+ const mark = key === 'same' ? c.dim('·', useColor) : c.green('✓', useColor);
417
+ return ` ${mark} ${c.bold(label, useColor)}${SUMMARY_TEXT[mode][key]}${toolsOnly}`;
418
+ })
419
+ .join('\n');
420
+ }
@@ -0,0 +1,45 @@
1
+ import type { UserConfig } from './types.js';
2
+ export declare const engines: readonly ["claude-code", "antigravity"];
3
+ export type HistoryEngine = (typeof engines)[number];
4
+ export type Trigger = 'server-start' | 'restore' | 'accept' | 'init' | 'init-undo';
5
+ export declare function historyKeep(config: UserConfig): number;
6
+ export declare function withHistoryLock<T>(home: string, work: () => T): T;
7
+ interface Metadata {
8
+ size: number;
9
+ hash: string | null;
10
+ block: boolean;
11
+ }
12
+ interface Version extends Metadata {
13
+ id: string;
14
+ time: number;
15
+ trigger: Trigger | 'unknown';
16
+ }
17
+ export interface Live extends Metadata {
18
+ bytes: Buffer | null;
19
+ destination: string;
20
+ }
21
+ export declare class InstructionHistory {
22
+ readonly engine: HistoryEngine;
23
+ readonly file: string;
24
+ readonly dir: string;
25
+ rows: Version[];
26
+ baseline?: Version;
27
+ private rebuild;
28
+ constructor(home: string, engine: HistoryEngine, userHome?: string);
29
+ live(): Live;
30
+ reason(live: Metadata): string | undefined;
31
+ warning(live: Live): string | undefined;
32
+ bytes(id: string): Buffer | null;
33
+ revision(): string;
34
+ record(live: Live, trigger: Trigger): Version | undefined;
35
+ finish(base: Version | undefined, keep: number): void;
36
+ snapshot(trigger: Trigger, keep: number, promote?: boolean): string | undefined;
37
+ private restoreBytes;
38
+ private get pendingRestorePath();
39
+ private readPendingRestore;
40
+ private publishRestore;
41
+ restore(target: Version, live: Live, bytes: Buffer, keep: number): void;
42
+ recoverRestore(live: Live): boolean;
43
+ }
44
+ export declare function startupHistory(home: string, config: UserConfig): string | undefined;
45
+ export {};