@fabersep/memory 0.5.2 → 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 +7 -0
- package/README.md +3 -0
- package/dist/src/cli.js +15 -9
- package/dist/src/config.js +1 -0
- package/dist/src/doctor.js +18 -0
- package/dist/src/engines.d.ts +17 -0
- package/dist/src/engines.js +63 -0
- package/dist/src/history-command.d.ts +3 -0
- package/dist/src/history-command.js +178 -0
- package/dist/src/init.d.ts +3 -17
- package/dist/src/init.js +72 -71
- package/dist/src/instruction-history.d.ts +45 -0
- package/dist/src/instruction-history.js +507 -0
- package/dist/src/mcp.d.ts +3 -0
- package/dist/src/mcp.js +14 -2
- package/dist/src/types.d.ts +3 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
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
|
+
|
|
5
12
|
## [0.5.2](https://github.com/fabersep/memory/compare/v0.5.1...v0.5.2) (2026-12-03)
|
|
6
13
|
|
|
7
14
|
|
package/README.md
CHANGED
|
@@ -26,11 +26,14 @@ FaberSEP Memory started from a common setup: several AI tools on a workstation,
|
|
|
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.
|
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';
|
|
@@ -22,7 +24,7 @@ import { openBrowserBestEffort, startWebServer, validateIdleTimeoutArg, validate
|
|
|
22
24
|
const BOOLEAN_FLAGS = new Set([
|
|
23
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
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
}
|
|
@@ -1027,6 +1031,8 @@ Commands:
|
|
|
1027
1031
|
approve <proposal-id> [...] [--mode auto|pr] [--yes]
|
|
1028
1032
|
reject <proposal-id> | reject --all [--yes]
|
|
1029
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]
|
|
1030
1036
|
reset [--include-personal-repo] [--yes]
|
|
1031
1037
|
import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]
|
|
1032
1038
|
serve
|
package/dist/src/config.js
CHANGED
|
@@ -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
|
}
|
package/dist/src/doctor.js
CHANGED
|
@@ -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,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
|
+
}
|
package/dist/src/init.d.ts
CHANGED
|
@@ -1,20 +1,6 @@
|
|
|
1
1
|
import { UserConfig } from './types.js';
|
|
2
|
-
|
|
3
|
-
export
|
|
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
|
-
label: string;
|
|
10
|
-
verifiedImport: boolean;
|
|
11
|
-
gap: boolean;
|
|
12
|
-
instructionFile?: (userHome: string) => string;
|
|
13
|
-
mcpConfigFile?: (userHome: string) => string;
|
|
14
|
-
mcpFormat?: 'json' | 'toml';
|
|
15
|
-
renderBlock?: (compiledL0Path: string) => string;
|
|
16
|
-
}
|
|
17
|
-
export declare function getEngineSpecs(): Record<EngineName, EngineSpec>;
|
|
2
|
+
import { type EngineName } from './engines.js';
|
|
3
|
+
export * from './engines.js';
|
|
18
4
|
export type PlanAction = 'added' | 'updated' | 'unchanged' | 'removed';
|
|
19
5
|
export interface FilePlan {
|
|
20
6
|
filePath: string;
|
|
@@ -33,7 +19,6 @@ export interface InitPlanResult {
|
|
|
33
19
|
notes: string[];
|
|
34
20
|
projectHint?: string;
|
|
35
21
|
}
|
|
36
|
-
export declare function getUserHome(): string;
|
|
37
22
|
export declare function upsertManagedBlock(existing: string, block: string): string;
|
|
38
23
|
export declare function removeManagedBlock(existing: string): string;
|
|
39
24
|
export declare function renderCodexTomlTable(): string;
|
|
@@ -48,6 +33,7 @@ export declare function planOrApplyInit(config: UserConfig, options?: {
|
|
|
48
33
|
projectHint?: boolean;
|
|
49
34
|
homeDir?: string;
|
|
50
35
|
userHome?: string;
|
|
36
|
+
resetting?: boolean;
|
|
51
37
|
}): InitPlanResult;
|
|
52
38
|
export declare function formatUnifiedDiff(plan: FilePlan): string;
|
|
53
39
|
export declare function formatPlanBeforeAfter(plan: FilePlan, useColor?: boolean): string;
|
package/dist/src/init.js
CHANGED
|
@@ -1,69 +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
|
-
|
|
8
|
-
export
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
label: 'Claude Code',
|
|
19
|
-
verifiedImport: true,
|
|
20
|
-
gap: false,
|
|
21
|
-
instructionFile: (home) => path.join(home, '.claude', 'CLAUDE.md'),
|
|
22
|
-
mcpConfigFile: (home) => path.join(home, '.claude.json'),
|
|
23
|
-
renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
|
|
24
|
-
},
|
|
25
|
-
'claude-desktop': {
|
|
26
|
-
name: 'claude-desktop',
|
|
27
|
-
label: 'Claude Desktop',
|
|
28
|
-
verifiedImport: false,
|
|
29
|
-
gap: false,
|
|
30
|
-
mcpConfigFile: (home) => process.platform === 'darwin'
|
|
31
|
-
? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
|
|
32
|
-
: path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
|
|
33
|
-
},
|
|
34
|
-
antigravity: {
|
|
35
|
-
name: 'antigravity',
|
|
36
|
-
label: 'Antigravity',
|
|
37
|
-
verifiedImport: true,
|
|
38
|
-
gap: false,
|
|
39
|
-
instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
|
|
40
|
-
mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
|
|
41
|
-
renderBlock: renderReadInstructionBlock,
|
|
42
|
-
},
|
|
43
|
-
cursor: {
|
|
44
|
-
name: 'cursor',
|
|
45
|
-
label: 'Cursor',
|
|
46
|
-
verifiedImport: false,
|
|
47
|
-
gap: true,
|
|
48
|
-
mcpConfigFile: (home) => path.join(home, '.cursor', 'mcp.json'),
|
|
49
|
-
},
|
|
50
|
-
// Codex CLI and the Codex desktop app share ~/.codex: global AGENTS.md
|
|
51
|
-
// (no @-import, so an explicit read instruction like Antigravity) and
|
|
52
|
-
// MCP servers in config.toml.
|
|
53
|
-
codex: {
|
|
54
|
-
name: 'codex',
|
|
55
|
-
label: 'Codex',
|
|
56
|
-
verifiedImport: false,
|
|
57
|
-
gap: false,
|
|
58
|
-
instructionFile: (home) => path.join(home, '.codex', 'AGENTS.md'),
|
|
59
|
-
mcpConfigFile: (home) => path.join(home, '.codex', 'config.toml'),
|
|
60
|
-
mcpFormat: 'toml',
|
|
61
|
-
renderBlock: renderReadInstructionBlock,
|
|
62
|
-
},
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
export function getUserHome() {
|
|
66
|
-
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
|
+
}
|
|
67
18
|
}
|
|
68
19
|
export function upsertManagedBlock(existing, block) {
|
|
69
20
|
const escapedStart = escapeRegex(BLOCK_START);
|
|
@@ -221,6 +172,7 @@ export function planOrApplyInit(config, options = {}) {
|
|
|
221
172
|
const compiledL0Path = getCompiledL0Path(homeDir);
|
|
222
173
|
const notes = [];
|
|
223
174
|
const plans = [];
|
|
175
|
+
const originalInstructions = new Map();
|
|
224
176
|
const backups = [];
|
|
225
177
|
if (options.apply && !options.undo) {
|
|
226
178
|
// Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
|
|
@@ -238,8 +190,8 @@ export function planOrApplyInit(config, options = {}) {
|
|
|
238
190
|
}
|
|
239
191
|
if (spec.instructionFile && spec.renderBlock && !spec.gap) {
|
|
240
192
|
const filePath = spec.instructionFile(userHome);
|
|
241
|
-
const
|
|
242
|
-
const before =
|
|
193
|
+
const original = instructionBytes(filePath);
|
|
194
|
+
const before = original?.toString('utf8') ?? null;
|
|
243
195
|
const after = options.undo
|
|
244
196
|
? before !== null
|
|
245
197
|
? removeManagedBlock(before)
|
|
@@ -259,6 +211,7 @@ export function planOrApplyInit(config, options = {}) {
|
|
|
259
211
|
plan.backupPath = `${filePath}.bak`;
|
|
260
212
|
backups.push(`${filePath}.bak`);
|
|
261
213
|
}
|
|
214
|
+
originalInstructions.set(plan, original);
|
|
262
215
|
plans.push(plan);
|
|
263
216
|
}
|
|
264
217
|
if (spec.mcpConfigFile) {
|
|
@@ -294,22 +247,70 @@ export function planOrApplyInit(config, options = {}) {
|
|
|
294
247
|
}
|
|
295
248
|
}
|
|
296
249
|
if (options.apply || options.undo) {
|
|
250
|
+
const historyErrors = new Set();
|
|
251
|
+
let retention;
|
|
297
252
|
for (const p of plans) {
|
|
298
253
|
if (!p.changed)
|
|
299
254
|
continue;
|
|
300
255
|
if (options.undo && p.before === null)
|
|
301
256
|
continue;
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
fs.
|
|
307
|
-
|
|
308
|
-
|
|
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
|
+
}
|
|
309
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();
|
|
310
310
|
}
|
|
311
|
-
fs.writeFileSync(p.filePath, p.after, 'utf8');
|
|
312
311
|
}
|
|
312
|
+
if (historyErrors.size)
|
|
313
|
+
console.error('Instruction history: ' + [...historyErrors].join('\n'));
|
|
313
314
|
}
|
|
314
315
|
return {
|
|
315
316
|
plans,
|
|
@@ -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 {};
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { performance } from 'node:perf_hooks';
|
|
6
|
+
import { getStateDir } from './config.js';
|
|
7
|
+
import { BLOCK_END, BLOCK_START, getEngineSpecs, getUserHome } from './engines.js';
|
|
8
|
+
export const engines = ['claude-code', 'antigravity'];
|
|
9
|
+
const maxBytes = 1024 * 1024;
|
|
10
|
+
export function historyKeep(config) {
|
|
11
|
+
const n = config.history?.keep;
|
|
12
|
+
if (n === undefined)
|
|
13
|
+
return 10;
|
|
14
|
+
if (Number.isInteger(n) && n >= 1 && n <= 100)
|
|
15
|
+
return n;
|
|
16
|
+
console.error('Invalid history.keep. Keeping up to 10 versions plus the protected baseline.');
|
|
17
|
+
return 10;
|
|
18
|
+
}
|
|
19
|
+
// Linux reads this from /proc, so every ticket can carry it. Elsewhere asking
|
|
20
|
+
// the OS means spawning a process; see processStartTime.
|
|
21
|
+
function processIdentity(pid) {
|
|
22
|
+
if (process.platform !== 'linux')
|
|
23
|
+
return;
|
|
24
|
+
try {
|
|
25
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
26
|
+
// The name in parentheses can itself contain spaces and parentheses.
|
|
27
|
+
const ticks = stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];
|
|
28
|
+
const boot = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
|
29
|
+
if (ticks)
|
|
30
|
+
return hash(boot + ':' + ticks).slice(0, 32);
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
if (!hasCode(e, 'ENOENT') && !hasCode(e, 'EACCES') && !hasCode(e, 'EPERM'))
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// Epoch milliseconds, for macOS and Windows. Only call this for a ticket that is
|
|
38
|
+
// in the way: an uncontended lock must not spawn anything.
|
|
39
|
+
function processStartTime(pid) {
|
|
40
|
+
const windows = process.platform === 'win32';
|
|
41
|
+
const command = windows
|
|
42
|
+
? ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command',
|
|
43
|
+
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`]
|
|
44
|
+
: ['/bin/ps', '-p', String(pid), '-o', 'lstart='];
|
|
45
|
+
const result = spawnSync(command[0], command.slice(1), {
|
|
46
|
+
encoding: 'utf8', timeout: 750, env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, windowsHide: true,
|
|
47
|
+
});
|
|
48
|
+
const out = result.status === 0 ? result.stdout.trim() : '';
|
|
49
|
+
if (!out)
|
|
50
|
+
return;
|
|
51
|
+
// Windows counts 100 ns ticks from 1601; ps prints whole seconds.
|
|
52
|
+
const time = windows ? Number(out) / 10000 - 11644473600000 : Date.parse(out + ' UTC');
|
|
53
|
+
return Number.isFinite(time) ? time : undefined;
|
|
54
|
+
}
|
|
55
|
+
const ticketName = /^(choosing|[0-9]{12})\.([1-9]\d{0,8})-[a-f0-9-]{36}(?:\.([a-f0-9]{32}))?$/;
|
|
56
|
+
// A process that started after a ticket was written cannot be its owner: the PID
|
|
57
|
+
// was reused. The margin absorbs clock rounding. Unknown means still alive.
|
|
58
|
+
function reusedPid(file, pid, starts) {
|
|
59
|
+
let written;
|
|
60
|
+
try {
|
|
61
|
+
written = fs.readFileSync(file, 'utf8');
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
if (hasCode(e, 'ENOENT'))
|
|
65
|
+
return false;
|
|
66
|
+
throw e;
|
|
67
|
+
}
|
|
68
|
+
if (!/^\d+$/.test(written))
|
|
69
|
+
return false;
|
|
70
|
+
// Ask once per ticket, not on every turn of the wait loop.
|
|
71
|
+
const started = starts.get(file) ?? processStartTime(pid);
|
|
72
|
+
if (started === undefined)
|
|
73
|
+
return false;
|
|
74
|
+
starts.set(file, started);
|
|
75
|
+
return started > Number(written) + 2000;
|
|
76
|
+
}
|
|
77
|
+
function liveTicket(locks, name, starts) {
|
|
78
|
+
const match = ticketName.exec(name);
|
|
79
|
+
if (!match)
|
|
80
|
+
return false;
|
|
81
|
+
const pid = Number(match[2]);
|
|
82
|
+
let dead = false;
|
|
83
|
+
try {
|
|
84
|
+
process.kill(pid, 0);
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
dead = hasCode(e, 'ESRCH');
|
|
88
|
+
}
|
|
89
|
+
if (!dead && process.platform !== 'linux')
|
|
90
|
+
dead = reusedPid(path.join(locks, name), pid, starts);
|
|
91
|
+
else if (!dead && match[3]) {
|
|
92
|
+
const identity = processIdentity(pid);
|
|
93
|
+
dead = identity !== undefined && identity !== match[3];
|
|
94
|
+
}
|
|
95
|
+
if (dead)
|
|
96
|
+
fs.rmSync(path.join(locks, name), { force: true });
|
|
97
|
+
return !dead;
|
|
98
|
+
}
|
|
99
|
+
// The lock lives outside the reset tree. Hold it from before reading live bytes
|
|
100
|
+
// through publication, including across both engines during startup and reset.
|
|
101
|
+
export function withHistoryLock(home, work) {
|
|
102
|
+
const locks = destination(path.resolve(home)) + '.instruction-history-locks';
|
|
103
|
+
fs.mkdirSync(locks, { recursive: true, mode: 0o700 });
|
|
104
|
+
// Publish intent before choosing a ticket. Concurrent equal tickets are
|
|
105
|
+
// ordered by owner ID. A dead owner's unique ticket can be removed safely.
|
|
106
|
+
const identity = processIdentity(process.pid);
|
|
107
|
+
const owner = process.pid + '-' + randomUUID() + (identity ? '.' + identity : '');
|
|
108
|
+
let ticket = path.join(locks, 'choosing.' + owner);
|
|
109
|
+
fs.writeFileSync(ticket, String(Date.now()), { flag: 'wx', mode: 0o600 });
|
|
110
|
+
try {
|
|
111
|
+
const sequence = fs.readdirSync(locks).reduce((max, name) => {
|
|
112
|
+
const number = Number(ticketName.exec(name)?.[1]);
|
|
113
|
+
return Number.isNaN(number) ? max : Math.max(max, number);
|
|
114
|
+
}, 0) + 1;
|
|
115
|
+
const name = String(sequence).padStart(12, '0') + '.' + owner;
|
|
116
|
+
const published = path.join(locks, name);
|
|
117
|
+
fs.renameSync(ticket, published);
|
|
118
|
+
ticket = published;
|
|
119
|
+
const deadline = performance.now() + 5000;
|
|
120
|
+
const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
|
|
121
|
+
const starts = new Map();
|
|
122
|
+
while (fs.readdirSync(locks).some((other) => (other.startsWith('choosing.') || other < name) && liveTicket(locks, other, starts))) {
|
|
123
|
+
if (performance.now() >= deadline)
|
|
124
|
+
throw new Error('Instruction history is busy. Re-run the command.');
|
|
125
|
+
Atomics.wait(waitBuffer, 0, 0, 50);
|
|
126
|
+
}
|
|
127
|
+
return work();
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
fs.rmSync(ticket, { force: true });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function hasCode(e, code) {
|
|
134
|
+
return e?.code === code;
|
|
135
|
+
}
|
|
136
|
+
function atomicWrite(file, data, mode = 0o600) {
|
|
137
|
+
const tmp = path.join(path.dirname(file), '.tmp-' + randomUUID());
|
|
138
|
+
try {
|
|
139
|
+
fs.writeFileSync(tmp, data, { flag: 'wx', mode });
|
|
140
|
+
fs.renameSync(tmp, file);
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
fs.rmSync(tmp, { force: true });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function destination(file, depth = 0) {
|
|
147
|
+
try {
|
|
148
|
+
return fs.realpathSync.native(file);
|
|
149
|
+
}
|
|
150
|
+
catch (e) {
|
|
151
|
+
if (!hasCode(e, 'ENOENT') || depth > 40)
|
|
152
|
+
throw e;
|
|
153
|
+
try {
|
|
154
|
+
const link = fs.readlinkSync(file);
|
|
155
|
+
return destination(path.resolve(path.dirname(file), link), depth + 1);
|
|
156
|
+
}
|
|
157
|
+
catch (linkError) {
|
|
158
|
+
if (!hasCode(linkError, 'ENOENT'))
|
|
159
|
+
throw linkError;
|
|
160
|
+
return path.join(destination(path.dirname(file), depth + 1), path.basename(file));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function metadata(bytes) {
|
|
165
|
+
if (bytes === null)
|
|
166
|
+
return { size: 0, hash: null, block: false };
|
|
167
|
+
const start = bytes.indexOf(BLOCK_START);
|
|
168
|
+
return {
|
|
169
|
+
size: bytes.length,
|
|
170
|
+
hash: hash(bytes),
|
|
171
|
+
block: start >= 0 && bytes.indexOf(BLOCK_END, start + BLOCK_START.length) >= 0,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function hash(value) {
|
|
175
|
+
return createHash('sha256').update(value).digest('hex');
|
|
176
|
+
}
|
|
177
|
+
function readLive(file) {
|
|
178
|
+
const dest = destination(file);
|
|
179
|
+
let bytes = null;
|
|
180
|
+
try {
|
|
181
|
+
const stat = fs.statSync(dest);
|
|
182
|
+
if (!stat.isFile())
|
|
183
|
+
throw new Error('Expected a regular instruction file: ' + file);
|
|
184
|
+
if (stat.size > maxBytes) {
|
|
185
|
+
// Inspect block presence without buffering a potentially huge instruction file.
|
|
186
|
+
const fd = fs.openSync(dest, 'r');
|
|
187
|
+
let tail = '', started = false, block = false;
|
|
188
|
+
const chunk = Buffer.alloc(65536);
|
|
189
|
+
try {
|
|
190
|
+
let n;
|
|
191
|
+
while (!block && (n = fs.readSync(fd, chunk)) > 0) {
|
|
192
|
+
const text = tail + chunk.toString('latin1', 0, n);
|
|
193
|
+
const start = started ? 0 : text.indexOf(BLOCK_START);
|
|
194
|
+
if (start >= 0) {
|
|
195
|
+
block = text.indexOf(BLOCK_END, started ? 0 : start + BLOCK_START.length) >= 0;
|
|
196
|
+
started = true;
|
|
197
|
+
}
|
|
198
|
+
tail = text.slice(-Math.max(BLOCK_START.length, BLOCK_END.length));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
fs.closeSync(fd);
|
|
203
|
+
}
|
|
204
|
+
return { size: stat.size, hash: 'oversize', bytes, block, destination: dest };
|
|
205
|
+
}
|
|
206
|
+
bytes = fs.readFileSync(dest);
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
if (!hasCode(e, 'ENOENT'))
|
|
210
|
+
throw e;
|
|
211
|
+
}
|
|
212
|
+
return { ...metadata(bytes), bytes, destination: dest };
|
|
213
|
+
}
|
|
214
|
+
function damage(base, live) {
|
|
215
|
+
if (!base || base.hash === null)
|
|
216
|
+
return;
|
|
217
|
+
if (live.hash === null)
|
|
218
|
+
return 'deleted';
|
|
219
|
+
if (base.block && !live.block)
|
|
220
|
+
return 'managed block missing';
|
|
221
|
+
if (base.size >= 200 && live.size < base.size / 2)
|
|
222
|
+
return 'size drop';
|
|
223
|
+
}
|
|
224
|
+
function fallback(rows) {
|
|
225
|
+
const blocks = rows.filter((r) => r.block);
|
|
226
|
+
return (blocks.find((r) => !rows.some((old) => old.id < r.id && old.size >= 200 && r.size < old.size / 2)) ??
|
|
227
|
+
blocks[0] ??
|
|
228
|
+
[...rows].reverse().find((r) => r.hash !== null) ??
|
|
229
|
+
rows[0]);
|
|
230
|
+
}
|
|
231
|
+
const versionName = /^\d{16}-[a-f0-9-]{36}\.(md|deleted)$/;
|
|
232
|
+
function restorePromotion(text) {
|
|
233
|
+
const value = JSON.parse(text);
|
|
234
|
+
if (typeof value !== 'object' || value === null ||
|
|
235
|
+
!('id' in value) || typeof value.id !== 'string' || !versionName.test(value.id) ||
|
|
236
|
+
!('destinationHash' in value) || typeof value.destinationHash !== 'string' ||
|
|
237
|
+
!/^[a-f0-9]{64}$/.test(value.destinationHash))
|
|
238
|
+
throw new Error('Invalid pending instruction history promotion.');
|
|
239
|
+
return { id: value.id, destinationHash: value.destinationHash };
|
|
240
|
+
}
|
|
241
|
+
function baselineId(marker) {
|
|
242
|
+
if (versionName.test(marker))
|
|
243
|
+
return marker;
|
|
244
|
+
try {
|
|
245
|
+
return restorePromotion(marker).id;
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return '';
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function readBaselineId(dir) {
|
|
252
|
+
try {
|
|
253
|
+
return baselineId(fs.readFileSync(path.join(dir, 'baseline'), 'utf8'));
|
|
254
|
+
}
|
|
255
|
+
catch (e) {
|
|
256
|
+
if (hasCode(e, 'ENOENT') || hasCode(e, 'EACCES') || hasCode(e, 'EISDIR'))
|
|
257
|
+
return '';
|
|
258
|
+
throw e;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function damageWarning(file, engine, reason) {
|
|
262
|
+
if (reason)
|
|
263
|
+
return file + ': ' + reason + '. Run faber-memory restore ' + engine + '.';
|
|
264
|
+
}
|
|
265
|
+
function readDamageWarning(home, engine) {
|
|
266
|
+
const dir = path.join(getStateDir(home), 'history', engine);
|
|
267
|
+
const file = getEngineSpecs()[engine].instructionFile(getUserHome());
|
|
268
|
+
// Read the published baseline directly. A writer may be changing or pruning
|
|
269
|
+
// other rows between our reads, so the full index is only a fallback.
|
|
270
|
+
const id = readBaselineId(dir);
|
|
271
|
+
if (id) {
|
|
272
|
+
try {
|
|
273
|
+
const bytes = id.endsWith('.deleted') ? null : fs.readFileSync(path.join(dir, id));
|
|
274
|
+
return damageWarning(file, engine, damage(metadata(bytes), readLive(file)));
|
|
275
|
+
}
|
|
276
|
+
catch (e) {
|
|
277
|
+
if (!hasCode(e, 'ENOENT'))
|
|
278
|
+
throw e;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const history = new InstructionHistory(home, engine);
|
|
282
|
+
return history.warning(history.live());
|
|
283
|
+
}
|
|
284
|
+
export class InstructionHistory {
|
|
285
|
+
engine;
|
|
286
|
+
file;
|
|
287
|
+
dir;
|
|
288
|
+
rows = [];
|
|
289
|
+
baseline;
|
|
290
|
+
rebuild = false;
|
|
291
|
+
constructor(home, engine, userHome = getUserHome()) {
|
|
292
|
+
this.engine = engine;
|
|
293
|
+
this.file = getEngineSpecs()[engine].instructionFile(userHome);
|
|
294
|
+
this.dir = path.join(getStateDir(home), 'history', engine);
|
|
295
|
+
let ids;
|
|
296
|
+
try {
|
|
297
|
+
ids = fs
|
|
298
|
+
.readdirSync(this.dir)
|
|
299
|
+
.filter((id) => versionName.test(id))
|
|
300
|
+
.sort()
|
|
301
|
+
.reverse();
|
|
302
|
+
}
|
|
303
|
+
catch (e) {
|
|
304
|
+
if (hasCode(e, 'ENOENT'))
|
|
305
|
+
return;
|
|
306
|
+
throw e;
|
|
307
|
+
}
|
|
308
|
+
if (!ids.length)
|
|
309
|
+
return;
|
|
310
|
+
try {
|
|
311
|
+
const rows = JSON.parse(fs.readFileSync(path.join(this.dir, 'index.json'), 'utf8'));
|
|
312
|
+
if (!Array.isArray(rows) ||
|
|
313
|
+
rows.length !== ids.length ||
|
|
314
|
+
!rows.every((r, i) => r?.id === ids[i] &&
|
|
315
|
+
Number.isFinite(r.time) &&
|
|
316
|
+
Number.isSafeInteger(r.size) &&
|
|
317
|
+
typeof r.block === 'boolean' &&
|
|
318
|
+
(r.hash === null ? r.id.endsWith('.deleted') : /^[0-9a-f]{64}$/.test(r.hash)) &&
|
|
319
|
+
['unknown', 'server-start', 'init', 'init-undo', 'accept', 'restore'].includes(r.trigger)))
|
|
320
|
+
throw Error();
|
|
321
|
+
this.rows = rows;
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
this.rebuild = true;
|
|
325
|
+
console.error('Rebuilding instruction history index for ' + engine);
|
|
326
|
+
this.rows = ids.map((id) => ({
|
|
327
|
+
id,
|
|
328
|
+
...metadata(this.bytes(id)),
|
|
329
|
+
time: fs.statSync(path.join(this.dir, id)).mtimeMs,
|
|
330
|
+
trigger: 'unknown',
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
const id = readBaselineId(this.dir);
|
|
334
|
+
this.baseline = this.rows.find((r) => r.id === id);
|
|
335
|
+
if (!this.baseline) {
|
|
336
|
+
this.baseline = fallback(this.rows);
|
|
337
|
+
this.rebuild = true;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
live() {
|
|
341
|
+
return readLive(this.file);
|
|
342
|
+
}
|
|
343
|
+
reason(live) {
|
|
344
|
+
return damage(this.baseline, live);
|
|
345
|
+
}
|
|
346
|
+
warning(live) {
|
|
347
|
+
return damageWarning(this.file, this.engine, this.reason(live));
|
|
348
|
+
}
|
|
349
|
+
bytes(id) {
|
|
350
|
+
return id.endsWith('.deleted') ? null : fs.readFileSync(path.join(this.dir, id));
|
|
351
|
+
}
|
|
352
|
+
revision() {
|
|
353
|
+
return JSON.stringify([this.rows, this.baseline?.id, this.readPendingRestore()]);
|
|
354
|
+
}
|
|
355
|
+
record(live, trigger) {
|
|
356
|
+
if (live.size > maxBytes)
|
|
357
|
+
throw new Error(this.file + ' exceeds 1 MB. Version was not stored.');
|
|
358
|
+
if (this.rows[0]?.hash === live.hash || (!this.rows.length && live.hash === null))
|
|
359
|
+
return this.rows[0];
|
|
360
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
361
|
+
const seq = Number(this.rows[0]?.id.slice(0, 16) ?? 0) + 1;
|
|
362
|
+
const id = String(seq).padStart(16, '0') + '-' + randomUUID() + (live.hash === null ? '.deleted' : '.md');
|
|
363
|
+
atomicWrite(path.join(this.dir, id), live.bytes ?? '');
|
|
364
|
+
const row = { id, size: live.size, hash: live.hash, block: live.block, trigger, time: Date.now() };
|
|
365
|
+
this.rows.unshift(row);
|
|
366
|
+
this.rebuild = true;
|
|
367
|
+
return row;
|
|
368
|
+
}
|
|
369
|
+
finish(base, keep) {
|
|
370
|
+
if (!base)
|
|
371
|
+
return;
|
|
372
|
+
const retained = this.rows.filter((r, i) => i < keep || r.id === base.id);
|
|
373
|
+
// Publish the list before changing the baseline. If this fails, the old
|
|
374
|
+
// marker and its bytes still exist, including when accept is retried.
|
|
375
|
+
if (this.rebuild || retained.length !== this.rows.length)
|
|
376
|
+
atomicWrite(path.join(this.dir, 'index.json'), JSON.stringify(retained));
|
|
377
|
+
if (this.rebuild || this.baseline?.id !== base.id)
|
|
378
|
+
atomicWrite(path.join(this.dir, 'baseline'), base.id);
|
|
379
|
+
this.baseline = base;
|
|
380
|
+
for (const row of this.rows) {
|
|
381
|
+
if (!retained.includes(row))
|
|
382
|
+
fs.rmSync(path.join(this.dir, row.id), { force: true });
|
|
383
|
+
}
|
|
384
|
+
this.rows = retained;
|
|
385
|
+
this.rebuild = false;
|
|
386
|
+
}
|
|
387
|
+
snapshot(trigger, keep, promote = false) {
|
|
388
|
+
const live = this.live();
|
|
389
|
+
const warning = this.warning(live);
|
|
390
|
+
const row = this.record(live, trigger);
|
|
391
|
+
this.finish(promote || !warning ? row : this.baseline, keep);
|
|
392
|
+
return warning;
|
|
393
|
+
}
|
|
394
|
+
restoreBytes(live, bytes) {
|
|
395
|
+
fs.mkdirSync(path.dirname(live.destination), { recursive: true });
|
|
396
|
+
const mode = live.hash === null ? 0o600 : fs.statSync(live.destination).mode & 0o777;
|
|
397
|
+
atomicWrite(live.destination, bytes, mode);
|
|
398
|
+
}
|
|
399
|
+
get pendingRestorePath() {
|
|
400
|
+
return path.join(this.dir, 'pending-restore');
|
|
401
|
+
}
|
|
402
|
+
readPendingRestore() {
|
|
403
|
+
try {
|
|
404
|
+
return fs.readFileSync(this.pendingRestorePath, 'utf8');
|
|
405
|
+
}
|
|
406
|
+
catch (e) {
|
|
407
|
+
if (!hasCode(e, 'ENOENT'))
|
|
408
|
+
throw e;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
publishRestore(target) {
|
|
412
|
+
fs.renameSync(this.pendingRestorePath, path.join(this.dir, 'baseline'));
|
|
413
|
+
this.baseline = target;
|
|
414
|
+
}
|
|
415
|
+
restore(target, live, bytes, keep) {
|
|
416
|
+
const previous = this.record(live, 'restore');
|
|
417
|
+
// Keep both versions until replacement and baseline publication succeed.
|
|
418
|
+
this.finish(this.baseline ?? previous, Infinity);
|
|
419
|
+
const marker = path.join(this.dir, 'baseline');
|
|
420
|
+
if (!fs.lstatSync(marker).isFile())
|
|
421
|
+
throw new Error('Cannot publish the instruction history baseline.');
|
|
422
|
+
// Check the actual destination as well as the directory. An existing
|
|
423
|
+
// marker can have replacement restrictions that staging alone misses.
|
|
424
|
+
atomicWrite(marker, fs.readFileSync(marker));
|
|
425
|
+
const pending = { id: target.id, destinationHash: hash(live.destination) };
|
|
426
|
+
// Prepare the actual replacement marker on the same filesystem before
|
|
427
|
+
// touching the live file. A later rename needs no new marker contents.
|
|
428
|
+
atomicWrite(this.pendingRestorePath, JSON.stringify(pending));
|
|
429
|
+
this.restoreBytes(live, bytes);
|
|
430
|
+
this.publishRestore(target);
|
|
431
|
+
this.finish(target, keep);
|
|
432
|
+
}
|
|
433
|
+
recoverRestore(live) {
|
|
434
|
+
const text = this.readPendingRestore();
|
|
435
|
+
if (text === undefined)
|
|
436
|
+
return false;
|
|
437
|
+
let pending;
|
|
438
|
+
try {
|
|
439
|
+
pending = restorePromotion(text);
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
// An unreadable promotion cannot be matched to a version. Drop it so
|
|
443
|
+
// capture, accept and restore keep working with normal damage checks.
|
|
444
|
+
console.error('Discarding unreadable pending instruction history promotion for ' + this.engine);
|
|
445
|
+
}
|
|
446
|
+
const target = pending && this.rows.find((row) => row.id === pending.id);
|
|
447
|
+
if (pending && target && live.bytes !== null && target.hash === live.hash &&
|
|
448
|
+
pending.destinationHash === hash(live.destination) && this.bytes(target.id)?.equals(live.bytes)) {
|
|
449
|
+
this.publishRestore(target);
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
fs.rmSync(this.pendingRestorePath, { force: true });
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
export function startupHistory(home, config) {
|
|
457
|
+
const warnings = [], errors = new Set();
|
|
458
|
+
const keep = historyKeep(config);
|
|
459
|
+
const check = (capture) => {
|
|
460
|
+
for (const engine of engines) {
|
|
461
|
+
try {
|
|
462
|
+
if (!capture) {
|
|
463
|
+
const warning = readDamageWarning(home, engine);
|
|
464
|
+
if (warning)
|
|
465
|
+
warnings.push(warning);
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
const history = new InstructionHistory(home, engine);
|
|
469
|
+
const live = history.live();
|
|
470
|
+
let recovered = false;
|
|
471
|
+
try {
|
|
472
|
+
recovered = history.recoverRestore(live);
|
|
473
|
+
}
|
|
474
|
+
catch (e) {
|
|
475
|
+
errors.add(String(e));
|
|
476
|
+
const warning = history.warning(live);
|
|
477
|
+
if (warning)
|
|
478
|
+
warnings.push(warning);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const warning = history.warning(live);
|
|
482
|
+
if (warning)
|
|
483
|
+
warnings.push(warning);
|
|
484
|
+
const row = recovered ? history.baseline : history.record(live, 'server-start');
|
|
485
|
+
history.finish(warning ? history.baseline : row, keep);
|
|
486
|
+
}
|
|
487
|
+
catch (e) {
|
|
488
|
+
errors.add(String(e));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
let entered = false;
|
|
493
|
+
try {
|
|
494
|
+
withHistoryLock(home, () => {
|
|
495
|
+
entered = true;
|
|
496
|
+
check(true);
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
catch (e) {
|
|
500
|
+
errors.add(String(e));
|
|
501
|
+
if (!entered)
|
|
502
|
+
check(false);
|
|
503
|
+
}
|
|
504
|
+
if (errors.size)
|
|
505
|
+
console.error('Instruction history: ' + [...errors].join('\n'));
|
|
506
|
+
return warnings.length ? 'Tell the user in one line: ' + warnings.join(' ') : undefined;
|
|
507
|
+
}
|
package/dist/src/mcp.d.ts
CHANGED
|
@@ -122,6 +122,8 @@ export declare class FaberMemoryMcpServer {
|
|
|
122
122
|
private startupWarnings;
|
|
123
123
|
private unpushedReminderShown;
|
|
124
124
|
private startupPullPromise;
|
|
125
|
+
private historyInstructions?;
|
|
126
|
+
private historyWarningSent;
|
|
125
127
|
private directSaveCount;
|
|
126
128
|
/** Keeps stdio responses in request order while a direct save awaits pull/push. */
|
|
127
129
|
private queue;
|
|
@@ -259,6 +261,7 @@ export declare class FaberMemoryMcpServer {
|
|
|
259
261
|
/** JSON-RPC entry for stdio: like `handleJsonRpc`, with `tools/call` via `handleToolCallAsync`. */
|
|
260
262
|
handleJsonRpcAsync(req: JsonRpcRequest): Promise<Record<string, unknown> | null>;
|
|
261
263
|
handleJsonRpc(req: JsonRpcRequest): Record<string, unknown> | null;
|
|
264
|
+
private withHistoryWarning;
|
|
262
265
|
serveStdio(): void;
|
|
263
266
|
}
|
|
264
267
|
export {};
|
package/dist/src/mcp.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { startupHistory } from './instruction-history.js';
|
|
1
2
|
import * as fs from 'node:fs';
|
|
2
3
|
import * as readline from 'node:readline';
|
|
3
4
|
import { BM25Index, findNearDuplicates, findRelatedEntries } from './bm25.js';
|
|
@@ -85,6 +86,8 @@ export class FaberMemoryMcpServer {
|
|
|
85
86
|
startupWarnings = [];
|
|
86
87
|
unpushedReminderShown = false;
|
|
87
88
|
startupPullPromise = null;
|
|
89
|
+
historyInstructions;
|
|
90
|
+
historyWarningSent = false;
|
|
88
91
|
directSaveCount = 0;
|
|
89
92
|
/** Keeps stdio responses in request order while a direct save awaits pull/push. */
|
|
90
93
|
queue = Promise.resolve();
|
|
@@ -96,6 +99,7 @@ export class FaberMemoryMcpServer {
|
|
|
96
99
|
}
|
|
97
100
|
startNonBlockingSync() {
|
|
98
101
|
const config = loadConfig(this.homeDir);
|
|
102
|
+
this.historyInstructions = startupHistory(this.homeDir, config);
|
|
99
103
|
// Ensure compiled L0 exists on startup if missing
|
|
100
104
|
if (!fs.existsSync(getCompiledL0Path(this.homeDir))) {
|
|
101
105
|
compileGlobalL0(config, { homeDir: this.homeDir, trigger: 'mcp-startup' });
|
|
@@ -519,7 +523,7 @@ export class FaberMemoryMcpServer {
|
|
|
519
523
|
return this.handleJsonRpc(req);
|
|
520
524
|
const params = req.params || {};
|
|
521
525
|
const res = await this.handleToolCallAsync(String(params.name || ''), params.arguments || {});
|
|
522
|
-
return { jsonrpc: '2.0', id: req.id ?? null, result: res };
|
|
526
|
+
return { jsonrpc: '2.0', id: req.id ?? null, result: this.withHistoryWarning(res) };
|
|
523
527
|
}
|
|
524
528
|
handleJsonRpc(req) {
|
|
525
529
|
if (req.method === 'initialize') {
|
|
@@ -527,6 +531,7 @@ export class FaberMemoryMcpServer {
|
|
|
527
531
|
jsonrpc: '2.0',
|
|
528
532
|
id: req.id ?? null,
|
|
529
533
|
result: {
|
|
534
|
+
...(this.historyInstructions ? { instructions: this.historyInstructions } : {}),
|
|
530
535
|
protocolVersion: '2024-11-05',
|
|
531
536
|
capabilities: {
|
|
532
537
|
tools: { listChanged: false },
|
|
@@ -559,7 +564,7 @@ export class FaberMemoryMcpServer {
|
|
|
559
564
|
return {
|
|
560
565
|
jsonrpc: '2.0',
|
|
561
566
|
id: req.id ?? null,
|
|
562
|
-
result: res,
|
|
567
|
+
result: this.withHistoryWarning(res),
|
|
563
568
|
};
|
|
564
569
|
}
|
|
565
570
|
if (req.id === undefined)
|
|
@@ -570,6 +575,13 @@ export class FaberMemoryMcpServer {
|
|
|
570
575
|
error: { code: -32601, message: `Method not found: ${req.method}` },
|
|
571
576
|
};
|
|
572
577
|
}
|
|
578
|
+
withHistoryWarning(response) {
|
|
579
|
+
if (this.historyInstructions && !this.historyWarningSent) {
|
|
580
|
+
this.historyWarningSent = true;
|
|
581
|
+
response.content.push({ type: 'text', text: this.historyInstructions });
|
|
582
|
+
}
|
|
583
|
+
return response;
|
|
584
|
+
}
|
|
573
585
|
serveStdio() {
|
|
574
586
|
this.startNonBlockingSync();
|
|
575
587
|
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
package/dist/src/types.d.ts
CHANGED
package/package.json
CHANGED