@robhowley/pi-remembrancer 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/README.md +58 -17
- package/extensions/remembrancer/capture-artifacts.ts +211 -0
- package/extensions/remembrancer/capture-handoff.ts +712 -0
- package/extensions/remembrancer/capture-jobs.ts +111 -0
- package/extensions/remembrancer/capture-matches.ts +145 -0
- package/extensions/remembrancer/capture-notices.ts +51 -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 +336 -0
- package/extensions/remembrancer/capture.ts +259 -135
- package/extensions/remembrancer/checkpoints.ts +603 -116
- 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 +597 -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
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
// The caller quiesces the outgoing saved session before admission. No transcript
|
|
2
|
+
// parsing or hashing occurs on this asynchronous preservation path.
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { constants, realpathSync } from 'node:fs';
|
|
5
|
+
import { Worker } from 'node:worker_threads';
|
|
6
|
+
import {
|
|
7
|
+
chmod,
|
|
8
|
+
copyFile,
|
|
9
|
+
mkdir,
|
|
10
|
+
lstat,
|
|
11
|
+
open,
|
|
12
|
+
readFile,
|
|
13
|
+
readdir,
|
|
14
|
+
rename,
|
|
15
|
+
realpath,
|
|
16
|
+
stat,
|
|
17
|
+
unlink,
|
|
18
|
+
writeFile,
|
|
19
|
+
} from 'node:fs/promises';
|
|
20
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
21
|
+
import type { CreateAgentSessionOptions } from '@earendil-works/pi-coding-agent';
|
|
22
|
+
import type { CheckpointStore } from './checkpoints.js';
|
|
23
|
+
|
|
24
|
+
// Headers/auth remain in the originating Pi configuration, never in handoffs.
|
|
25
|
+
export type CaptureModel = Omit<NonNullable<CreateAgentSessionOptions['model']>, 'headers'>;
|
|
26
|
+
export type CaptureRuntime = {
|
|
27
|
+
model: CaptureModel;
|
|
28
|
+
thinkingLevel: NonNullable<CreateAgentSessionOptions['thinkingLevel']>;
|
|
29
|
+
projectTrusted: boolean;
|
|
30
|
+
headerNames?: string[];
|
|
31
|
+
};
|
|
32
|
+
import type { CaptureJob, CaptureWorkerOwnership } from './capture-jobs.js';
|
|
33
|
+
|
|
34
|
+
export type HandoffInput = {
|
|
35
|
+
// Fresh randomUUID per admission. Recovery reuses the saved manifest, never
|
|
36
|
+
// preserves another snapshot under an accepted ID.
|
|
37
|
+
id: string;
|
|
38
|
+
inbox: string;
|
|
39
|
+
source: { file: string; sessionId: string };
|
|
40
|
+
execution: {
|
|
41
|
+
cwd: string;
|
|
42
|
+
agentDir: string;
|
|
43
|
+
authorization: { autoCapture: true; disabled: false };
|
|
44
|
+
host?: { nodeExecutable: string; piEntry: string };
|
|
45
|
+
runtime: CaptureRuntime;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const preservationSteps = [
|
|
50
|
+
'source-stat',
|
|
51
|
+
'snapshot-copy',
|
|
52
|
+
'source-verify',
|
|
53
|
+
'snapshot-chmod',
|
|
54
|
+
'snapshot-sync',
|
|
55
|
+
'snapshot-directory-sync',
|
|
56
|
+
'publication-order-write',
|
|
57
|
+
'publication-order-sync',
|
|
58
|
+
'publication-order-rename',
|
|
59
|
+
'publication-order-directory-sync',
|
|
60
|
+
'manifest-write',
|
|
61
|
+
'manifest-sync',
|
|
62
|
+
'manifest-rename',
|
|
63
|
+
'ready-directory-sync',
|
|
64
|
+
] as const;
|
|
65
|
+
export type PreservationStep = (typeof preservationSteps)[number];
|
|
66
|
+
type Hooks = {
|
|
67
|
+
copy?: typeof copyFile;
|
|
68
|
+
before?: (step: PreservationStep) => void | Promise<void>;
|
|
69
|
+
after?: (step: PreservationStep) => void | Promise<void>;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
async function synchronize(file: string) {
|
|
73
|
+
const handle = await open(file, 'r');
|
|
74
|
+
try {
|
|
75
|
+
await handle.sync();
|
|
76
|
+
} finally {
|
|
77
|
+
await handle.close();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// This queue is also descriptor ownership: closing a second SQLite connection
|
|
82
|
+
// to the same inode can release another thread's POSIX locks in this process.
|
|
83
|
+
const publications = new Map<string, Promise<void>>();
|
|
84
|
+
export const CAPTURE_MANIFEST_VERSION = 3 as const;
|
|
85
|
+
|
|
86
|
+
const localCodes = new Set([
|
|
87
|
+
'EACCES',
|
|
88
|
+
'EPERM',
|
|
89
|
+
'ENOSPC',
|
|
90
|
+
'EIO',
|
|
91
|
+
'ENOENT',
|
|
92
|
+
'EEXIST',
|
|
93
|
+
'ENOTDIR',
|
|
94
|
+
'EROFS',
|
|
95
|
+
'EMFILE',
|
|
96
|
+
'ENFILE',
|
|
97
|
+
'ENOTSUP',
|
|
98
|
+
'EOPNOTSUPP',
|
|
99
|
+
'ENOSYS',
|
|
100
|
+
'EXDEV',
|
|
101
|
+
'EINVAL',
|
|
102
|
+
]);
|
|
103
|
+
export class CaptureHandoffError extends Error {
|
|
104
|
+
readonly code: string | undefined;
|
|
105
|
+
constructor(
|
|
106
|
+
readonly phase: string,
|
|
107
|
+
readonly category: string,
|
|
108
|
+
readonly artifactId: string,
|
|
109
|
+
error?: unknown,
|
|
110
|
+
) {
|
|
111
|
+
const raw = error as { code?: string; errcode?: number } | undefined;
|
|
112
|
+
const code = localCodes.has(raw?.code ?? '')
|
|
113
|
+
? raw!.code
|
|
114
|
+
: (
|
|
115
|
+
{
|
|
116
|
+
8: 'SQLITE_READONLY',
|
|
117
|
+
10: 'SQLITE_IOERR',
|
|
118
|
+
13: 'SQLITE_FULL',
|
|
119
|
+
14: 'SQLITE_CANTOPEN',
|
|
120
|
+
} as Record<number, string>
|
|
121
|
+
)[raw?.errcode ?? -1];
|
|
122
|
+
super(`Capture ${phase}: ${category}${code ? ` (${code})` : ''} [${artifactId}]`);
|
|
123
|
+
this.code = code;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function claimPublication(inbox: string, id: string) {
|
|
128
|
+
const worker = new Worker(new URL('./capture-publication-lock.mjs', import.meta.url), {
|
|
129
|
+
workerData: join(inbox, '.publication-lock.sqlite'),
|
|
130
|
+
// Do not inherit a foreground loader or command-line evaluation.
|
|
131
|
+
execArgv: [],
|
|
132
|
+
});
|
|
133
|
+
let failure: CaptureHandoffError | undefined;
|
|
134
|
+
let acquired = false;
|
|
135
|
+
const exited = new Promise<void>((resolve) => worker.once('exit', () => resolve()));
|
|
136
|
+
try {
|
|
137
|
+
await new Promise<void>((resolve, reject) => {
|
|
138
|
+
worker.on(
|
|
139
|
+
'message',
|
|
140
|
+
(message: { acquired?: boolean; failed?: boolean; code?: string; errcode?: number }) => {
|
|
141
|
+
if (message.failed) {
|
|
142
|
+
failure = new CaptureHandoffError(
|
|
143
|
+
'publication-lock',
|
|
144
|
+
'local-lock-failure',
|
|
145
|
+
id,
|
|
146
|
+
message,
|
|
147
|
+
);
|
|
148
|
+
reject(failure);
|
|
149
|
+
} else if (message.acquired) {
|
|
150
|
+
acquired = true;
|
|
151
|
+
resolve();
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
);
|
|
155
|
+
worker.on('error', (error) => {
|
|
156
|
+
failure = new CaptureHandoffError('publication-lock', 'lock-holder-startup', id, error);
|
|
157
|
+
reject(failure);
|
|
158
|
+
});
|
|
159
|
+
worker.once('exit', () => {
|
|
160
|
+
if (!acquired)
|
|
161
|
+
reject(failure ?? new CaptureHandoffError('publication-lock', 'lock-holder-exited', id));
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
} catch (error) {
|
|
165
|
+
await worker.terminate();
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
return async () => {
|
|
169
|
+
try {
|
|
170
|
+
worker.postMessage('release');
|
|
171
|
+
await exited;
|
|
172
|
+
if (failure) throw failure;
|
|
173
|
+
} finally {
|
|
174
|
+
await worker.terminate();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function preserveHandoff(request: HandoffInput, hooks: Hooks = {}) {
|
|
180
|
+
const input = structuredClone(request);
|
|
181
|
+
const id = /^[a-zA-Z0-9_-]{1,128}$/.test(input.id) ? input.id : 'invalid-id';
|
|
182
|
+
let phase = 'validation';
|
|
183
|
+
try {
|
|
184
|
+
validateInput(input);
|
|
185
|
+
await validateHeaderReferences(input.execution, id);
|
|
186
|
+
phase = 'inbox-initialization';
|
|
187
|
+
await mkdir(input.inbox, { recursive: true, mode: 0o700 });
|
|
188
|
+
input.inbox = await realpath(input.inbox);
|
|
189
|
+
await chmod(input.inbox, 0o700);
|
|
190
|
+
// Independently persist every ancestor, even when another publisher created
|
|
191
|
+
// it and has not yet synced it. No caller relies on mkdir's created flag.
|
|
192
|
+
for (let directory = input.inbox; ; directory = dirname(directory)) {
|
|
193
|
+
await synchronize(directory);
|
|
194
|
+
if (directory === dirname(directory)) break;
|
|
195
|
+
}
|
|
196
|
+
const previous = publications.get(input.inbox);
|
|
197
|
+
let done!: () => void;
|
|
198
|
+
const current = new Promise<void>((resolve) => (done = resolve));
|
|
199
|
+
publications.set(input.inbox, current);
|
|
200
|
+
await previous;
|
|
201
|
+
try {
|
|
202
|
+
phase = 'publication-lock';
|
|
203
|
+
try {
|
|
204
|
+
await lstat(join(input.inbox, '.publication-lock'));
|
|
205
|
+
throw new CaptureHandoffError(phase, 'legacy-publication-lock', id);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
208
|
+
}
|
|
209
|
+
const release = await claimPublication(input.inbox, id);
|
|
210
|
+
let accepted: Awaited<ReturnType<typeof preserveOrderedHandoff>> | undefined;
|
|
211
|
+
let cleanupDiagnostic: string | undefined;
|
|
212
|
+
try {
|
|
213
|
+
accepted = await preserveOrderedHandoff(input, hooks);
|
|
214
|
+
} finally {
|
|
215
|
+
try {
|
|
216
|
+
await release();
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (accepted)
|
|
219
|
+
cleanupDiagnostic = new CaptureHandoffError(
|
|
220
|
+
'publication-lock-release',
|
|
221
|
+
'accepted-cleanup-pending',
|
|
222
|
+
id,
|
|
223
|
+
error,
|
|
224
|
+
).message;
|
|
225
|
+
// Otherwise preserve the original admission failure, not cleanup.
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return { ...accepted, ...(cleanupDiagnostic ? { cleanupDiagnostic } : {}) };
|
|
229
|
+
} finally {
|
|
230
|
+
done();
|
|
231
|
+
if (publications.get(input.inbox) === current) publications.delete(input.inbox);
|
|
232
|
+
}
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (error instanceof CaptureHandoffError) throw error;
|
|
235
|
+
throw new CaptureHandoffError(
|
|
236
|
+
phase,
|
|
237
|
+
phase === 'validation' ? 'invalid-input' : 'local-io-failure',
|
|
238
|
+
id,
|
|
239
|
+
error,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function validateHeaderReferences(execution: HandoffInput['execution'], id: string) {
|
|
245
|
+
const required = execution.runtime.headerNames ?? [];
|
|
246
|
+
if (!required.length) return;
|
|
247
|
+
let config: unknown;
|
|
248
|
+
try {
|
|
249
|
+
config = JSON.parse(await readFile(join(execution.agentDir, 'models.json'), 'utf8'));
|
|
250
|
+
} catch (error) {
|
|
251
|
+
throw new CaptureHandoffError('validation', 'unavailable-header-references', id, error);
|
|
252
|
+
}
|
|
253
|
+
const provider = (
|
|
254
|
+
config as {
|
|
255
|
+
providers?: Record<
|
|
256
|
+
string,
|
|
257
|
+
{
|
|
258
|
+
headers?: Record<string, unknown>;
|
|
259
|
+
models?: { id: string; headers?: Record<string, unknown> }[];
|
|
260
|
+
modelOverrides?: Record<string, { headers?: Record<string, unknown> }>;
|
|
261
|
+
}
|
|
262
|
+
>;
|
|
263
|
+
} | null
|
|
264
|
+
)?.providers?.[execution.runtime.model.provider];
|
|
265
|
+
const model = provider?.models?.find((model) => model.id === execution.runtime.model.id);
|
|
266
|
+
const headers = {
|
|
267
|
+
...provider?.headers,
|
|
268
|
+
...model?.headers,
|
|
269
|
+
...provider?.modelOverrides?.[execution.runtime.model.id]?.headers,
|
|
270
|
+
};
|
|
271
|
+
const references = new Set(
|
|
272
|
+
Object.entries(headers)
|
|
273
|
+
.filter(([, value]) => typeof value === 'string' && value.trim())
|
|
274
|
+
.map(([name]) => name.toLowerCase()),
|
|
275
|
+
);
|
|
276
|
+
if (required.some((name) => !references.has(name.toLowerCase())))
|
|
277
|
+
throw new CaptureHandoffError('validation', 'unsupported-runtime-headers', id);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function preserveOrderedHandoff(input: HandoffInput, hooks: Hooks) {
|
|
281
|
+
const orderFile = join(input.inbox, '.publication-order');
|
|
282
|
+
let previous = '0'.padStart(32, '0');
|
|
283
|
+
try {
|
|
284
|
+
previous = await readFile(orderFile, 'utf8');
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
|
|
287
|
+
throw new CaptureHandoffError('publication-order', 'unavailable-order', input.id, error);
|
|
288
|
+
// Never reset ordering around retained evidence, including pre-sequence
|
|
289
|
+
// handoffs. A fresh inbox is the only safe initialization case.
|
|
290
|
+
if (
|
|
291
|
+
(await readdir(input.inbox)).some(
|
|
292
|
+
(name) =>
|
|
293
|
+
!/^\.publication-lock\.sqlite(?:-journal|-wal|-shm)?$/.test(name) &&
|
|
294
|
+
!/^\.publication-order\.[a-f0-9-]{36}\.tmp$/.test(name),
|
|
295
|
+
)
|
|
296
|
+
)
|
|
297
|
+
throw new CaptureHandoffError('publication-order', 'missing-order', input.id);
|
|
298
|
+
// A failed first snapshot must not leave an apparently uninitialized inbox.
|
|
299
|
+
await writeOrder(previous);
|
|
300
|
+
}
|
|
301
|
+
if (!/^\d{32}$/.test(previous))
|
|
302
|
+
throw new CaptureHandoffError('publication-order', 'invalid-order', input.id);
|
|
303
|
+
const admissionOrder = (BigInt(previous) + 1n).toString().padStart(32, '0');
|
|
304
|
+
if (admissionOrder.length !== 32)
|
|
305
|
+
throw new CaptureHandoffError('publication-order', 'order-exhausted', input.id);
|
|
306
|
+
const snapshot = join(input.inbox, `${input.id}.snapshot.jsonl`);
|
|
307
|
+
const temporary = join(input.inbox, `.${input.id}.ready.tmp`);
|
|
308
|
+
const ready = join(input.inbox, `${input.id}.ready.json`);
|
|
309
|
+
// A retained ID must never overwrite a previous ready manifest, even if an
|
|
310
|
+
// operator has removed its snapshot. Exclusive snapshot creation serializes IDs.
|
|
311
|
+
try {
|
|
312
|
+
await stat(ready);
|
|
313
|
+
throw new CaptureHandoffError('snapshot-admission', 'duplicate-handoff', input.id, {
|
|
314
|
+
code: 'EEXIST',
|
|
315
|
+
});
|
|
316
|
+
} catch (error) {
|
|
317
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
318
|
+
}
|
|
319
|
+
async function step<T>(name: PreservationStep, operation: () => Promise<T>): Promise<T> {
|
|
320
|
+
try {
|
|
321
|
+
await hooks.before?.(name);
|
|
322
|
+
const value = await operation();
|
|
323
|
+
await hooks.after?.(name);
|
|
324
|
+
return value;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw new CaptureHandoffError(
|
|
327
|
+
name,
|
|
328
|
+
name === 'ready-directory-sync' ? 'acceptance-uncertain' : 'preservation-failed',
|
|
329
|
+
input.id,
|
|
330
|
+
error,
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const initial = await step('source-stat', () => stat(input.source.file, { bigint: true }));
|
|
336
|
+
if (!initial.isFile() || initial.size > BigInt(Number.MAX_SAFE_INTEGER))
|
|
337
|
+
throw new CaptureHandoffError('source-stat', 'unsupported-source', input.id);
|
|
338
|
+
const copy = hooks.copy ?? copyFile;
|
|
339
|
+
const copyMode = await step('snapshot-copy', async () => {
|
|
340
|
+
try {
|
|
341
|
+
await copy(
|
|
342
|
+
input.source.file,
|
|
343
|
+
snapshot,
|
|
344
|
+
constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE_FORCE,
|
|
345
|
+
);
|
|
346
|
+
return 'clone' as const;
|
|
347
|
+
} catch (error) {
|
|
348
|
+
// Do not mask I/O, space, permission or destination-collision failures.
|
|
349
|
+
if (
|
|
350
|
+
!['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV', 'EINVAL'].includes(
|
|
351
|
+
(error as NodeJS.ErrnoException).code ?? '',
|
|
352
|
+
)
|
|
353
|
+
)
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
await copy(input.source.file, snapshot, constants.COPYFILE_EXCL);
|
|
357
|
+
return 'copy' as const;
|
|
358
|
+
});
|
|
359
|
+
await step('source-verify', async () => {
|
|
360
|
+
const final = await stat(input.source.file, { bigint: true });
|
|
361
|
+
const saved = await stat(snapshot, { bigint: true });
|
|
362
|
+
if (
|
|
363
|
+
final.dev !== initial.dev ||
|
|
364
|
+
final.ino !== initial.ino ||
|
|
365
|
+
final.size !== initial.size ||
|
|
366
|
+
final.mtimeNs !== initial.mtimeNs ||
|
|
367
|
+
final.ctimeNs !== initial.ctimeNs ||
|
|
368
|
+
saved.size !== initial.size
|
|
369
|
+
)
|
|
370
|
+
throw Error('Source changed during preservation');
|
|
371
|
+
});
|
|
372
|
+
await step('snapshot-chmod', () => chmod(snapshot, 0o600));
|
|
373
|
+
await step('snapshot-sync', () => synchronize(snapshot));
|
|
374
|
+
await step('snapshot-directory-sync', () => synchronize(input.inbox));
|
|
375
|
+
|
|
376
|
+
// Persist the high-water mark before publishing. Gaps after failure are safe;
|
|
377
|
+
// reuse after a restart is not. The lock remains held through ready sync.
|
|
378
|
+
async function writeOrder(order: string, recordSteps = false) {
|
|
379
|
+
const temporary = join(input.inbox, `.publication-order.${randomUUID()}.tmp`);
|
|
380
|
+
const run = async <T>(name: PreservationStep, operation: () => Promise<T>) => {
|
|
381
|
+
if (recordSteps) return step(name, operation);
|
|
382
|
+
try {
|
|
383
|
+
return await operation();
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw new CaptureHandoffError(
|
|
386
|
+
'publication-order-initialization',
|
|
387
|
+
'initialization-failed',
|
|
388
|
+
input.id,
|
|
389
|
+
error,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
let written = false;
|
|
394
|
+
try {
|
|
395
|
+
await run('publication-order-write', async () => {
|
|
396
|
+
await writeFile(temporary, order, { flag: 'wx', mode: 0o600 });
|
|
397
|
+
written = true;
|
|
398
|
+
});
|
|
399
|
+
await run('publication-order-sync', () => synchronize(temporary));
|
|
400
|
+
await run('publication-order-rename', () => rename(temporary, orderFile));
|
|
401
|
+
await run('publication-order-directory-sync', () => synchronize(input.inbox));
|
|
402
|
+
} finally {
|
|
403
|
+
// Only our private, unpublished scratch. Never remove evidence or the
|
|
404
|
+
// high-water record. A cleanup error must not poison the next admission.
|
|
405
|
+
if (written) await unlink(temporary).catch(() => {});
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
await writeOrder(admissionOrder, true);
|
|
409
|
+
|
|
410
|
+
// The manifest is the ready signal. Snapshot paths are never source identity.
|
|
411
|
+
const manifest = {
|
|
412
|
+
version: CAPTURE_MANIFEST_VERSION,
|
|
413
|
+
id: input.id,
|
|
414
|
+
snapshot,
|
|
415
|
+
source: {
|
|
416
|
+
file: input.source.file,
|
|
417
|
+
sessionId: input.source.sessionId,
|
|
418
|
+
bytes: Number(initial.size),
|
|
419
|
+
device: String(initial.dev),
|
|
420
|
+
inode: String(initial.ino),
|
|
421
|
+
},
|
|
422
|
+
execution: structuredClone(input.execution),
|
|
423
|
+
acceptedAt: new Date().toISOString(),
|
|
424
|
+
admissionOrder,
|
|
425
|
+
};
|
|
426
|
+
await step('manifest-write', () =>
|
|
427
|
+
writeFile(temporary, JSON.stringify(manifest) + '\n', { flag: 'wx', mode: 0o600 }),
|
|
428
|
+
);
|
|
429
|
+
await step('manifest-sync', () => synchronize(temporary));
|
|
430
|
+
await step('manifest-rename', () => rename(temporary, ready));
|
|
431
|
+
let cleanupDiagnostic: string | undefined;
|
|
432
|
+
await step('ready-directory-sync', async () => {
|
|
433
|
+
const directory = await open(input.inbox, 'r');
|
|
434
|
+
try {
|
|
435
|
+
await directory.sync();
|
|
436
|
+
} catch (error) {
|
|
437
|
+
await directory.close().catch(() => {});
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
// This sync is the acceptance boundary. Closing its descriptor is cleanup,
|
|
441
|
+
// not another condition on whether the already-synced job was accepted.
|
|
442
|
+
try {
|
|
443
|
+
await directory.close();
|
|
444
|
+
} catch (error) {
|
|
445
|
+
cleanupDiagnostic = new CaptureHandoffError(
|
|
446
|
+
'ready-directory-close',
|
|
447
|
+
'accepted-cleanup-pending',
|
|
448
|
+
input.id,
|
|
449
|
+
error,
|
|
450
|
+
).message;
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
// No cleanup on error: an acknowledgement failure can follow publication.
|
|
454
|
+
// Ambiguous artifacts must be diagnosed, not guessed safe to delete.
|
|
455
|
+
return { manifest, ready, copyMode, ...(cleanupDiagnostic ? { cleanupDiagnostic } : {}) };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export type ReadyManifest = Awaited<ReturnType<typeof preserveHandoff>>['manifest'];
|
|
459
|
+
|
|
460
|
+
function validateInput(input: HandoffInput): void {
|
|
461
|
+
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(input.id)) throw Error('Invalid handoff ID');
|
|
462
|
+
for (const path of [
|
|
463
|
+
input.inbox,
|
|
464
|
+
input.source.file,
|
|
465
|
+
input.execution.cwd,
|
|
466
|
+
input.execution.agentDir,
|
|
467
|
+
])
|
|
468
|
+
if (!isAbsolute(path)) throw Error('Handoff paths must be absolute');
|
|
469
|
+
if (
|
|
470
|
+
[
|
|
471
|
+
input.source.sessionId,
|
|
472
|
+
input.execution.runtime?.model?.provider,
|
|
473
|
+
input.execution.runtime?.model?.id,
|
|
474
|
+
].some((value) => typeof value !== 'string' || !value.trim()) ||
|
|
475
|
+
input.execution.authorization?.autoCapture !== true ||
|
|
476
|
+
input.execution.authorization.disabled !== false
|
|
477
|
+
)
|
|
478
|
+
throw Error('Handoff requires originating capture authorization');
|
|
479
|
+
// Serialize only the declared non-secret configuration references.
|
|
480
|
+
const allowed = ['cwd', 'agentDir', 'authorization', 'host', 'runtime'];
|
|
481
|
+
if (
|
|
482
|
+
Object.keys(input.execution).some((key) => !allowed.includes(key)) ||
|
|
483
|
+
Object.keys(input.execution.authorization).some(
|
|
484
|
+
(key) => !['autoCapture', 'disabled'].includes(key),
|
|
485
|
+
)
|
|
486
|
+
)
|
|
487
|
+
throw Error('Unexpected execution metadata');
|
|
488
|
+
{
|
|
489
|
+
const { runtime } = input.execution;
|
|
490
|
+
if (!runtime || !runtime.model) throw Error('Missing reviewer runtime');
|
|
491
|
+
if (
|
|
492
|
+
Object.keys(runtime).some(
|
|
493
|
+
(key) => !['model', 'thinkingLevel', 'projectTrusted', 'headerNames'].includes(key),
|
|
494
|
+
) ||
|
|
495
|
+
typeof runtime.projectTrusted !== 'boolean' ||
|
|
496
|
+
(runtime.headerNames !== undefined &&
|
|
497
|
+
(!Array.isArray(runtime.headerNames) ||
|
|
498
|
+
runtime.headerNames.some((name) => typeof name !== 'string' || !name.trim()))) ||
|
|
499
|
+
!['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'].includes(
|
|
500
|
+
runtime.thinkingLevel,
|
|
501
|
+
) ||
|
|
502
|
+
[
|
|
503
|
+
runtime.model.provider,
|
|
504
|
+
runtime.model.id,
|
|
505
|
+
runtime.model.name,
|
|
506
|
+
runtime.model.api,
|
|
507
|
+
runtime.model.baseUrl,
|
|
508
|
+
].some((value) => typeof value !== 'string' || !value.trim()) ||
|
|
509
|
+
typeof runtime.model.reasoning !== 'boolean' ||
|
|
510
|
+
!Array.isArray(runtime.model.input) ||
|
|
511
|
+
!runtime.model.input.length ||
|
|
512
|
+
runtime.model.input.some((kind) => !['text', 'image'].includes(kind)) ||
|
|
513
|
+
[
|
|
514
|
+
runtime.model.cost?.input,
|
|
515
|
+
runtime.model.cost?.output,
|
|
516
|
+
runtime.model.cost?.cacheRead,
|
|
517
|
+
runtime.model.cost?.cacheWrite,
|
|
518
|
+
].some((value) => !Number.isFinite(value) || value < 0) ||
|
|
519
|
+
!Number.isSafeInteger(runtime.model.contextWindow) ||
|
|
520
|
+
runtime.model.contextWindow <= 0 ||
|
|
521
|
+
!Number.isSafeInteger(runtime.model.maxTokens) ||
|
|
522
|
+
runtime.model.maxTokens <= 0 ||
|
|
523
|
+
'headers' in runtime.model ||
|
|
524
|
+
Object.keys(runtime.model).some(
|
|
525
|
+
(key) =>
|
|
526
|
+
![
|
|
527
|
+
'provider',
|
|
528
|
+
'id',
|
|
529
|
+
'name',
|
|
530
|
+
'api',
|
|
531
|
+
'baseUrl',
|
|
532
|
+
'reasoning',
|
|
533
|
+
'input',
|
|
534
|
+
'cost',
|
|
535
|
+
'contextWindow',
|
|
536
|
+
'maxTokens',
|
|
537
|
+
'thinkingLevelMap',
|
|
538
|
+
'compat',
|
|
539
|
+
'samplingParams',
|
|
540
|
+
'samplingParamsByThinkingLevel',
|
|
541
|
+
'inputLimits',
|
|
542
|
+
'promptCache',
|
|
543
|
+
'type',
|
|
544
|
+
].includes(key),
|
|
545
|
+
)
|
|
546
|
+
)
|
|
547
|
+
throw Error('Invalid non-secret reviewer runtime');
|
|
548
|
+
const url = new URL(runtime.model.baseUrl);
|
|
549
|
+
if (url.username || url.password || url.search || url.hash)
|
|
550
|
+
throw Error('Capture model endpoint must not contain credentials or query parameters');
|
|
551
|
+
}
|
|
552
|
+
if (
|
|
553
|
+
input.execution.host &&
|
|
554
|
+
(Object.keys(input.execution.host).some(
|
|
555
|
+
(key) => !['nodeExecutable', 'piEntry'].includes(key),
|
|
556
|
+
) ||
|
|
557
|
+
!isAbsolute(input.execution.host.nodeExecutable) ||
|
|
558
|
+
!isAbsolute(input.execution.host.piEntry))
|
|
559
|
+
)
|
|
560
|
+
throw Error('Invalid host references');
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export function validateReadyManifest(value: unknown, inbox: string): ReadyManifest {
|
|
564
|
+
try {
|
|
565
|
+
const manifest = value as ReadyManifest;
|
|
566
|
+
if (
|
|
567
|
+
!manifest ||
|
|
568
|
+
manifest.version !== CAPTURE_MANIFEST_VERSION ||
|
|
569
|
+
!manifest.source ||
|
|
570
|
+
!manifest.execution ||
|
|
571
|
+
Object.keys(manifest).some(
|
|
572
|
+
(key) =>
|
|
573
|
+
![
|
|
574
|
+
'version',
|
|
575
|
+
'id',
|
|
576
|
+
'snapshot',
|
|
577
|
+
'source',
|
|
578
|
+
'execution',
|
|
579
|
+
'acceptedAt',
|
|
580
|
+
'admissionOrder',
|
|
581
|
+
].includes(key),
|
|
582
|
+
) ||
|
|
583
|
+
Object.keys(manifest.source).some(
|
|
584
|
+
(key) => !['file', 'sessionId', 'bytes', 'device', 'inode'].includes(key),
|
|
585
|
+
)
|
|
586
|
+
)
|
|
587
|
+
throw new CaptureHandoffError(
|
|
588
|
+
'ready-validation',
|
|
589
|
+
'unsupported-or-invalid-manifest',
|
|
590
|
+
'retained',
|
|
591
|
+
);
|
|
592
|
+
validateInput({ ...manifest, inbox });
|
|
593
|
+
if (
|
|
594
|
+
physicalInbox(dirname(manifest.snapshot)) !== physicalInbox(inbox) ||
|
|
595
|
+
manifest.snapshot !== join(dirname(manifest.snapshot), `${manifest.id}.snapshot.jsonl`) ||
|
|
596
|
+
!Number.isSafeInteger(manifest.source.bytes) ||
|
|
597
|
+
manifest.source.bytes < 0 ||
|
|
598
|
+
typeof manifest.source.device !== 'string' ||
|
|
599
|
+
!/^\d+$/.test(manifest.source.device) ||
|
|
600
|
+
typeof manifest.source.inode !== 'string' ||
|
|
601
|
+
!/^\d+$/.test(manifest.source.inode) ||
|
|
602
|
+
!Number.isFinite(Date.parse(manifest.acceptedAt)) ||
|
|
603
|
+
new Date(manifest.acceptedAt).toISOString() !== manifest.acceptedAt ||
|
|
604
|
+
typeof manifest.admissionOrder !== 'string' ||
|
|
605
|
+
!/^\d{32}$/.test(manifest.admissionOrder)
|
|
606
|
+
)
|
|
607
|
+
throw Error('Invalid retained snapshot metadata');
|
|
608
|
+
return manifest;
|
|
609
|
+
} catch (error) {
|
|
610
|
+
if (error instanceof CaptureHandoffError) throw error;
|
|
611
|
+
throw new CaptureHandoffError(
|
|
612
|
+
'ready-validation',
|
|
613
|
+
'invalid-retained-manifest',
|
|
614
|
+
'retained',
|
|
615
|
+
error,
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// Compare physical directories without rewriting retained payloads/identity JSON.
|
|
621
|
+
export function physicalInbox(inbox: string): string {
|
|
622
|
+
return realpathSync(resolve(inbox));
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async function readReadyManifest(ready: string): Promise<ReadyManifest> {
|
|
626
|
+
try {
|
|
627
|
+
const manifest = validateReadyManifest(
|
|
628
|
+
JSON.parse(await readFile(ready, 'utf8')),
|
|
629
|
+
dirname(ready),
|
|
630
|
+
);
|
|
631
|
+
if (ready !== join(dirname(ready), `${manifest.id}.ready.json`))
|
|
632
|
+
throw Error('Ready filename mismatch');
|
|
633
|
+
return manifest;
|
|
634
|
+
} catch (error) {
|
|
635
|
+
const id =
|
|
636
|
+
/^([a-zA-Z0-9_-]{1,128})\.ready\.json$/.exec(basename(ready))?.[1] ?? 'invalid-ready-name';
|
|
637
|
+
if (error instanceof CaptureHandoffError)
|
|
638
|
+
throw new CaptureHandoffError(error.phase, error.category, id, error);
|
|
639
|
+
throw new CaptureHandoffError('ready-read', 'invalid-or-unavailable-manifest', id, error);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// Import is committed before removing the only ready signal. A failed unlink is
|
|
644
|
+
// harmless: re-import recognizes the retained ID, including completed jobs.
|
|
645
|
+
export async function importReadyHandoff(
|
|
646
|
+
store: CheckpointStore,
|
|
647
|
+
owner: CaptureWorkerOwnership,
|
|
648
|
+
ready: string,
|
|
649
|
+
): Promise<{ job: CaptureJob; signalCleanupPending: boolean; cleanupDiagnostic?: string }> {
|
|
650
|
+
owner.assertStore(store.file);
|
|
651
|
+
const manifest = await readReadyManifest(ready);
|
|
652
|
+
const job = store.importCaptureJob(owner, manifest);
|
|
653
|
+
owner.assertStore(store.file);
|
|
654
|
+
try {
|
|
655
|
+
try {
|
|
656
|
+
await unlink(ready);
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
659
|
+
}
|
|
660
|
+
await synchronize(dirname(ready));
|
|
661
|
+
return { job, signalCleanupPending: false };
|
|
662
|
+
} catch (error) {
|
|
663
|
+
return {
|
|
664
|
+
job,
|
|
665
|
+
signalCleanupPending: true,
|
|
666
|
+
cleanupDiagnostic: new CaptureHandoffError(
|
|
667
|
+
'ready-cleanup',
|
|
668
|
+
'committed-signal-cleanup-pending',
|
|
669
|
+
manifest.id,
|
|
670
|
+
error,
|
|
671
|
+
).message,
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Only explicit completed-job cleanup, not an orphan scanner. Any unreadable or
|
|
677
|
+
// ambiguous ready manifest prevents deletion. All unresolved SQLite references
|
|
678
|
+
// are checked again after the asynchronous filesystem reads.
|
|
679
|
+
export async function cleanupCompletedSnapshot(
|
|
680
|
+
store: CheckpointStore,
|
|
681
|
+
owner: CaptureWorkerOwnership,
|
|
682
|
+
id: string,
|
|
683
|
+
): Promise<boolean> {
|
|
684
|
+
owner.assertStore(store.file);
|
|
685
|
+
const job = store.captureJob(id);
|
|
686
|
+
if (!job || job.state !== 'completed') return false;
|
|
687
|
+
const inbox = dirname(job.manifest.snapshot);
|
|
688
|
+
// A hard cutover never makes retained unsupported rows cleanup authority.
|
|
689
|
+
validateReadyManifest(job.manifest, inbox);
|
|
690
|
+
for (const name of await readdir(inbox)) {
|
|
691
|
+
if (!name.endsWith('.ready.json')) continue;
|
|
692
|
+
const manifest = await readReadyManifest(join(inbox, name));
|
|
693
|
+
if (
|
|
694
|
+
join(physicalInbox(dirname(manifest.snapshot)), basename(manifest.snapshot)) ===
|
|
695
|
+
join(physicalInbox(inbox), basename(job.manifest.snapshot))
|
|
696
|
+
)
|
|
697
|
+
return false;
|
|
698
|
+
}
|
|
699
|
+
owner.assertStore(store.file);
|
|
700
|
+
if (
|
|
701
|
+
store.captureJob(id)?.state !== 'completed' ||
|
|
702
|
+
store.unresolvedSnapshot(job.manifest.snapshot)
|
|
703
|
+
)
|
|
704
|
+
return false;
|
|
705
|
+
try {
|
|
706
|
+
await unlink(job.manifest.snapshot);
|
|
707
|
+
} catch (error) {
|
|
708
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
709
|
+
}
|
|
710
|
+
await synchronize(inbox);
|
|
711
|
+
return true;
|
|
712
|
+
}
|