@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 +14 -0
- package/README.md +6 -3
- package/dist/src/cli.js +53 -25
- 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 +13 -15
- package/dist/src/init.js +210 -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
|
@@ -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