@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/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to `@fabersep/memory`. Versions follow [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.6.0](https://github.com/fabersep/memory/compare/v0.5.2...v0.6.0) (2026-12-04)
6
+
7
+
8
+ ### Features
9
+
10
+ * keep and restore local instruction file history ([#27](https://github.com/fabersep/memory/issues/27)) ([f9b39da](https://github.com/fabersep/memory/commit/f9b39dafd79c90a2217ac4d1121b59f2056dc827))
11
+
12
+ ## [0.5.2](https://github.com/fabersep/memory/compare/v0.5.1...v0.5.2) (2026-12-03)
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * connect Codex in init and print a plain summary instead of Before/After ([#25](https://github.com/fabersep/memory/issues/25)) ([72245ad](https://github.com/fabersep/memory/commit/72245addb45fcd2ab5729f961f6eab7b9275998b))
18
+
5
19
  ## [0.5.1](https://github.com/fabersep/memory/compare/v0.5.0...v0.5.1) (2026-12-03)
6
20
 
7
21
 
package/README.md CHANGED
@@ -22,15 +22,18 @@ FaberSEP Memory started from a common setup: several AI tools on a workstation,
22
22
 
23
23
  | | Built-in agent memory | FaberSEP Memory |
24
24
  | :--- | :--- | :--- |
25
- | **Who can read it** | The one tool that wrote it | Claude Code, Antigravity, Cursor, Claude Desktop, Codex (manual setup) |
25
+ | **Who can read it** | The one tool that wrote it | Claude Code, Antigravity, Codex, Cursor, Claude Desktop |
26
26
  | **Where it lives** | One machine | A Git repo you can clone to any machine, a server included (read-only there) |
27
27
  | **Who writes it** | The agent, silently | What you tell it to remember is saved at once; what the agent decides on its own waits for your approval |
28
28
  | **History and undo** | Usually none | Every change is a Git commit |
29
+ | **Recover an overwritten instruction file** | Depends on the tool | Restore a saved local version with one command |
29
30
  | **Team use** | Not shareable | Optional private team repo |
30
31
  | **Context cost** | Grows with the file | A fixed-size index (max ~1,500 tokens); details fetched on demand |
31
32
 
32
33
  If you use one tool on one machine and are happy with its memory, you don't need this.
33
34
 
35
+ Suppose an agent overwrites your global Claude instructions. At the next session, FaberSEP Memory tells the agent to let you know. It kept the earlier file on your machine. Run `faber-memory restore claude-code`, review the changes, and confirm to bring it back.
36
+
34
37
  ## What `init` changes, and how your agent finds it
35
38
 
36
39
  There is **no background service and no account**. `faber-memory` is a CLI plus a small MCP server that your AI tool starts by itself (stdio) when a chat opens.
@@ -56,9 +59,9 @@ There is **no background service and no account**. `faber-memory` is a CLI plus
56
59
  | Antigravity | `~/.gemini/GEMINI.md` | `~/.gemini/config/mcp_config.json` |
57
60
  | Cursor | none | `~/.cursor/mcp.json` |
58
61
  | Claude Desktop | none | `claude_desktop_config.json` (`--engine claude-desktop`) |
59
- | Codex | none | add the MCP server by hand |
62
+ | Codex (CLI and app) | `~/.codex/AGENTS.md` | `~/.codex/config.toml` |
60
63
 
61
- Every touched file gets a `.bak` backup. `init --preview` shows the exact diff first, and `init --undo` removes the block and the MCP entry and leaves your notes alone. Details: [Connecting engines](docs/guide.md#connecting-engines-init).
64
+ Every touched file gets a `.bak` backup. `init` prints one line per tool; `init --details` shows each file change, `init --preview` shows what would change first, and `init --undo` removes the block and the MCP entry and leaves your notes alone. Details: [Connecting engines](docs/guide.md#connecting-engines-init).
62
65
 
63
66
  ## Get started
64
67
 
package/dist/src/cli.js CHANGED
@@ -1,4 +1,6 @@
1
1
  #!/usr/bin/env node
2
+ import { runHistoryCommand } from './history-command.js';
3
+ import { withHistoryLock } from './instruction-history.js';
2
4
  import * as fs from 'node:fs';
3
5
  import * as path from 'node:path';
4
6
  import * as readline from 'node:readline';
@@ -8,7 +10,7 @@ import { countRecentDirectSaves, DIRECT_SAVE_RECENT_DAYS, isDirectUserSaveOn, un
8
10
  import { formatDoctorReport, runDoctor } from './doctor.js';
9
11
  import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, gitSync, isGitRepo, } from './git.js';
10
12
  import { runImport } from './importer.js';
11
- import { formatPlanBeforeAfter, planOrApplyInit } from './init.js';
13
+ import { formatInitSummary, formatPlanBeforeAfter, planOrApplyInit, } from './init.js';
12
14
  import { FaberMemoryMcpServer } from './mcp.js';
13
15
  import { approveProposalsBatch, findProposalById, reconcileAwaitingCommitProposals, rejectProposal, saveProposal, } from './proposals.js';
14
16
  import { buildShareableBenchmark, computeStats, formatShareableMarkdown, formatStatsReport, validateDaysArg, } from './stats.js';
@@ -20,9 +22,9 @@ import { c, hr, inferErrorAnchor, normalizeTeamUrl, troubleshootingLink, } from
20
22
  import { openBrowserBestEffort, startWebServer, validateIdleTimeoutArg, validatePortArg, } from './web.js';
21
23
  // Flags that never take a value, so `init --preview ~/notes` keeps ~/notes as a positional.
22
24
  const BOOLEAN_FLAGS = new Set([
23
- 'apply', 'undo', 'preview', 'dry-run', 'check', 'json', 'strict', 'cache', 'share', 'yes',
25
+ 'apply', 'undo', 'preview', 'dry-run', 'details', 'check', 'json', 'strict', 'cache', 'share', 'yes',
24
26
  'all', 'approve', 'approve-all', 'split-headings', 'normalize-paths', 'project-hint',
25
- 'include-personal-repo', 'help', 'allow-public', 'web', 'no-open',
27
+ 'include-personal-repo', 'clear', 'accept', 'help', 'allow-public', 'web', 'no-open',
26
28
  ]);
27
29
  function parseFlags(args) {
28
30
  const positional = [];
@@ -140,6 +142,8 @@ async function main() {
140
142
  printHelp();
141
143
  return 0;
142
144
  }
145
+ if (cmd === 'history' || cmd === 'restore')
146
+ return runHistoryCommand(cmd, positional, flags, homeDir, promptLine);
143
147
  if (cmd === 'serve') {
144
148
  const server = new FaberMemoryMcpServer({ homeDir, cwd: process.cwd() });
145
149
  server.serveStdio();
@@ -481,15 +485,15 @@ async function main() {
481
485
  return 0;
482
486
  }
483
487
  }
484
- try {
485
- planOrApplyInit(config, { undo: true, homeDir });
486
- }
487
- catch {
488
- // Best-effort undo even if config is partial
489
- }
490
- if (fs.existsSync(homeDir)) {
488
+ withHistoryLock(homeDir, () => {
489
+ try {
490
+ planOrApplyInit(config, { undo: true, homeDir, resetting: true });
491
+ }
492
+ catch {
493
+ // Best-effort undo even if config is partial.
494
+ }
491
495
  fs.rmSync(homeDir, { recursive: true, force: true });
492
- }
496
+ });
493
497
  if (includePersonal && personalPath && fs.existsSync(personalPath)) {
494
498
  fs.rmSync(personalPath, { recursive: true, force: true });
495
499
  }
@@ -908,26 +912,48 @@ async function main() {
908
912
  projectHint,
909
913
  homeDir,
910
914
  });
911
- for (const n of res.notes)
912
- console.log(c.yellow(n));
913
- for (const p of res.plans) {
914
- console.log(formatPlanBeforeAfter(p));
915
+ // Default output is one plain line per assistant; --details adds the
916
+ // file-by-file Before/After view for those who want it.
917
+ const details = Boolean(flags.details);
918
+ const mode = undo ? 'undo' : preview ? 'preview' : 'apply';
919
+ const heading = mode === 'undo'
920
+ ? 'Disconnecting memory from your assistants:'
921
+ : mode === 'preview'
922
+ ? 'Preview: nothing was written.'
923
+ : 'Memory is connected to your assistants:';
924
+ console.log(c.bold(heading));
925
+ console.log(formatInitSummary(res.plans, mode));
926
+ if (details) {
927
+ for (const n of res.notes)
928
+ console.log(c.yellow(n));
929
+ for (const p of res.plans)
930
+ console.log(formatPlanBeforeAfter(p));
931
+ }
932
+ if (res.projectHint) {
933
+ console.log(`\nProject hint: ${res.projectHint}`);
915
934
  }
935
+ console.log('');
916
936
  if (undo) {
917
- console.log(c.cyan('\nRemoved agent wiring only. Your memory repos and pending pre-memory proposals were kept intact. (Use "faber-memory reset" to wipe local state.)'));
937
+ console.log('Your memories and pending proposals were kept. (Use "faber-memory reset" to wipe local state.)');
918
938
  if (res.backups.length > 0) {
919
- console.log(c.dim(`Backup files preserved (not auto-restored): ${res.backups.join(', ')}`));
939
+ console.log(c.dim(`Backups kept, not restored: ${res.backups.join(', ')}`));
920
940
  }
921
941
  }
922
- if (res.projectHint) {
923
- console.log(`Project hint: ${res.projectHint}`);
942
+ else if (preview) {
943
+ console.log(`Run ${c.cyan('faber-memory init')} to apply.`);
944
+ }
945
+ else {
946
+ const changed = res.plans.some((p) => p.changed);
947
+ console.log(changed
948
+ ? 'Start a new chat in your assistant to use memory.'
949
+ : 'Everything was already set up.');
924
950
  }
925
- if (preview) {
926
- console.log(c.yellow('\nPreview only. Run "faber-memory init" to write these changes.'));
951
+ if (!details) {
952
+ const again = undo ? 'faber-memory init --undo --details' : preview ? 'faber-memory init --preview --details' : 'faber-memory init --details';
953
+ console.log(c.dim(`See which files are touched and how: ${again}`));
927
954
  }
928
- else if (apply) {
929
- const wired = [...new Set(res.plans.map((p) => p.engine))];
930
- console.log(c.green(`\nConnected: ${wired.join(', ') || 'nothing to change'}. Backups are saved as .bak; undo any time with "faber-memory init --undo". Start a new chat in your assistant to use memory.`));
955
+ if (!undo && !preview) {
956
+ console.log(c.dim('Undo any time: faber-memory init --undo'));
931
957
  }
932
958
  return 0;
933
959
  }
@@ -994,7 +1020,7 @@ Commands:
994
1020
  remote add <git-url> [--allow-public] | remote remove
995
1021
  push
996
1022
  config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | set-push-mode <ask|auto|never> | set-direct-save <on|off> | unset <personal|team>]
997
- init [folder] [--remote <git-url>] [--preview | --undo] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
1023
+ init [folder] [--remote <git-url>] [--preview | --undo] [--details] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
998
1024
  compile [--check] [--repo <dir>]
999
1025
  sync [--timeout <ms>]
1000
1026
  status
@@ -1005,6 +1031,8 @@ Commands:
1005
1031
  approve <proposal-id> [...] [--mode auto|pr] [--yes]
1006
1032
  reject <proposal-id> | reject --all [--yes]
1007
1033
  undo <entry-id> [--yes] (undo a memory saved directly on your word)
1034
+ history [engine] [--show <n> | --diff <n> | --accept | --clear] [--json]
1035
+ restore <engine> [--version <n>] [--yes]
1008
1036
  reset [--include-personal-repo] [--yes]
1009
1037
  import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]
1010
1038
  serve
@@ -68,6 +68,7 @@ export function loadConfig(homeDir = getHomeDir()) {
68
68
  : DEFAULT_SIMILARITY_THRESHOLD,
69
69
  ...(typeof raw.similarityHintFloor === 'number' ? { similarityHintFloor: raw.similarityHintFloor } : {}),
70
70
  ...(typeof raw.directUserSave === 'boolean' ? { directUserSave: raw.directUserSave } : {}),
71
+ ...(raw.history !== undefined ? { history: raw.history } : {}),
71
72
  roots: raw.roots || {},
72
73
  };
73
74
  }
@@ -1,3 +1,4 @@
1
+ import { engines, InstructionHistory } from './instruction-history.js';
1
2
  import * as crypto from 'node:crypto';
2
3
  import * as fs from 'node:fs';
3
4
  import { estimateTokens, renderGlobalL0 } from './compiler.js';
@@ -366,6 +367,23 @@ export function runDoctor(options = {}) {
366
367
  else {
367
368
  wiringDetails.push(`Wired engines: ${wiredEngines.join(', ')}.`);
368
369
  }
370
+ for (const engine of engines) {
371
+ try {
372
+ const history = new InstructionHistory(homeDir, engine, userHome);
373
+ if (!history.baseline)
374
+ continue;
375
+ const warning = history.warning(history.live());
376
+ if (warning) {
377
+ wiringDetails.push(warning);
378
+ wiringStatus = 'FAIL';
379
+ }
380
+ }
381
+ catch (error) {
382
+ wiringDetails.push('Cannot inspect instruction history: ' + String(error));
383
+ if (wiringStatus === 'PASS')
384
+ wiringStatus = 'WARN';
385
+ }
386
+ }
369
387
  checks.push({
370
388
  id: 'engine-wiring',
371
389
  name: 'Engine wiring',
@@ -0,0 +1,17 @@
1
+ export declare const BLOCK_START = "<!-- faber-memory:start -->";
2
+ export declare const BLOCK_END = "<!-- faber-memory:end -->";
3
+ 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). 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.";
4
+ export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
5
+ export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
6
+ export interface EngineSpec {
7
+ name: EngineName;
8
+ label: string;
9
+ verifiedImport: boolean;
10
+ gap: boolean;
11
+ instructionFile?: (userHome: string) => string;
12
+ mcpConfigFile?: (userHome: string) => string;
13
+ mcpFormat?: 'json' | 'toml';
14
+ renderBlock?: (compiledL0Path: string) => string;
15
+ }
16
+ export declare function getEngineSpecs(): Record<EngineName, EngineSpec>;
17
+ export declare function getUserHome(): string;
@@ -0,0 +1,63 @@
1
+ import * as os from 'node:os';
2
+ import * as path from 'node:path';
3
+ export const BLOCK_START = '<!-- faber-memory:start -->';
4
+ export const BLOCK_END = '<!-- faber-memory:end -->';
5
+ 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.';
6
+ export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
7
+ function renderReadInstructionBlock(l0Path) {
8
+ return `${BLOCK_START}\nAt session start, read ${l0Path} (global L0 memory).\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`;
9
+ }
10
+ export function getEngineSpecs() {
11
+ return {
12
+ 'claude-code': {
13
+ name: 'claude-code',
14
+ label: '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
+ label: 'Claude Desktop',
24
+ verifiedImport: false,
25
+ gap: false,
26
+ mcpConfigFile: (home) => process.platform === 'darwin'
27
+ ? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
28
+ : path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
29
+ },
30
+ antigravity: {
31
+ name: 'antigravity',
32
+ label: 'Antigravity',
33
+ verifiedImport: true,
34
+ gap: false,
35
+ instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
36
+ mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
37
+ renderBlock: renderReadInstructionBlock,
38
+ },
39
+ cursor: {
40
+ name: 'cursor',
41
+ label: 'Cursor',
42
+ verifiedImport: false,
43
+ gap: true,
44
+ mcpConfigFile: (home) => path.join(home, '.cursor', 'mcp.json'),
45
+ },
46
+ // Codex CLI and the Codex desktop app share ~/.codex: global AGENTS.md
47
+ // (no @-import, so an explicit read instruction like Antigravity) and
48
+ // MCP servers in config.toml.
49
+ codex: {
50
+ name: 'codex',
51
+ label: 'Codex',
52
+ verifiedImport: false,
53
+ gap: false,
54
+ instructionFile: (home) => path.join(home, '.codex', 'AGENTS.md'),
55
+ mcpConfigFile: (home) => path.join(home, '.codex', 'config.toml'),
56
+ mcpFormat: 'toml',
57
+ renderBlock: renderReadInstructionBlock,
58
+ },
59
+ };
60
+ }
61
+ export function getUserHome() {
62
+ return process.env.FABER_USER_HOME || os.homedir();
63
+ }
@@ -0,0 +1,3 @@
1
+ type Flags = Record<string, string | boolean>;
2
+ export declare function runHistoryCommand(cmd: 'history' | 'restore', args: string[], flags: Flags, home: string, prompt: (question: string) => Promise<string>): Promise<number>;
3
+ export {};
@@ -0,0 +1,178 @@
1
+ import { createHash } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import { loadConfig } from './config.js';
4
+ import { engines, historyKeep, InstructionHistory, withHistoryLock } from './instruction-history.js';
5
+ function versionNumber(value) {
6
+ if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value))
7
+ throw new Error('Expected a positive version number.');
8
+ return Number(value);
9
+ }
10
+ function unifiedDiff(file, before, after) {
11
+ if (before === after || (before && after && before.equals(after)))
12
+ return '';
13
+ const lines = (data) => data?.toString().match(/[^\n]*\n|[^\n]+$/g) ?? [];
14
+ const a = lines(before), b = lines(after);
15
+ const render = (line, prefix) => prefix + line + (line.endsWith('\n') ? '' : '\n\\n');
16
+ const header = '--- ' + (before === null ? '/dev/null' : file) + '\n+++ ' + (after === null ? '/dev/null' : file) + '\n';
17
+ if (!a.length && !b.length)
18
+ return header;
19
+ let prefix = 0, suffix = 0;
20
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix])
21
+ prefix++;
22
+ while (suffix < Math.min(a.length, b.length) - prefix &&
23
+ a[a.length - 1 - suffix] === b[b.length - 1 - suffix])
24
+ suffix++;
25
+ const start = Math.max(0, prefix - 3);
26
+ const endA = a.length - suffix, endB = b.length - suffix;
27
+ const context = Math.min(3, suffix);
28
+ const range = (count) => (count ? start + 1 : start) + ',' + count;
29
+ const hunk = '@@ -' + range(endA + context - start) + ' +' + range(endB + context - start) + ' @@\n';
30
+ return (header +
31
+ hunk +
32
+ a
33
+ .slice(start, prefix)
34
+ .map((line) => render(line, ' '))
35
+ .join('') +
36
+ a
37
+ .slice(prefix, endA)
38
+ .map((line) => render(line, '-'))
39
+ .join('') +
40
+ b
41
+ .slice(prefix, endB)
42
+ .map((line) => render(line, '+'))
43
+ .join('') +
44
+ a
45
+ .slice(endA, endA + context)
46
+ .map((line) => render(line, ' '))
47
+ .join(''));
48
+ }
49
+ export async function runHistoryCommand(cmd, args, flags, home, prompt) {
50
+ if (flags.help) {
51
+ console.log('faber-memory history [engine] [--show <n> | --diff <n> | --accept | --clear [--yes]] [--json]\n' +
52
+ 'faber-memory restore <engine> [--version <n>] [--yes]\n' +
53
+ 'Versions are taken at session start, around init and undo, before restore, and on accept. ' +
54
+ 'Of two changes between these moments only the later one is kept.');
55
+ return 0;
56
+ }
57
+ const actions = ['show', 'diff', 'accept', 'clear'].filter((k) => k in flags);
58
+ const allowed = cmd === 'restore' ? ['version', 'yes'] : ['show', 'diff', 'accept', 'clear', 'json', 'yes'];
59
+ if (Object.keys(flags).some((k) => !allowed.includes(k)) || actions.length > 1 || args.length > 1)
60
+ throw new Error('Invalid options. Run faber-memory ' + cmd + ' --help.');
61
+ const confirm = async () => {
62
+ if (flags.yes === true)
63
+ return;
64
+ if (!process.stdin.isTTY || !/^y(es)?$/i.test(await prompt('Continue? [y/N] ')))
65
+ throw new Error('Confirmation needed. Use --yes to confirm.');
66
+ };
67
+ if (!args.length && cmd === 'history' && !actions.length) {
68
+ const overview = engines.map((engine) => {
69
+ const h = new InstructionHistory(home, engine);
70
+ return { engine, path: h.file, versions: h.rows.length, damaged: Boolean(h.reason(h.live())) };
71
+ });
72
+ console.log(flags.json
73
+ ? JSON.stringify(overview)
74
+ : overview
75
+ .map((r) => r.engine +
76
+ ' ' +
77
+ r.path +
78
+ ' versions=' +
79
+ r.versions +
80
+ ' damaged=' +
81
+ (r.damaged ? 'yes' : 'no'))
82
+ .join('\n'));
83
+ return 0;
84
+ }
85
+ const engine = engines.find((e) => e === args[0]);
86
+ if (!engine)
87
+ throw new Error('Engines with tracked instruction files: ' + engines.join(', '));
88
+ const read = () => new InstructionHistory(home, engine);
89
+ if (flags.clear) {
90
+ console.log('Clear instruction history for ' + engine + '?');
91
+ await confirm();
92
+ withHistoryLock(home, () => fs.rmSync(read().dir, { recursive: true, force: true }));
93
+ return 0;
94
+ }
95
+ if (flags.accept) {
96
+ withHistoryLock(home, () => {
97
+ const h = read();
98
+ const live = h.live();
99
+ if (!h.rows.length && live.hash === null)
100
+ throw new Error('No instruction file to accept.');
101
+ h.recoverRestore(live);
102
+ h.snapshot('accept', historyKeep(loadConfig(home)), true);
103
+ });
104
+ return 0;
105
+ }
106
+ const h = read();
107
+ if (cmd === 'restore') {
108
+ if (!h.rows.length)
109
+ throw new Error('No stored versions of ' + h.file + '. Nothing to restore.');
110
+ const target = flags.version === undefined ? h.baseline : h.rows[versionNumber(flags.version) - 1];
111
+ if (!target || target.hash === null)
112
+ throw new Error('No restorable content at this version. Select a stored file with --version <n>.');
113
+ const bytes = h.bytes(target.id);
114
+ if (createHash('sha256').update(bytes).digest('hex') !== target.hash)
115
+ throw new Error('The selected history file has changed on disk. Restore cancelled.');
116
+ const observed = h.live();
117
+ if (observed.bytes === null && observed.hash !== null)
118
+ throw new Error(h.file + ' exceeds 1 MB.');
119
+ process.stdout.write(unifiedDiff(h.file, observed.bytes, bytes));
120
+ await confirm();
121
+ withHistoryLock(home, () => {
122
+ const current = read(), live = current.live();
123
+ if (current.revision() !== h.revision() ||
124
+ observed.destination !== live.destination ||
125
+ observed.hash !== live.hash ||
126
+ !current.bytes(target.id)?.equals(bytes))
127
+ throw new Error('Instruction file or history changed. Re-run restore.');
128
+ current.recoverRestore(live);
129
+ current.restore(target, live, bytes, historyKeep(loadConfig(home)));
130
+ });
131
+ console.log('Restored ' + h.file + '. Applies from the next session.');
132
+ return 0;
133
+ }
134
+ if (flags.show !== undefined || flags.diff !== undefined) {
135
+ const row = h.rows[versionNumber(flags.show ?? flags.diff) - 1];
136
+ if (!row)
137
+ throw new Error('Version does not exist.');
138
+ const bytes = h.bytes(row.id);
139
+ let output;
140
+ if (flags.show !== undefined)
141
+ output = bytes ?? 'File was deleted at ' + new Date(row.time).toISOString() + '\n';
142
+ else {
143
+ const live = h.live();
144
+ if (live.size && live.bytes === null)
145
+ throw new Error(h.file + ' exceeds 1 MB.');
146
+ output = unifiedDiff(h.file, bytes, live.bytes);
147
+ }
148
+ process.stdout.write(flags.json ? JSON.stringify(output.toString()) + '\n' : output);
149
+ return 0;
150
+ }
151
+ const rows = h.rows.map((r, i) => ({
152
+ number: i + 1,
153
+ time: new Date(r.time).toLocaleString(),
154
+ size: r.size,
155
+ block: r.block,
156
+ trigger: r.trigger,
157
+ deleted: r.hash === null,
158
+ baseline: r.id === h.baseline?.id,
159
+ damaged: Boolean(h.reason(r)),
160
+ reason: h.reason(r),
161
+ }));
162
+ console.log(flags.json
163
+ ? JSON.stringify(rows)
164
+ : rows
165
+ .map((r) => [
166
+ r.number,
167
+ r.time,
168
+ r.deleted ? 'deleted' : r.size + ' B',
169
+ 'block=' + (r.block ? 'yes' : 'no'),
170
+ r.trigger,
171
+ r.baseline && 'baseline',
172
+ r.damaged && 'damaged (' + r.reason + ')',
173
+ ]
174
+ .filter(Boolean)
175
+ .join(' '))
176
+ .join('\n'));
177
+ return 0;
178
+ }
@@ -1,18 +1,7 @@
1
1
  import { UserConfig } from './types.js';
2
- export declare const BLOCK_START = "<!-- faber-memory:start -->";
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). 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.";
5
- export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
6
- export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
7
- export interface EngineSpec {
8
- name: EngineName;
9
- verifiedImport: boolean;
10
- gap: boolean;
11
- instructionFile?: (userHome: string) => string;
12
- mcpConfigFile?: (userHome: string) => string;
13
- renderBlock?: (compiledL0Path: string) => string;
14
- }
15
- export declare function getEngineSpecs(): Record<EngineName, EngineSpec>;
2
+ import { type EngineName } from './engines.js';
3
+ export * from './engines.js';
4
+ export type PlanAction = 'added' | 'updated' | 'unchanged' | 'removed';
16
5
  export interface FilePlan {
17
6
  filePath: string;
18
7
  kind: 'instruction' | 'mcp-config';
@@ -20,6 +9,8 @@ export interface FilePlan {
20
9
  before: string | null;
21
10
  after: string;
22
11
  changed: boolean;
12
+ /** What init does to faber-memory's part of the file; omitted plans count as added/updated by `changed`. */
13
+ action?: PlanAction;
23
14
  backupPath?: string;
24
15
  }
25
16
  export interface InitPlanResult {
@@ -28,9 +19,12 @@ export interface InitPlanResult {
28
19
  notes: string[];
29
20
  projectHint?: string;
30
21
  }
31
- export declare function getUserHome(): string;
32
22
  export declare function upsertManagedBlock(existing: string, block: string): string;
33
23
  export declare function removeManagedBlock(existing: string): string;
24
+ export declare function renderCodexTomlTable(): string;
25
+ export declare function hasCodexTomlEntry(raw: string | null): boolean;
26
+ export declare function upsertMcpToml(existingRaw: string | null): string;
27
+ export declare function removeMcpToml(existingRaw: string): string;
34
28
  export declare function detectTargetEngines(userHome: string, requested?: EngineName[]): EngineName[];
35
29
  export declare function planOrApplyInit(config: UserConfig, options?: {
36
30
  apply?: boolean;
@@ -39,6 +33,10 @@ export declare function planOrApplyInit(config: UserConfig, options?: {
39
33
  projectHint?: boolean;
40
34
  homeDir?: string;
41
35
  userHome?: string;
36
+ resetting?: boolean;
42
37
  }): InitPlanResult;
43
38
  export declare function formatUnifiedDiff(plan: FilePlan): string;
44
39
  export declare function formatPlanBeforeAfter(plan: FilePlan, useColor?: boolean): string;
40
+ export type InitMode = 'apply' | 'preview' | 'undo';
41
+ /** One plain line per assistant: what init did (or would do) there. */
42
+ export declare function formatInitSummary(plans: FilePlan[], mode: InitMode, useColor?: boolean): string;