@robhowley/pi-remembrancer 0.2.0 → 0.3.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/README.md +36 -24
- package/extensions/remembrancer/checkpoints.ts +138 -26
- package/extensions/remembrancer/discovery.ts +270 -0
- package/extensions/remembrancer/evidence.ts +499 -62
- package/extensions/remembrancer/index.ts +441 -31
- package/extensions/remembrancer/render.ts +421 -0
- package/extensions/remembrancer/warnings.ts +29 -0
- package/package.json +7 -4
- package/skills/remembrancer/SKILL.md +30 -10
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync, statSync } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { resolve } from 'node:path';
|
|
4
|
+
import { createWarning, type WarningRecord } from './warnings.js';
|
|
3
5
|
|
|
4
6
|
export type Tip = { file: string; sessionId: string; entryId: string };
|
|
7
|
+
export type Checkpoint = Tip & { since: string | null };
|
|
8
|
+
export type Source = Pick<Tip, 'sessionId' | 'file'> & { seedSince?: string | null };
|
|
9
|
+
export type SeedDefault = { sessionId: string; since: string };
|
|
5
10
|
export type Evidence = Tip & {
|
|
6
11
|
role: string;
|
|
7
12
|
text: string;
|
|
@@ -11,32 +16,322 @@ export type Evidence = Tip & {
|
|
|
11
16
|
reviewedThrough: string | null;
|
|
12
17
|
editId: string | null;
|
|
13
18
|
};
|
|
14
|
-
export type
|
|
19
|
+
export type ReviewOptions = {
|
|
20
|
+
requestedSince?: string | null;
|
|
21
|
+
seed?: string;
|
|
22
|
+
now?: Date | string | number;
|
|
23
|
+
};
|
|
24
|
+
export type PreparedReview = {
|
|
25
|
+
tips: Tip[];
|
|
26
|
+
checkpoints: Checkpoint[];
|
|
27
|
+
sourceDefaults: SeedDefault[];
|
|
28
|
+
evidence: Evidence[];
|
|
29
|
+
snapshots: SessionSnapshot[];
|
|
30
|
+
successfulSources: Source[];
|
|
31
|
+
warnings: WarningRecord[];
|
|
32
|
+
incomplete: boolean;
|
|
33
|
+
coverageChanged: boolean;
|
|
34
|
+
};
|
|
15
35
|
type Entry = {
|
|
16
36
|
id: string;
|
|
17
37
|
parentId: string | null;
|
|
18
38
|
type: string;
|
|
19
|
-
timestamp?:
|
|
39
|
+
timestamp?: unknown;
|
|
20
40
|
message?: { role?: string; content?: unknown };
|
|
21
41
|
targetId?: string;
|
|
22
42
|
replacement?: { content?: unknown } | null;
|
|
23
43
|
};
|
|
24
44
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
45
|
+
const DAY_MS = 86_400_000;
|
|
46
|
+
|
|
47
|
+
function timestampText(value: unknown): string {
|
|
48
|
+
return typeof value === 'string' ? value : '';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function timestampMillis(value: string): number | null {
|
|
52
|
+
if (!value) return null;
|
|
53
|
+
const milliseconds = Date.parse(value);
|
|
54
|
+
return Number.isFinite(milliseconds) ? milliseconds : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function absoluteTimestamp(value: string): string {
|
|
58
|
+
const milliseconds = timestampMillis(value);
|
|
59
|
+
if (milliseconds === null) throw new Error(`Invalid review timestamp: ${value}`);
|
|
60
|
+
return new Date(milliseconds).toISOString();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function earlierFinite(
|
|
64
|
+
existing: string | null | undefined,
|
|
65
|
+
requested: string | null,
|
|
66
|
+
): string | null {
|
|
67
|
+
if (requested === null) return existing ?? null;
|
|
68
|
+
if (existing === undefined || existing === null) return requested;
|
|
69
|
+
return existing < requested ? existing : requested;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function checkpointSince(
|
|
73
|
+
checkpoint: Checkpoint | undefined,
|
|
74
|
+
source: Source,
|
|
75
|
+
requested: string | null,
|
|
76
|
+
) {
|
|
77
|
+
if (checkpoint) {
|
|
78
|
+
if (checkpoint.since === null) return null;
|
|
79
|
+
return earlierFinite(checkpoint.since, requested);
|
|
80
|
+
}
|
|
81
|
+
return earlierFinite(source.seedSince, requested);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isEligible(item: Evidence, since: string | null): boolean {
|
|
85
|
+
if (since === null) return true;
|
|
86
|
+
const itemTime = timestampMillis(item.timestamp);
|
|
87
|
+
return itemTime === null || itemTime >= Date.parse(since);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function selectionKey(item: Evidence): string {
|
|
91
|
+
return `${item.entryId}\u0000${item.editId ?? ''}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sourceKey(source: Pick<Source, 'sessionId' | 'file'>): string {
|
|
95
|
+
return `${source.sessionId}\u0000${resolve(source.file)}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function normalizedOptions(options?: ReviewOptions | string): { requestedSince: string | null } {
|
|
99
|
+
if (typeof options === 'string') return { requestedSince: absoluteTimestamp(options) };
|
|
100
|
+
if (!options) return { requestedSince: null };
|
|
101
|
+
if (options.seed !== undefined && options.requestedSince !== undefined)
|
|
102
|
+
throw new Error('Use either seed or requestedSince, not both');
|
|
103
|
+
if (options.seed !== undefined)
|
|
104
|
+
return { requestedSince: resolveSeedSince(options.seed, options.now ?? new Date()) };
|
|
105
|
+
return {
|
|
106
|
+
requestedSince:
|
|
107
|
+
options.requestedSince === undefined || options.requestedSince === null
|
|
108
|
+
? null
|
|
109
|
+
: absoluteTimestamp(options.requestedSince),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function resolveSeedSince(
|
|
114
|
+
duration: string,
|
|
115
|
+
now: Date | string | number = new Date(),
|
|
116
|
+
): string {
|
|
117
|
+
const match = /^([1-9]\d*)d$/.exec(duration);
|
|
118
|
+
if (!match) throw new Error('Seed duration must be a positive integer such as 14d');
|
|
119
|
+
const days = Number(match[1]);
|
|
120
|
+
if (!Number.isSafeInteger(days) || days > Math.floor(Number.MAX_SAFE_INTEGER / DAY_MS))
|
|
121
|
+
throw new Error('Seed duration is out of range');
|
|
122
|
+
|
|
123
|
+
const nowMilliseconds =
|
|
124
|
+
now instanceof Date ? now.getTime() : typeof now === 'number' ? now : Date.parse(now);
|
|
125
|
+
if (!Number.isFinite(nowMilliseconds)) throw new Error('Seed start requires a valid UTC clock');
|
|
126
|
+
const sinceMilliseconds = nowMilliseconds - days * DAY_MS;
|
|
127
|
+
if (!Number.isFinite(sinceMilliseconds)) throw new Error('Seed duration is out of range');
|
|
128
|
+
const since = new Date(sinceMilliseconds);
|
|
129
|
+
if (Number.isNaN(since.getTime())) throw new Error('Seed duration is out of range');
|
|
130
|
+
return since.toISOString();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Internal limits, injectable only for isolated tests. Text and compact-data
|
|
134
|
+
// limits use UTF-8 string bytes plus small fixed slots; raw payloads exist for
|
|
135
|
+
// only one record at a time.
|
|
136
|
+
export const REVIEW_LIMITS = {
|
|
137
|
+
recordBytes: 32 * 1024 * 1024,
|
|
138
|
+
sourceEntries: 20_000,
|
|
139
|
+
sourceBytes: 8 * 1024 * 1024,
|
|
140
|
+
sourceTextBytes: 4 * 1024 * 1024,
|
|
141
|
+
sourceBranches: 512,
|
|
142
|
+
sourceBranchEntries: 100_000,
|
|
143
|
+
totalEntries: 300_000,
|
|
144
|
+
totalBytes: 64 * 1024 * 1024,
|
|
145
|
+
totalTextBytes: 32 * 1024 * 1024,
|
|
146
|
+
totalBranchEntries: 1_000_000,
|
|
147
|
+
sources: 2048,
|
|
148
|
+
};
|
|
149
|
+
export type ReviewLimits = typeof REVIEW_LIMITS;
|
|
150
|
+
export class ReviewLimitError extends Error {}
|
|
151
|
+
|
|
152
|
+
const COMPACT_HEADER_BYTES = 32;
|
|
153
|
+
const COMPACT_ENTRY_BYTES = 64;
|
|
154
|
+
|
|
155
|
+
function stringBytes(value: unknown): number {
|
|
156
|
+
return typeof value === 'string' ? Buffer.byteLength(value) : 0;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function compactEntryBytes(entry: Entry): number {
|
|
160
|
+
let bytes =
|
|
161
|
+
COMPACT_ENTRY_BYTES +
|
|
162
|
+
stringBytes(entry.id) +
|
|
163
|
+
stringBytes(entry.parentId) +
|
|
164
|
+
stringBytes(entry.type) +
|
|
165
|
+
stringBytes(entry.timestamp);
|
|
166
|
+
if (entry.message)
|
|
167
|
+
bytes +=
|
|
168
|
+
COMPACT_ENTRY_BYTES + stringBytes(entry.message.role) + stringBytes(entry.message.content);
|
|
169
|
+
if (entry.targetId) bytes += COMPACT_ENTRY_BYTES + stringBytes(entry.targetId);
|
|
170
|
+
if (entry.replacement) bytes += COMPACT_ENTRY_BYTES + stringBytes(entry.replacement.content);
|
|
171
|
+
return bytes;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export class ReviewBudget {
|
|
175
|
+
readonly limits: ReviewLimits;
|
|
176
|
+
private trees = new WeakSet<SessionTree>();
|
|
177
|
+
private sourcePaths = new Set<string>();
|
|
178
|
+
private entries = 0;
|
|
179
|
+
private bytes = 0;
|
|
180
|
+
private textBytes = 0;
|
|
181
|
+
private branches = 0;
|
|
182
|
+
constructor(limits: Partial<ReviewLimits> = {}) {
|
|
183
|
+
this.limits = { ...REVIEW_LIMITS, ...limits };
|
|
184
|
+
}
|
|
185
|
+
reserveSource(file: string) {
|
|
186
|
+
const path = resolve(file);
|
|
187
|
+
if (this.sourcePaths.has(path)) return;
|
|
188
|
+
if (this.sourcePaths.size >= this.limits.sources)
|
|
189
|
+
throw new ReviewLimitError('Aggregate review source limit exceeded');
|
|
190
|
+
this.sourcePaths.add(path);
|
|
191
|
+
}
|
|
192
|
+
retain(tree: SessionTree) {
|
|
193
|
+
if (this.trees.has(tree)) return;
|
|
194
|
+
this.entries += tree.entries.size;
|
|
195
|
+
this.bytes += tree.bytes;
|
|
196
|
+
this.textBytes += tree.textBytes;
|
|
197
|
+
if (
|
|
198
|
+
this.entries > this.limits.totalEntries ||
|
|
199
|
+
this.bytes > this.limits.totalBytes ||
|
|
200
|
+
this.textBytes > this.limits.totalTextBytes
|
|
201
|
+
)
|
|
202
|
+
throw new ReviewLimitError('Aggregate review snapshot limit exceeded');
|
|
203
|
+
this.trees.add(tree);
|
|
204
|
+
}
|
|
205
|
+
review(tree: SessionTree) {
|
|
206
|
+
// Three walks cover ancestor lookup, previous evidence and current evidence.
|
|
207
|
+
// This also bounds descriptors, selection keys and unknown-time warnings.
|
|
208
|
+
this.branches += tree.branchEntries * 3;
|
|
209
|
+
if (this.branches > this.limits.totalBranchEntries)
|
|
210
|
+
throw new ReviewLimitError('Aggregate review branch/evidence limit exceeded');
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function visibleText(content: unknown, maxBytes = Number.POSITIVE_INFINITY): string {
|
|
215
|
+
if (typeof content === 'string') {
|
|
216
|
+
if (Buffer.byteLength(content) > maxBytes)
|
|
217
|
+
throw Error('Session retained text/metadata limit exceeded');
|
|
218
|
+
return content;
|
|
219
|
+
}
|
|
220
|
+
if (!Array.isArray(content)) return '';
|
|
221
|
+
|
|
222
|
+
const texts: string[] = [];
|
|
223
|
+
let bytes = 0;
|
|
224
|
+
for (const block of content) {
|
|
225
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue;
|
|
226
|
+
bytes += Buffer.byteLength(block.text) + (texts.length > 0 ? 1 : 0);
|
|
227
|
+
if (bytes > maxBytes) throw Error('Session retained text/metadata limit exceeded');
|
|
228
|
+
texts.push(block.text);
|
|
229
|
+
}
|
|
230
|
+
return texts.join('\n');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Read only the opening extent. Verify its bytes again without retaining them. */
|
|
234
|
+
function readRecords(file: string, limit: number, consume: (line: string, number: number) => void) {
|
|
235
|
+
const fd = openSync(file, 'r');
|
|
236
|
+
try {
|
|
237
|
+
const initial = fstatSync(fd);
|
|
238
|
+
if (!initial.isFile()) throw Error('Session source is not a regular file');
|
|
239
|
+
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
240
|
+
let parts: Buffer[] = [];
|
|
241
|
+
let length = 0;
|
|
242
|
+
let lineNumber = 1;
|
|
243
|
+
const hash = createHash('sha256');
|
|
244
|
+
for (let position = 0; position < initial.size; ) {
|
|
245
|
+
const count = readSync(
|
|
246
|
+
fd,
|
|
247
|
+
chunk,
|
|
248
|
+
0,
|
|
249
|
+
Math.min(chunk.length, initial.size - position),
|
|
250
|
+
position,
|
|
251
|
+
);
|
|
252
|
+
if (!count) throw Error('Session source truncated during read');
|
|
253
|
+
position += count;
|
|
254
|
+
hash.update(chunk.subarray(0, count));
|
|
255
|
+
let start = 0;
|
|
256
|
+
while (start < count) {
|
|
257
|
+
const newline = chunk.indexOf(10, start);
|
|
258
|
+
const end = newline < 0 || newline >= count ? count : newline;
|
|
259
|
+
const size = end - start;
|
|
260
|
+
if (length + size > limit) throw Error('Session raw record limit exceeded');
|
|
261
|
+
if (size) parts.push(Buffer.from(chunk.subarray(start, end)));
|
|
262
|
+
length += size;
|
|
263
|
+
if (end < count) {
|
|
264
|
+
consume(Buffer.concat(parts, length).toString('utf8'), lineNumber++);
|
|
265
|
+
parts = [];
|
|
266
|
+
length = 0;
|
|
267
|
+
}
|
|
268
|
+
start = end + 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (length) consume(Buffer.concat(parts, length).toString('utf8'), lineNumber);
|
|
272
|
+
parts = [];
|
|
273
|
+
const verify = createHash('sha256');
|
|
274
|
+
for (let position = 0; position < initial.size; ) {
|
|
275
|
+
const count = readSync(
|
|
276
|
+
fd,
|
|
277
|
+
chunk,
|
|
278
|
+
0,
|
|
279
|
+
Math.min(chunk.length, initial.size - position),
|
|
280
|
+
position,
|
|
281
|
+
);
|
|
282
|
+
if (!count) throw Error('Session source truncated during verification');
|
|
283
|
+
verify.update(chunk.subarray(0, count));
|
|
284
|
+
position += count;
|
|
285
|
+
}
|
|
286
|
+
const final = fstatSync(fd);
|
|
287
|
+
const path = statSync(file);
|
|
288
|
+
if (
|
|
289
|
+
final.size < initial.size ||
|
|
290
|
+
path.dev !== initial.dev ||
|
|
291
|
+
path.ino !== initial.ino ||
|
|
292
|
+
hash.digest('hex') !== verify.digest('hex') ||
|
|
293
|
+
(final.size === initial.size &&
|
|
294
|
+
(final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs))
|
|
295
|
+
)
|
|
296
|
+
throw Error('Session source changed during read');
|
|
297
|
+
} finally {
|
|
298
|
+
closeSync(fd);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function readSession(file: string, limits: ReviewLimits = REVIEW_LIMITS) {
|
|
303
|
+
let header: { type?: string; id?: unknown; cwd?: unknown } = {};
|
|
31
304
|
const entries = new Map<string, Entry>();
|
|
32
305
|
const leaves = new Set<string>();
|
|
33
|
-
|
|
34
|
-
|
|
306
|
+
const depths = new Map<string, number>();
|
|
307
|
+
let bytes = 0;
|
|
308
|
+
let textBytes = 0;
|
|
309
|
+
const bounded = (value: string, max = 256) => {
|
|
310
|
+
if (Buffer.byteLength(value) > max) throw Error('Session metadata limit exceeded');
|
|
311
|
+
return value;
|
|
312
|
+
};
|
|
313
|
+
readRecords(file, limits.recordBytes, (line, lineNumber) => {
|
|
314
|
+
if (lineNumber === 1) {
|
|
315
|
+
const raw = JSON.parse(line || '{}');
|
|
316
|
+
header = {
|
|
317
|
+
type: raw?.type,
|
|
318
|
+
id: raw?.id,
|
|
319
|
+
cwd: typeof raw?.cwd === 'string' ? raw.cwd : undefined,
|
|
320
|
+
};
|
|
321
|
+
if (header?.type !== 'session' || typeof header.id !== 'string' || !header.id.trim())
|
|
322
|
+
throw Error(`Invalid session header in ${file}`);
|
|
323
|
+
bounded(header.id);
|
|
324
|
+
if (typeof header.cwd === 'string') bounded(header.cwd, 16 * 1024);
|
|
325
|
+
bytes += COMPACT_HEADER_BYTES + stringBytes(header.id) + stringBytes(header.cwd);
|
|
326
|
+
if (bytes > limits.sourceBytes) throw Error('Session retained text/metadata limit exceeded');
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (!line.trim()) return;
|
|
35
330
|
let e: Entry;
|
|
36
331
|
try {
|
|
37
|
-
e = JSON.parse(line);
|
|
38
|
-
} catch (
|
|
39
|
-
throw Error(`Invalid JSON at ${file}:${
|
|
332
|
+
e = JSON.parse(line) as Entry;
|
|
333
|
+
} catch (error) {
|
|
334
|
+
throw Error(`Invalid JSON at ${file}:${lineNumber}`, { cause: error });
|
|
40
335
|
}
|
|
41
336
|
if (
|
|
42
337
|
!e ||
|
|
@@ -46,14 +341,43 @@ export function readSession(file: string) {
|
|
|
46
341
|
entries.has(e.id) ||
|
|
47
342
|
!(e.parentId === null || entries.has(e.parentId))
|
|
48
343
|
)
|
|
49
|
-
throw Error(`Invalid session tree at ${file}:${
|
|
50
|
-
entries.
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
344
|
+
throw Error(`Invalid session tree at ${file}:${lineNumber}`);
|
|
345
|
+
if (entries.size >= limits.sourceEntries) throw Error('Session entry limit exceeded');
|
|
346
|
+
const compact: Entry = {
|
|
347
|
+
id: bounded(e.id),
|
|
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
|
+
});
|
|
373
|
+
if (header?.type !== 'session' || typeof header.id !== 'string' || header.id.trim() === '')
|
|
374
|
+
throw Error(`Invalid session header in ${file}`);
|
|
375
|
+
const branchEntries = [...leaves].reduce((sum, id) => sum + depths.get(id)!, 0);
|
|
376
|
+
if (leaves.size > limits.sourceBranches || branchEntries * 3 > limits.sourceBranchEntries)
|
|
377
|
+
throw Error('Session branch/evidence limit exceeded');
|
|
54
378
|
const tips: Tip[] = [...leaves].map((entryId) => ({
|
|
55
379
|
file: resolve(file),
|
|
56
|
-
sessionId: header.id,
|
|
380
|
+
sessionId: header.id as string,
|
|
57
381
|
entryId,
|
|
58
382
|
}));
|
|
59
383
|
return {
|
|
@@ -61,10 +385,14 @@ export function readSession(file: string) {
|
|
|
61
385
|
cwd: typeof header.cwd === 'string' && header.cwd.trim() ? String(header.cwd) : '(unknown)',
|
|
62
386
|
entries,
|
|
63
387
|
tips,
|
|
388
|
+
bytes,
|
|
389
|
+
textBytes,
|
|
390
|
+
branchEntries,
|
|
64
391
|
};
|
|
65
392
|
}
|
|
66
393
|
|
|
67
394
|
export type SessionTree = ReturnType<typeof readSession>;
|
|
395
|
+
export type SessionSnapshot = { source: Source; tree: SessionTree };
|
|
68
396
|
|
|
69
397
|
/** Include only visible user and assistant text on the immutable path to tip. */
|
|
70
398
|
export function branchEvidence(
|
|
@@ -86,15 +414,7 @@ export function branchEvidence(
|
|
|
86
414
|
const role = e.message?.role;
|
|
87
415
|
if (e.type !== 'message' || (role !== 'user' && role !== 'assistant')) continue;
|
|
88
416
|
const content = edit ? edit.replacement?.content : e.message?.content;
|
|
89
|
-
const text =
|
|
90
|
-
typeof content === 'string'
|
|
91
|
-
? content
|
|
92
|
-
: Array.isArray(content)
|
|
93
|
-
? content
|
|
94
|
-
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
95
|
-
.map((b) => b.text)
|
|
96
|
-
.join('\n')
|
|
97
|
-
: '';
|
|
417
|
+
const text = visibleText(content);
|
|
98
418
|
if (!text) continue;
|
|
99
419
|
evidence.push({
|
|
100
420
|
...tip,
|
|
@@ -102,7 +422,7 @@ export function branchEvidence(
|
|
|
102
422
|
role,
|
|
103
423
|
text,
|
|
104
424
|
cwd: tree.cwd,
|
|
105
|
-
timestamp:
|
|
425
|
+
timestamp: timestampText(edit ? edit.timestamp : e.timestamp),
|
|
106
426
|
branchId: tip.entryId,
|
|
107
427
|
reviewedThrough,
|
|
108
428
|
editId: edit?.id ?? null,
|
|
@@ -111,46 +431,163 @@ export function branchEvidence(
|
|
|
111
431
|
return evidence.reverse();
|
|
112
432
|
}
|
|
113
433
|
|
|
114
|
-
/** Read each
|
|
115
|
-
export function prepareReview(
|
|
434
|
+
/** Read each source once, then freeze branch evidence and finish boundaries. */
|
|
435
|
+
export function prepareReview(
|
|
436
|
+
sources: readonly Source[],
|
|
437
|
+
reviewed: readonly (Tip | Checkpoint)[],
|
|
438
|
+
options?: ReviewOptions | string,
|
|
439
|
+
snapshots: readonly SessionSnapshot[] = [],
|
|
440
|
+
budget = new ReviewBudget(),
|
|
441
|
+
): PreparedReview {
|
|
442
|
+
const { requestedSince } = normalizedOptions(options);
|
|
116
443
|
const tips: Tip[] = [];
|
|
444
|
+
const checkpoints: Checkpoint[] = [];
|
|
445
|
+
const sourceDefaults: SeedDefault[] = [];
|
|
117
446
|
const evidence: Evidence[] = [];
|
|
118
|
-
const
|
|
447
|
+
const frozenSnapshots: SessionSnapshot[] = [];
|
|
448
|
+
const successfulSources: Source[] = [];
|
|
449
|
+
const warnings: WarningRecord[] = [];
|
|
450
|
+
let incomplete = false;
|
|
451
|
+
const warnedUnknown = new Set<string>();
|
|
452
|
+
|
|
453
|
+
const warnUnknown = (source: Source, item: Evidence) => {
|
|
454
|
+
const key = `${source.sessionId}\u0000${item.branchId}\u0000${selectionKey(item)}`;
|
|
455
|
+
if (warnedUnknown.has(key)) return;
|
|
456
|
+
warnedUnknown.add(key);
|
|
457
|
+
const reason = `selection timestamp unknown for ${item.entryId}${
|
|
458
|
+
item.editId ? ` (edit ${item.editId})` : ''
|
|
459
|
+
}`;
|
|
460
|
+
warnings.push(
|
|
461
|
+
createWarning(`${source.file}: ${reason}`, [source.file], reason, 'unknown-timestamp'),
|
|
462
|
+
);
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
const snapshotsBySource = new Map<string, SessionSnapshot>();
|
|
466
|
+
const treesByPath = new Map<string, SessionTree>();
|
|
467
|
+
for (const snapshot of snapshots) {
|
|
468
|
+
const path = resolve(snapshot.source.file);
|
|
469
|
+
const key = sourceKey(snapshot.source);
|
|
470
|
+
budget.reserveSource(path);
|
|
471
|
+
if (snapshotsBySource.has(key)) continue;
|
|
472
|
+
budget.retain(snapshot.tree);
|
|
473
|
+
snapshotsBySource.set(key, snapshot);
|
|
474
|
+
if (!treesByPath.has(path)) treesByPath.set(path, snapshot.tree);
|
|
475
|
+
}
|
|
476
|
+
const sourceKeys = new Set<string>();
|
|
119
477
|
for (const source of sources) {
|
|
478
|
+
const path = resolve(source.file);
|
|
479
|
+
const key = sourceKey(source);
|
|
480
|
+
if (sourceKeys.has(key)) continue;
|
|
481
|
+
sourceKeys.add(key);
|
|
482
|
+
budget.reserveSource(path);
|
|
120
483
|
try {
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
]),
|
|
141
|
-
);
|
|
142
|
-
// Separate leaves are alternatives. Repeat their shared context rather than
|
|
143
|
-
// flattening branches together or discovering ancestry in other files.
|
|
144
|
-
evidence.push(
|
|
145
|
-
...branchEvidence(tree, tip, ancestor).filter(
|
|
146
|
-
(item) => !previous.has(item.entryId) || previous.get(item.entryId) !== item.editId,
|
|
484
|
+
const sourceSince =
|
|
485
|
+
source.seedSince === undefined || source.seedSince === null
|
|
486
|
+
? null
|
|
487
|
+
: absoluteTimestamp(source.seedSince);
|
|
488
|
+
const normalizedSource = { ...source, seedSince: sourceSince };
|
|
489
|
+
const snapshot = snapshotsBySource.get(key);
|
|
490
|
+
const tree =
|
|
491
|
+
snapshot?.tree ?? treesByPath.get(path) ?? readSession(source.file, budget.limits);
|
|
492
|
+
budget.retain(tree);
|
|
493
|
+
if (!treesByPath.has(path)) treesByPath.set(path, tree);
|
|
494
|
+
if (tree.sessionId !== source.sessionId) {
|
|
495
|
+
const reason = 'Session header ID changed';
|
|
496
|
+
incomplete = true;
|
|
497
|
+
warnings.push(
|
|
498
|
+
createWarning(
|
|
499
|
+
`${source.file}: Error: ${reason}`,
|
|
500
|
+
[source.file],
|
|
501
|
+
reason,
|
|
502
|
+
'identity-ambiguity',
|
|
147
503
|
),
|
|
148
504
|
);
|
|
149
|
-
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
budget.review(tree);
|
|
508
|
+
const boundaries = new Map<string, Checkpoint>();
|
|
509
|
+
for (const tip of reviewed) {
|
|
510
|
+
if (tip.sessionId !== source.sessionId) continue;
|
|
511
|
+
const checkpoint: Checkpoint = {
|
|
512
|
+
...tip,
|
|
513
|
+
since: 'since' in tip ? tip.since : null,
|
|
514
|
+
};
|
|
515
|
+
checkpoint.since = checkpoint.since === null ? null : absoluteTimestamp(checkpoint.since);
|
|
516
|
+
if (!tree.entries.has(checkpoint.entryId))
|
|
517
|
+
throw Error(`Review boundary unavailable: ${checkpoint.entryId}`);
|
|
518
|
+
boundaries.set(checkpoint.entryId, checkpoint);
|
|
150
519
|
}
|
|
520
|
+
|
|
521
|
+
const sourceEvidence: Evidence[] = [];
|
|
522
|
+
const sourceTips: Tip[] = [];
|
|
523
|
+
const sourceCheckpoints: Checkpoint[] = [];
|
|
524
|
+
for (const tip of tree.tips) {
|
|
525
|
+
let ancestorId: string | null = tip.entryId;
|
|
526
|
+
let ancestor: Checkpoint | undefined;
|
|
527
|
+
while (ancestorId !== null) {
|
|
528
|
+
ancestor = boundaries.get(ancestorId);
|
|
529
|
+
if (ancestor) break;
|
|
530
|
+
const entry = tree.entries.get(ancestorId);
|
|
531
|
+
if (!entry) throw Error(`Review boundary unavailable: ${ancestorId}`);
|
|
532
|
+
ancestorId = entry.parentId;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const effectiveSince = checkpointSince(ancestor, normalizedSource, requestedSince);
|
|
536
|
+
const previous = new Map<string, string | null>();
|
|
537
|
+
if (ancestor) {
|
|
538
|
+
for (const item of branchEvidence(tree, { ...tip, entryId: ancestor.entryId })) {
|
|
539
|
+
if (timestampMillis(item.timestamp) === null) warnUnknown(source, item);
|
|
540
|
+
if (isEligible(item, ancestor.since)) previous.set(selectionKey(item), item.editId);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const branch = branchEvidence(tree, tip, ancestor?.entryId ?? null);
|
|
545
|
+
for (const item of branch) {
|
|
546
|
+
if (timestampMillis(item.timestamp) === null) warnUnknown(source, item);
|
|
547
|
+
if (!isEligible(item, effectiveSince)) continue;
|
|
548
|
+
if (previous.get(selectionKey(item)) === item.editId) continue;
|
|
549
|
+
sourceEvidence.push(item);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const needsCheckpoint =
|
|
553
|
+
ancestor === undefined ||
|
|
554
|
+
ancestor.entryId !== tip.entryId ||
|
|
555
|
+
(ancestor.since !== null && effectiveSince !== ancestor.since);
|
|
556
|
+
if (needsCheckpoint) {
|
|
557
|
+
sourceTips.push(tip);
|
|
558
|
+
sourceCheckpoints.push({ ...tip, since: effectiveSince });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (requestedSince !== null) {
|
|
563
|
+
const nextDefault = earlierFinite(sourceSince, requestedSince);
|
|
564
|
+
if (nextDefault !== sourceSince && nextDefault !== null)
|
|
565
|
+
sourceDefaults.push({ sessionId: source.sessionId, since: nextDefault });
|
|
566
|
+
}
|
|
567
|
+
tips.push(...sourceTips);
|
|
568
|
+
checkpoints.push(...sourceCheckpoints);
|
|
569
|
+
evidence.push(...sourceEvidence);
|
|
570
|
+
frozenSnapshots.push({ source: normalizedSource, tree });
|
|
571
|
+
successfulSources.push(normalizedSource);
|
|
151
572
|
} catch (error) {
|
|
152
|
-
|
|
573
|
+
if (error instanceof ReviewLimitError) throw error;
|
|
574
|
+
incomplete = true;
|
|
575
|
+
const reason = String(error);
|
|
576
|
+
warnings.push(
|
|
577
|
+
createWarning(`${source.file}: ${reason}`, [source.file], reason, 'source-failure'),
|
|
578
|
+
);
|
|
153
579
|
}
|
|
154
580
|
}
|
|
155
|
-
|
|
581
|
+
|
|
582
|
+
return {
|
|
583
|
+
tips,
|
|
584
|
+
checkpoints,
|
|
585
|
+
sourceDefaults,
|
|
586
|
+
evidence,
|
|
587
|
+
snapshots: frozenSnapshots,
|
|
588
|
+
successfulSources,
|
|
589
|
+
warnings,
|
|
590
|
+
incomplete,
|
|
591
|
+
coverageChanged: checkpoints.length > 0 || sourceDefaults.length > 0,
|
|
592
|
+
};
|
|
156
593
|
}
|