@robhowley/pi-remembrancer 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -17
- package/extensions/remembrancer/capture-artifacts.ts +211 -0
- package/extensions/remembrancer/capture-handoff.ts +714 -0
- package/extensions/remembrancer/capture-jobs.ts +112 -0
- package/extensions/remembrancer/capture-matches.ts +145 -0
- package/extensions/remembrancer/capture-notices.ts +54 -0
- package/extensions/remembrancer/capture-publication-lock.mjs +37 -0
- package/extensions/remembrancer/capture-review.ts +84 -12
- package/extensions/remembrancer/capture-sizing.ts +63 -0
- package/extensions/remembrancer/capture-submission.ts +289 -0
- package/extensions/remembrancer/capture-worker-bootstrap.mjs +53 -0
- package/extensions/remembrancer/capture-worker.ts +341 -0
- package/extensions/remembrancer/capture.ts +262 -136
- package/extensions/remembrancer/checkpoints.ts +687 -119
- package/extensions/remembrancer/config.ts +31 -1
- package/extensions/remembrancer/evidence.ts +318 -74
- package/extensions/remembrancer/index.ts +260 -14
- package/extensions/remembrancer/private-sqlite.mjs +17 -0
- package/extensions/remembrancer/proposal-read.ts +223 -9
- package/extensions/remembrancer/proposal-ui.ts +608 -191
- package/extensions/remembrancer/proposals.ts +44 -9
- package/extensions/remembrancer/review-findings.ts +178 -0
- package/extensions/remembrancer/review-pages.ts +58 -16
- package/extensions/remembrancer/review-plan.ts +27 -0
- package/extensions/remembrancer/reviewer-budget.ts +53 -0
- package/extensions/remembrancer/reviewer.ts +166 -30
- package/extensions/remembrancer/taskwarrior.ts +95 -14
- package/package.json +5 -4
- package/skills/remembrancer/SKILL.md +35 -19
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import {
|
|
3
|
+
getAgentDir,
|
|
4
|
+
getPackageDir,
|
|
5
|
+
SettingsManager,
|
|
6
|
+
type ExtensionContext,
|
|
7
|
+
} from '@earendil-works/pi-coding-agent';
|
|
8
|
+
import type { HandoffInput } from './capture-handoff.js';
|
|
2
9
|
|
|
3
10
|
export interface RemembrancerConfig {
|
|
4
11
|
disabled: boolean;
|
|
@@ -31,6 +38,29 @@ export function loadRemembrancerConfig(cwd: string, projectTrusted: boolean): Re
|
|
|
31
38
|
};
|
|
32
39
|
}
|
|
33
40
|
|
|
41
|
+
export function captureHost(): NonNullable<HandoffInput['execution']['host']> {
|
|
42
|
+
return { nodeExecutable: process.execPath, piEntry: join(getPackageDir(), 'dist', 'cli.js') };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Capture non-secret execution data from the outgoing context, never from a later waking TUI. */
|
|
46
|
+
export function captureExecution(ctx: ExtensionContext): HandoffInput['execution'] {
|
|
47
|
+
if (!ctx.model) throw Error('Capture requires the outgoing model');
|
|
48
|
+
const model = structuredClone(ctx.model);
|
|
49
|
+
delete model.headers;
|
|
50
|
+
return {
|
|
51
|
+
cwd: ctx.cwd,
|
|
52
|
+
agentDir: getAgentDir(),
|
|
53
|
+
authorization: { autoCapture: true, disabled: false },
|
|
54
|
+
host: captureHost(),
|
|
55
|
+
runtime: {
|
|
56
|
+
model,
|
|
57
|
+
...(ctx.model.headers ? { headerNames: Object.keys(ctx.model.headers) } : {}),
|
|
58
|
+
thinkingLevel: ctx.thinkingLevel ?? 'medium',
|
|
59
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
34
64
|
function remembrancerSettings(settings: unknown): Record<string, unknown> {
|
|
35
65
|
if (!isRecord(settings)) return {};
|
|
36
66
|
const remembrancer = settings['pi-remembrancer'];
|
|
@@ -149,6 +149,20 @@ export const REVIEW_LIMITS = {
|
|
|
149
149
|
export type ReviewLimits = typeof REVIEW_LIMITS;
|
|
150
150
|
export class ReviewLimitError extends Error {}
|
|
151
151
|
|
|
152
|
+
type InvalidSessionCategory =
|
|
153
|
+
| 'invalid-json'
|
|
154
|
+
| 'invalid-tree'
|
|
155
|
+
| 'invalid-identity'
|
|
156
|
+
| 'retained-limit';
|
|
157
|
+
class InvalidSessionError extends Error {
|
|
158
|
+
constructor(
|
|
159
|
+
readonly category: InvalidSessionCategory,
|
|
160
|
+
message: string,
|
|
161
|
+
) {
|
|
162
|
+
super(message);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
152
166
|
const COMPACT_HEADER_BYTES = 32;
|
|
153
167
|
const COMPACT_ENTRY_BYTES = 64;
|
|
154
168
|
|
|
@@ -179,6 +193,7 @@ export class ReviewBudget {
|
|
|
179
193
|
private bytes = 0;
|
|
180
194
|
private textBytes = 0;
|
|
181
195
|
private branches = 0;
|
|
196
|
+
private sourceVisits = new WeakMap<SessionTree, number>();
|
|
182
197
|
constructor(limits: Partial<ReviewLimits> = {}) {
|
|
183
198
|
this.limits = { ...REVIEW_LIMITS, ...limits };
|
|
184
199
|
}
|
|
@@ -202,19 +217,24 @@ export class ReviewBudget {
|
|
|
202
217
|
throw new ReviewLimitError('Aggregate review snapshot limit exceeded');
|
|
203
218
|
this.trees.add(tree);
|
|
204
219
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
this.branches
|
|
220
|
+
visit(tree: SessionTree) {
|
|
221
|
+
const visits = (this.sourceVisits.get(tree) ?? 0) + 1;
|
|
222
|
+
this.sourceVisits.set(tree, visits);
|
|
223
|
+
this.branches++;
|
|
209
224
|
if (this.branches > this.limits.totalBranchEntries)
|
|
210
225
|
throw new ReviewLimitError('Aggregate review branch/evidence limit exceeded');
|
|
226
|
+
if (visits > this.limits.sourceBranchEntries)
|
|
227
|
+
throw new ReviewLimitError('Session ancestry walk limit exceeded');
|
|
211
228
|
}
|
|
212
229
|
}
|
|
213
230
|
|
|
214
231
|
function visibleText(content: unknown, maxBytes = Number.POSITIVE_INFINITY): string {
|
|
215
232
|
if (typeof content === 'string') {
|
|
216
233
|
if (Buffer.byteLength(content) > maxBytes)
|
|
217
|
-
throw
|
|
234
|
+
throw new InvalidSessionError(
|
|
235
|
+
'retained-limit',
|
|
236
|
+
'Session retained text/metadata limit exceeded',
|
|
237
|
+
);
|
|
218
238
|
return content;
|
|
219
239
|
}
|
|
220
240
|
if (!Array.isArray(content)) return '';
|
|
@@ -224,18 +244,41 @@ function visibleText(content: unknown, maxBytes = Number.POSITIVE_INFINITY): str
|
|
|
224
244
|
for (const block of content) {
|
|
225
245
|
if (block?.type !== 'text' || typeof block.text !== 'string') continue;
|
|
226
246
|
bytes += Buffer.byteLength(block.text) + (texts.length > 0 ? 1 : 0);
|
|
227
|
-
if (bytes > maxBytes)
|
|
247
|
+
if (bytes > maxBytes)
|
|
248
|
+
throw new InvalidSessionError(
|
|
249
|
+
'retained-limit',
|
|
250
|
+
'Session retained text/metadata limit exceeded',
|
|
251
|
+
);
|
|
228
252
|
texts.push(block.text);
|
|
229
253
|
}
|
|
230
254
|
return texts.join('\n');
|
|
231
255
|
}
|
|
232
256
|
|
|
233
257
|
/** Read only the opening extent. Verify its bytes again without retaining them. */
|
|
234
|
-
function readRecords(
|
|
258
|
+
function readRecords(
|
|
259
|
+
file: string,
|
|
260
|
+
limit: number,
|
|
261
|
+
consume: (line: string, number: number) => void,
|
|
262
|
+
prefix?: string,
|
|
263
|
+
) {
|
|
235
264
|
const fd = openSync(file, 'r');
|
|
265
|
+
let prefixFd: number | undefined;
|
|
236
266
|
try {
|
|
267
|
+
prefixFd = prefix === undefined ? undefined : openSync(prefix, 'r');
|
|
237
268
|
const initial = fstatSync(fd);
|
|
238
269
|
if (!initial.isFile()) throw Error('Session source is not a regular file');
|
|
270
|
+
const prefixStat = prefixFd === undefined ? undefined : fstatSync(prefixFd);
|
|
271
|
+
const comparison = Buffer.allocUnsafe(64 * 1024);
|
|
272
|
+
if (prefixStat) {
|
|
273
|
+
const last = Buffer.alloc(1);
|
|
274
|
+
if (
|
|
275
|
+
!prefixStat.size ||
|
|
276
|
+
initial.size < prefixStat.size ||
|
|
277
|
+
readSync(prefixFd!, last, 0, 1, prefixStat.size - 1) !== 1 ||
|
|
278
|
+
last[0] !== 10
|
|
279
|
+
)
|
|
280
|
+
throw Error('Live source is not an exact extension of the retained prefix');
|
|
281
|
+
}
|
|
239
282
|
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
240
283
|
let parts: Buffer[] = [];
|
|
241
284
|
let length = 0;
|
|
@@ -250,6 +293,14 @@ function readRecords(file: string, limit: number, consume: (line: string, number
|
|
|
250
293
|
position,
|
|
251
294
|
);
|
|
252
295
|
if (!count) throw Error('Session source truncated during read');
|
|
296
|
+
if (prefixStat && position < prefixStat.size) {
|
|
297
|
+
const length = Math.min(count, prefixStat.size - position);
|
|
298
|
+
if (
|
|
299
|
+
readSync(prefixFd!, comparison, 0, length, position) !== length ||
|
|
300
|
+
!chunk.subarray(0, length).equals(comparison.subarray(0, length))
|
|
301
|
+
)
|
|
302
|
+
throw Error('Live source is not an exact extension of the retained prefix');
|
|
303
|
+
}
|
|
253
304
|
position += count;
|
|
254
305
|
hash.update(chunk.subarray(0, count));
|
|
255
306
|
let start = 0;
|
|
@@ -257,7 +308,8 @@ function readRecords(file: string, limit: number, consume: (line: string, number
|
|
|
257
308
|
const newline = chunk.indexOf(10, start);
|
|
258
309
|
const end = newline < 0 || newline >= count ? count : newline;
|
|
259
310
|
const size = end - start;
|
|
260
|
-
if (length + size > limit)
|
|
311
|
+
if (length + size > limit)
|
|
312
|
+
throw new InvalidSessionError('retained-limit', 'Session raw record limit exceeded');
|
|
261
313
|
if (size) parts.push(Buffer.from(chunk.subarray(start, end)));
|
|
262
314
|
length += size;
|
|
263
315
|
if (end < count) {
|
|
@@ -283,6 +335,15 @@ function readRecords(file: string, limit: number, consume: (line: string, number
|
|
|
283
335
|
verify.update(chunk.subarray(0, count));
|
|
284
336
|
position += count;
|
|
285
337
|
}
|
|
338
|
+
if (prefixStat) {
|
|
339
|
+
const finalPrefix = fstatSync(prefixFd!);
|
|
340
|
+
if (
|
|
341
|
+
finalPrefix.size !== prefixStat.size ||
|
|
342
|
+
finalPrefix.mtimeMs !== prefixStat.mtimeMs ||
|
|
343
|
+
finalPrefix.ctimeMs !== prefixStat.ctimeMs
|
|
344
|
+
)
|
|
345
|
+
throw Error('Retained prefix changed during verification');
|
|
346
|
+
}
|
|
286
347
|
const final = fstatSync(fd);
|
|
287
348
|
const path = statSync(file);
|
|
288
349
|
if (
|
|
@@ -295,11 +356,12 @@ function readRecords(file: string, limit: number, consume: (line: string, number
|
|
|
295
356
|
)
|
|
296
357
|
throw Error('Session source changed during read');
|
|
297
358
|
} finally {
|
|
359
|
+
if (prefixFd !== undefined) closeSync(prefixFd);
|
|
298
360
|
closeSync(fd);
|
|
299
361
|
}
|
|
300
362
|
}
|
|
301
363
|
|
|
302
|
-
export function readSession(file: string, limits: ReviewLimits = REVIEW_LIMITS) {
|
|
364
|
+
export function readSession(file: string, limits: ReviewLimits = REVIEW_LIMITS, prefix?: string) {
|
|
303
365
|
let header: { type?: string; id?: unknown; cwd?: unknown } = {};
|
|
304
366
|
const entries = new Map<string, Entry>();
|
|
305
367
|
const leaves = new Set<string>();
|
|
@@ -307,74 +369,97 @@ export function readSession(file: string, limits: ReviewLimits = REVIEW_LIMITS)
|
|
|
307
369
|
let bytes = 0;
|
|
308
370
|
let textBytes = 0;
|
|
309
371
|
const bounded = (value: string, max = 256) => {
|
|
310
|
-
if (Buffer.byteLength(value) > max)
|
|
372
|
+
if (Buffer.byteLength(value) > max)
|
|
373
|
+
throw new InvalidSessionError('retained-limit', 'Session metadata limit exceeded');
|
|
311
374
|
return value;
|
|
312
375
|
};
|
|
313
|
-
readRecords(
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
376
|
+
readRecords(
|
|
377
|
+
file,
|
|
378
|
+
limits.recordBytes,
|
|
379
|
+
(line, lineNumber) => {
|
|
380
|
+
if (lineNumber === 1) {
|
|
381
|
+
let raw;
|
|
382
|
+
try {
|
|
383
|
+
raw = JSON.parse(line || '{}');
|
|
384
|
+
} catch {
|
|
385
|
+
throw new InvalidSessionError('invalid-json', 'Invalid session header JSON');
|
|
386
|
+
}
|
|
387
|
+
header = {
|
|
388
|
+
type: raw?.type,
|
|
389
|
+
id: raw?.id,
|
|
390
|
+
cwd: typeof raw?.cwd === 'string' ? raw.cwd : undefined,
|
|
391
|
+
};
|
|
392
|
+
if (header?.type !== 'session' || typeof header.id !== 'string' || !header.id.trim())
|
|
393
|
+
throw new InvalidSessionError('invalid-identity', `Invalid session header in ${file}`);
|
|
394
|
+
bounded(header.id);
|
|
395
|
+
if (typeof header.cwd === 'string') bounded(header.cwd, 16 * 1024);
|
|
396
|
+
bytes += COMPACT_HEADER_BYTES + stringBytes(header.id) + stringBytes(header.cwd);
|
|
397
|
+
if (bytes > limits.sourceBytes)
|
|
398
|
+
throw new InvalidSessionError(
|
|
399
|
+
'retained-limit',
|
|
400
|
+
'Session retained text/metadata limit exceeded',
|
|
401
|
+
);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (!line.trim()) return;
|
|
405
|
+
let e: Entry;
|
|
406
|
+
try {
|
|
407
|
+
e = JSON.parse(line) as Entry;
|
|
408
|
+
} catch {
|
|
409
|
+
throw new InvalidSessionError('invalid-json', `Invalid JSON at ${file}:${lineNumber}`);
|
|
410
|
+
}
|
|
411
|
+
if (
|
|
412
|
+
!e ||
|
|
413
|
+
typeof e.id !== 'string' ||
|
|
414
|
+
!e.id ||
|
|
415
|
+
typeof e.type !== 'string' ||
|
|
416
|
+
entries.has(e.id) ||
|
|
417
|
+
!(e.parentId === null || entries.has(e.parentId))
|
|
418
|
+
)
|
|
419
|
+
throw new InvalidSessionError(
|
|
420
|
+
'invalid-tree',
|
|
421
|
+
`Invalid session tree at ${file}:${lineNumber}`,
|
|
422
|
+
);
|
|
423
|
+
if (entries.size >= limits.sourceEntries)
|
|
424
|
+
throw new InvalidSessionError('retained-limit', 'Session entry limit exceeded');
|
|
425
|
+
const compact: Entry = {
|
|
426
|
+
id: bounded(e.id),
|
|
427
|
+
parentId: e.parentId,
|
|
428
|
+
type: bounded(e.type),
|
|
429
|
+
timestamp: bounded(timestampText(e.timestamp)),
|
|
320
430
|
};
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
if (
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
entries.
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
parentId: e.parentId,
|
|
349
|
-
type: bounded(e.type),
|
|
350
|
-
timestamp: bounded(timestampText(e.timestamp)),
|
|
351
|
-
};
|
|
352
|
-
const projectText = (content: unknown) => {
|
|
353
|
-
const text = visibleText(content, limits.sourceTextBytes - textBytes);
|
|
354
|
-
textBytes += Buffer.byteLength(text);
|
|
355
|
-
return text;
|
|
356
|
-
};
|
|
357
|
-
if (e.type === 'message' && (e.message?.role === 'user' || e.message?.role === 'assistant'))
|
|
358
|
-
compact.message = { role: e.message.role, content: projectText(e.message.content) };
|
|
359
|
-
if (e.type === 'context_edit') {
|
|
360
|
-
if (typeof e.targetId === 'string') compact.targetId = bounded(e.targetId);
|
|
361
|
-
compact.replacement =
|
|
362
|
-
e.replacement === null || e.replacement === undefined
|
|
363
|
-
? null
|
|
364
|
-
: { content: projectText(e.replacement.content) };
|
|
365
|
-
}
|
|
366
|
-
bytes += compactEntryBytes(compact);
|
|
367
|
-
if (bytes > limits.sourceBytes) throw Error('Session retained text/metadata limit exceeded');
|
|
368
|
-
entries.set(compact.id, compact);
|
|
369
|
-
depths.set(compact.id, (compact.parentId === null ? 0 : depths.get(compact.parentId)!) + 1);
|
|
370
|
-
if (compact.parentId) leaves.delete(compact.parentId);
|
|
371
|
-
leaves.add(compact.id);
|
|
372
|
-
});
|
|
431
|
+
const projectText = (content: unknown) => {
|
|
432
|
+
const text = visibleText(content, limits.sourceTextBytes - textBytes);
|
|
433
|
+
textBytes += Buffer.byteLength(text);
|
|
434
|
+
return text;
|
|
435
|
+
};
|
|
436
|
+
if (e.type === 'message' && (e.message?.role === 'user' || e.message?.role === 'assistant'))
|
|
437
|
+
compact.message = { role: e.message.role, content: projectText(e.message.content) };
|
|
438
|
+
if (e.type === 'context_edit') {
|
|
439
|
+
if (typeof e.targetId === 'string') compact.targetId = bounded(e.targetId);
|
|
440
|
+
compact.replacement =
|
|
441
|
+
e.replacement === null || e.replacement === undefined
|
|
442
|
+
? null
|
|
443
|
+
: { content: projectText(e.replacement.content) };
|
|
444
|
+
}
|
|
445
|
+
bytes += compactEntryBytes(compact);
|
|
446
|
+
if (bytes > limits.sourceBytes)
|
|
447
|
+
throw new InvalidSessionError(
|
|
448
|
+
'retained-limit',
|
|
449
|
+
'Session retained text/metadata limit exceeded',
|
|
450
|
+
);
|
|
451
|
+
entries.set(compact.id, compact);
|
|
452
|
+
depths.set(compact.id, (compact.parentId === null ? 0 : depths.get(compact.parentId)!) + 1);
|
|
453
|
+
if (compact.parentId) leaves.delete(compact.parentId);
|
|
454
|
+
leaves.add(compact.id);
|
|
455
|
+
},
|
|
456
|
+
prefix,
|
|
457
|
+
);
|
|
373
458
|
if (header?.type !== 'session' || typeof header.id !== 'string' || header.id.trim() === '')
|
|
374
|
-
throw
|
|
459
|
+
throw new InvalidSessionError('invalid-identity', `Invalid session header in ${file}`);
|
|
375
460
|
const branchEntries = [...leaves].reduce((sum, id) => sum + depths.get(id)!, 0);
|
|
376
461
|
if (leaves.size > limits.sourceBranches || branchEntries * 3 > limits.sourceBranchEntries)
|
|
377
|
-
throw
|
|
462
|
+
throw new InvalidSessionError('retained-limit', 'Session branch/evidence limit exceeded');
|
|
378
463
|
const tips: Tip[] = [...leaves].map((entryId) => ({
|
|
379
464
|
file: resolve(file),
|
|
380
465
|
sessionId: header.id as string,
|
|
@@ -399,6 +484,7 @@ export function branchEvidence(
|
|
|
399
484
|
tree: SessionTree,
|
|
400
485
|
tip: Tip,
|
|
401
486
|
reviewedThrough: string | null = null,
|
|
487
|
+
budget?: ReviewBudget,
|
|
402
488
|
): Evidence[] {
|
|
403
489
|
if (tip.sessionId !== tree.sessionId || !tree.entries.has(tip.entryId))
|
|
404
490
|
throw Error('Unknown review boundary');
|
|
@@ -406,6 +492,7 @@ export function branchEvidence(
|
|
|
406
492
|
const edits = new Map<string, Entry>();
|
|
407
493
|
let id: string | null = tip.entryId;
|
|
408
494
|
while (id !== null) {
|
|
495
|
+
budget?.visit(tree);
|
|
409
496
|
const e: Entry = tree.entries.get(id)!;
|
|
410
497
|
id = e.parentId;
|
|
411
498
|
if (e.type === 'context_edit' && e.targetId && !edits.has(e.targetId)) edits.set(e.targetId, e);
|
|
@@ -504,7 +591,6 @@ export function prepareReview(
|
|
|
504
591
|
);
|
|
505
592
|
continue;
|
|
506
593
|
}
|
|
507
|
-
budget.review(tree);
|
|
508
594
|
const boundaries = new Map<string, Checkpoint>();
|
|
509
595
|
for (const tip of reviewed) {
|
|
510
596
|
if (tip.sessionId !== source.sessionId) continue;
|
|
@@ -525,6 +611,7 @@ export function prepareReview(
|
|
|
525
611
|
let ancestorId: string | null = tip.entryId;
|
|
526
612
|
let ancestor: Checkpoint | undefined;
|
|
527
613
|
while (ancestorId !== null) {
|
|
614
|
+
budget.visit(tree);
|
|
528
615
|
ancestor = boundaries.get(ancestorId);
|
|
529
616
|
if (ancestor) break;
|
|
530
617
|
const entry = tree.entries.get(ancestorId);
|
|
@@ -535,13 +622,18 @@ export function prepareReview(
|
|
|
535
622
|
const effectiveSince = checkpointSince(ancestor, normalizedSource, requestedSince);
|
|
536
623
|
const previous = new Map<string, string | null>();
|
|
537
624
|
if (ancestor) {
|
|
538
|
-
for (const item of branchEvidence(
|
|
625
|
+
for (const item of branchEvidence(
|
|
626
|
+
tree,
|
|
627
|
+
{ ...tip, entryId: ancestor.entryId },
|
|
628
|
+
null,
|
|
629
|
+
budget,
|
|
630
|
+
)) {
|
|
539
631
|
if (timestampMillis(item.timestamp) === null) warnUnknown(source, item);
|
|
540
632
|
if (isEligible(item, ancestor.since)) previous.set(selectionKey(item), item.editId);
|
|
541
633
|
}
|
|
542
634
|
}
|
|
543
635
|
|
|
544
|
-
const branch = branchEvidence(tree, tip, ancestor?.entryId ?? null);
|
|
636
|
+
const branch = branchEvidence(tree, tip, ancestor?.entryId ?? null, budget);
|
|
545
637
|
for (const item of branch) {
|
|
546
638
|
if (timestampMillis(item.timestamp) === null) warnUnknown(source, item);
|
|
547
639
|
if (!isEligible(item, effectiveSince)) continue;
|
|
@@ -591,3 +683,155 @@ export function prepareReview(
|
|
|
591
683
|
coverageChanged: checkpoints.length > 0 || sourceDefaults.length > 0,
|
|
592
684
|
};
|
|
593
685
|
}
|
|
686
|
+
|
|
687
|
+
function ancestor(tree: SessionTree, before: string, after: string, budget: ReviewBudget): boolean {
|
|
688
|
+
let id: string | null = after;
|
|
689
|
+
while (id !== null) {
|
|
690
|
+
budget.visit(tree);
|
|
691
|
+
if (id === before) return true;
|
|
692
|
+
const entry = tree.entries.get(id);
|
|
693
|
+
if (!entry) throw Error(`Ancestry unavailable: ${id}`);
|
|
694
|
+
id = entry.parentId;
|
|
695
|
+
}
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
const version = (item: Evidence) => JSON.stringify([item.entryId, item.editId]);
|
|
699
|
+
|
|
700
|
+
type HistoricalFailureCategory =
|
|
701
|
+
| InvalidSessionCategory
|
|
702
|
+
| 'snapshot-unavailable'
|
|
703
|
+
| 'live-proof-unavailable'
|
|
704
|
+
| 'checkpoint-unavailable'
|
|
705
|
+
| 'invalid-checkpoint-date'
|
|
706
|
+
| 'coverage-limit'
|
|
707
|
+
| 'review-context';
|
|
708
|
+
export type HistoricalReviewResult =
|
|
709
|
+
| {
|
|
710
|
+
review: null;
|
|
711
|
+
diagnostic: string;
|
|
712
|
+
category: HistoricalFailureCategory;
|
|
713
|
+
retryEligible: boolean;
|
|
714
|
+
}
|
|
715
|
+
| { review: PreparedReview; diagnostic: null };
|
|
716
|
+
export function prepareHistoricalReview(
|
|
717
|
+
source: Source,
|
|
718
|
+
snapshotFile: string,
|
|
719
|
+
reviewed: readonly Checkpoint[],
|
|
720
|
+
options?: ReviewOptions,
|
|
721
|
+
liveSourceFile = source.file,
|
|
722
|
+
budget = new ReviewBudget(),
|
|
723
|
+
): HistoricalReviewResult {
|
|
724
|
+
let phase: 'snapshot' | 'coverage' | 'extraction' = 'snapshot';
|
|
725
|
+
let category: HistoricalFailureCategory = 'snapshot-unavailable';
|
|
726
|
+
let diagnostic = 'Historical snapshot unavailable';
|
|
727
|
+
try {
|
|
728
|
+
const saved = readSession(snapshotFile, budget.limits);
|
|
729
|
+
if (saved.sessionId !== source.sessionId)
|
|
730
|
+
throw new InvalidSessionError('invalid-identity', 'Session identity differs from snapshot');
|
|
731
|
+
const tree = { ...saved, tips: saved.tips.map((tip) => ({ ...tip, file: source.file })) };
|
|
732
|
+
budget.retain(tree);
|
|
733
|
+
const boundaries = reviewed.filter((cp) => cp.sessionId === source.sessionId);
|
|
734
|
+
let coverageTree = tree;
|
|
735
|
+
phase = 'coverage';
|
|
736
|
+
category = 'live-proof-unavailable';
|
|
737
|
+
diagnostic = 'Historical live coverage proof unavailable';
|
|
738
|
+
if (boundaries.some((cp) => !tree.entries.has(cp.entryId))) {
|
|
739
|
+
// The current enrollment proves coverage only. Evidence and references keep
|
|
740
|
+
// the accepted historical pathname and the immutable saved text.
|
|
741
|
+
coverageTree = readSession(liveSourceFile, budget.limits, snapshotFile);
|
|
742
|
+
budget.retain(coverageTree);
|
|
743
|
+
if (coverageTree.sessionId !== source.sessionId)
|
|
744
|
+
throw Error('Live coverage identity differs');
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Resolve all receipts before selection, charging each visited ancestor,
|
|
748
|
+
// not the size of a tree that a shallow checkpoint never traverses.
|
|
749
|
+
const receipts = boundaries.map((cp) => {
|
|
750
|
+
category = 'checkpoint-unavailable';
|
|
751
|
+
diagnostic = 'Historical committed checkpoint unavailable';
|
|
752
|
+
if (!coverageTree.entries.has(cp.entryId)) throw Error(diagnostic);
|
|
753
|
+
category = 'invalid-checkpoint-date';
|
|
754
|
+
diagnostic = 'Historical checkpoint date invalid';
|
|
755
|
+
if (cp.since !== null && !Number.isFinite(Date.parse(cp.since))) throw Error(diagnostic);
|
|
756
|
+
return {
|
|
757
|
+
checkpoint: cp,
|
|
758
|
+
versions: new Set(
|
|
759
|
+
branchEvidence(coverageTree, cp, null, budget)
|
|
760
|
+
.filter((item) => isEligible(item, cp.since))
|
|
761
|
+
.map(version),
|
|
762
|
+
),
|
|
763
|
+
};
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
// Reuse current cutoff/default semantics for endpoints inside the preserved
|
|
767
|
+
// tree. All other endpoints have already been mapped, not silently ignored.
|
|
768
|
+
phase = 'extraction';
|
|
769
|
+
category = 'review-context';
|
|
770
|
+
diagnostic = 'Historical review context unavailable';
|
|
771
|
+
const review = prepareReview(
|
|
772
|
+
[source],
|
|
773
|
+
boundaries.filter((cp) => tree.entries.has(cp.entryId)),
|
|
774
|
+
options,
|
|
775
|
+
[{ source, tree }],
|
|
776
|
+
budget,
|
|
777
|
+
);
|
|
778
|
+
if (review.incomplete) throw Error(diagnostic);
|
|
779
|
+
const remaining = new Map<string, Set<string>>();
|
|
780
|
+
for (const item of review.evidence) {
|
|
781
|
+
let versions = remaining.get(item.branchId);
|
|
782
|
+
if (!versions) remaining.set(item.branchId, (versions = new Set()));
|
|
783
|
+
versions.add(version(item));
|
|
784
|
+
}
|
|
785
|
+
for (const [branchId, versions] of remaining) {
|
|
786
|
+
for (const receipt of receipts) {
|
|
787
|
+
// Compare a checkpoint/branch pair once, and only if the receipt has
|
|
788
|
+
// a selected version. Shallow receipts must not trigger deep walks.
|
|
789
|
+
let matches = false;
|
|
790
|
+
for (const candidate of receipt.versions) {
|
|
791
|
+
if (versions.has(candidate)) {
|
|
792
|
+
matches = true;
|
|
793
|
+
break;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
if (!matches) continue;
|
|
797
|
+
if (
|
|
798
|
+
ancestor(coverageTree, receipt.checkpoint.entryId, branchId, budget) ||
|
|
799
|
+
ancestor(coverageTree, branchId, receipt.checkpoint.entryId, budget)
|
|
800
|
+
) {
|
|
801
|
+
for (const covered of receipt.versions) versions.delete(covered);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
review.evidence = review.evidence.filter((item) =>
|
|
806
|
+
remaining.get(item.branchId)!.has(version(item)),
|
|
807
|
+
);
|
|
808
|
+
if (!review.evidence.length) {
|
|
809
|
+
// Match automatic capture: no evidence means no manufactured coverage,
|
|
810
|
+
// including when a manual seed would have staged a default-only change.
|
|
811
|
+
review.tips = [];
|
|
812
|
+
review.checkpoints = [];
|
|
813
|
+
review.sourceDefaults = [];
|
|
814
|
+
review.successfulSources = [];
|
|
815
|
+
review.coverageChanged = false;
|
|
816
|
+
}
|
|
817
|
+
return { diagnostic: null, review };
|
|
818
|
+
} catch (error) {
|
|
819
|
+
// Invalid input, limits and unknown failures require deliberate retry.
|
|
820
|
+
// Only recognized temporary filesystem interruptions can recover automatically.
|
|
821
|
+
const code = (error as NodeJS.ErrnoException | null)?.code;
|
|
822
|
+
const retryEligible = ['EAGAIN', 'EBUSY', 'EINTR', 'ETIMEDOUT'].includes(code ?? '');
|
|
823
|
+
if (phase === 'snapshot' && error instanceof InvalidSessionError) {
|
|
824
|
+
category = error.category;
|
|
825
|
+
diagnostic = `Historical snapshot ${category}`;
|
|
826
|
+
if (category === 'invalid-identity') diagnostic += ': Session identity differs from snapshot';
|
|
827
|
+
} else if (phase === 'coverage' && error instanceof InvalidSessionError) {
|
|
828
|
+
category = 'live-proof-unavailable';
|
|
829
|
+
diagnostic = `Historical live coverage proof ${error.category}`;
|
|
830
|
+
} else if (error instanceof ReviewLimitError) {
|
|
831
|
+
category = phase === 'snapshot' ? 'retained-limit' : 'coverage-limit';
|
|
832
|
+
diagnostic = `Historical ${phase} ancestry/snapshot limit exceeded`;
|
|
833
|
+
}
|
|
834
|
+
if (typeof code === 'string' && /^E[A-Z0-9]{1,24}$/.test(code)) diagnostic += ` (${code})`;
|
|
835
|
+
return { review: null, diagnostic, category, retryEligible };
|
|
836
|
+
}
|
|
837
|
+
}
|