@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,10 +1,14 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
4
|
import { StringEnum, Type } from '@earendil-works/pi-ai';
|
|
4
5
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
|
-
import { CheckpointStore } from './checkpoints.js';
|
|
6
|
-
import { loadRemembrancerConfig } from './config.js';
|
|
7
|
-
import {
|
|
6
|
+
import { CheckpointStore, defaultCheckpointFile } from './checkpoints.js';
|
|
7
|
+
import { captureExecution, captureHost, loadRemembrancerConfig } from './config.js';
|
|
8
|
+
import { CaptureHandoffError, preserveHandoff } from './capture-handoff.js';
|
|
9
|
+
import { launchCaptureWorker } from './capture-worker.js';
|
|
10
|
+
import { CAPTURE_MAX_ATTEMPTS, type CaptureStatus } from './capture-jobs.js';
|
|
11
|
+
import { readProposalNotice } from './capture-notices.js';
|
|
8
12
|
import { openProposals } from './proposal-ui.js';
|
|
9
13
|
import { proposalReadDescription, proposalReadParameters, readProposals } from './proposal-read.js';
|
|
10
14
|
import { discoverSources } from './discovery.js';
|
|
@@ -70,14 +74,22 @@ type Batch = {
|
|
|
70
74
|
|
|
71
75
|
export const REMEMBRANCER_COMMAND_NAME = 'remembrancer';
|
|
72
76
|
export const REMEMBRANCER_COMMAND_USAGE =
|
|
73
|
-
'Usage: /remembrancer seed <Nd>\n /remembrancer proposals\n /remembrancer help';
|
|
77
|
+
'Usage: /remembrancer seed <Nd>\n /remembrancer proposals\n /remembrancer capture now|status|pause|resume\n /remembrancer capture retry <full-job-id>\n /remembrancer help';
|
|
74
78
|
export const REMEMBRANCER_HELP = [
|
|
75
79
|
REMEMBRANCER_COMMAND_USAGE,
|
|
76
80
|
'Seed saved-session evidence from a bounded historical window, then follow the Remembrancer skill.',
|
|
81
|
+
'Capture now snapshots the idle saved interactive session and requests a background worker wake; autoCapture must be true and disabled false.',
|
|
82
|
+
'Status, pause, resume and retry remain available when Remembrancer is disabled. Retry requires explicit UI confirmation.',
|
|
77
83
|
'Natural-language review requests remain supported.',
|
|
78
84
|
].join('\n');
|
|
79
85
|
|
|
86
|
+
const CAPTURE_COMMANDS = ['now', 'status', 'pause', 'resume', 'retry'] as const;
|
|
80
87
|
const REMEMBRANCER_SUBCOMMANDS = [
|
|
88
|
+
{
|
|
89
|
+
value: 'capture ',
|
|
90
|
+
label: 'capture',
|
|
91
|
+
description: 'Capture this session or control accepted jobs',
|
|
92
|
+
},
|
|
81
93
|
{ value: 'proposals', label: 'proposals', description: 'Review stored task proposals locally' },
|
|
82
94
|
{
|
|
83
95
|
value: 'seed ',
|
|
@@ -98,6 +110,11 @@ type RemembrancerCommandArgs =
|
|
|
98
110
|
| { ok: true; mode: 'help' }
|
|
99
111
|
| { ok: true; mode: 'proposals' }
|
|
100
112
|
| { ok: true; mode: 'seed'; duration: string }
|
|
113
|
+
| { ok: true; mode: 'capture'; action: 'now' }
|
|
114
|
+
| { ok: true; mode: 'capture'; action: 'status' }
|
|
115
|
+
| { ok: true; mode: 'capture'; action: 'pause' }
|
|
116
|
+
| { ok: true; mode: 'capture'; action: 'resume' }
|
|
117
|
+
| { ok: true; mode: 'capture'; action: 'retry'; jobId: string }
|
|
101
118
|
| { ok: false; message: string };
|
|
102
119
|
|
|
103
120
|
export function parseRemembrancerCommandArgs(args: string): RemembrancerCommandArgs {
|
|
@@ -107,6 +124,17 @@ export function parseRemembrancerCommandArgs(args: string): RemembrancerCommandA
|
|
|
107
124
|
if (tokens.length === 0 || (subcommand === 'help' && tokens.length === 1))
|
|
108
125
|
return { ok: true, mode: 'help' };
|
|
109
126
|
if (subcommand === 'proposals' && tokens.length === 1) return { ok: true, mode: 'proposals' };
|
|
127
|
+
if (subcommand === 'capture') {
|
|
128
|
+
const action = tokens[1];
|
|
129
|
+
if (
|
|
130
|
+
(action === 'now' || action === 'status' || action === 'pause' || action === 'resume') &&
|
|
131
|
+
tokens.length === 2
|
|
132
|
+
)
|
|
133
|
+
return { ok: true, mode: 'capture', action };
|
|
134
|
+
if (action === 'retry' && tokens.length === 3)
|
|
135
|
+
return { ok: true, mode: 'capture', action, jobId: tokens[2]! };
|
|
136
|
+
return { ok: false, message: `Invalid capture command. ${REMEMBRANCER_COMMAND_USAGE}` };
|
|
137
|
+
}
|
|
110
138
|
if (subcommand === 'help')
|
|
111
139
|
return { ok: false, message: `Help does not accept arguments. ${REMEMBRANCER_COMMAND_USAGE}` };
|
|
112
140
|
if (subcommand !== 'seed')
|
|
@@ -139,6 +167,17 @@ export function getRemembrancerArgumentCompletions(prefix: string) {
|
|
|
139
167
|
const tokens = input.trim().length === 0 ? [] : input.trim().split(/\s+/u);
|
|
140
168
|
|
|
141
169
|
if (tokens.length === 0) return REMEMBRANCER_SUBCOMMANDS;
|
|
170
|
+
if (tokens[0] === 'capture' && (tokens.length === 2 || trailingWhitespace)) {
|
|
171
|
+
if (tokens.length > 2 || (tokens.length === 2 && trailingWhitespace)) return null;
|
|
172
|
+
const partial = tokens.length === 2 ? tokens[1]! : '';
|
|
173
|
+
const matches = CAPTURE_COMMANDS.filter((action) => action.startsWith(partial)).map(
|
|
174
|
+
(action) => ({
|
|
175
|
+
value: `capture ${action}${action === 'retry' ? ' ' : ''}`,
|
|
176
|
+
label: action,
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
return matches.length > 0 ? matches : null;
|
|
180
|
+
}
|
|
142
181
|
if (tokens.length === 1) {
|
|
143
182
|
const token = tokens[0]!;
|
|
144
183
|
if (trailingWhitespace) {
|
|
@@ -158,6 +197,18 @@ export function getRemembrancerArgumentCompletions(prefix: string) {
|
|
|
158
197
|
: null;
|
|
159
198
|
}
|
|
160
199
|
|
|
200
|
+
function captureJobStatus(job: CaptureStatus['jobs'][number]): string {
|
|
201
|
+
return [
|
|
202
|
+
job.manifest.id,
|
|
203
|
+
`State: ${job.state}${job.activeAttemptId ? ' (active)' : ''}`,
|
|
204
|
+
`Current allowance: ${job.attemptCount}/${CAPTURE_MAX_ATTEMPTS} attempts used, ${Math.max(0, CAPTURE_MAX_ATTEMPTS - job.attemptCount)} remaining (not lifetime history)`,
|
|
205
|
+
`Stopped reason: ${!job.retryEligible && !job.activeAttemptId ? (job.diagnostic ?? 'none recorded') : 'not stopped'}`,
|
|
206
|
+
`Diagnostic: ${job.diagnostic ?? 'none'}`,
|
|
207
|
+
`Next attempt due: ${job.nextAttemptAt === null ? 'none' : new Date(job.nextAttemptAt).toISOString()}`,
|
|
208
|
+
`Blocked by predecessor: ${job.blockedBy ?? 'none'}`,
|
|
209
|
+
].join('\n');
|
|
210
|
+
}
|
|
211
|
+
|
|
161
212
|
const selectedParameters = Type.Object({
|
|
162
213
|
sessionId: Type.String(),
|
|
163
214
|
branchId: Type.String(),
|
|
@@ -192,11 +243,162 @@ function usesDefaultSessionDir(ctx: ExtensionContext): boolean {
|
|
|
192
243
|
return manager.usesDefaultSessionDir();
|
|
193
244
|
}
|
|
194
245
|
|
|
246
|
+
export const CAPTURE_TICK_MS = 2_000;
|
|
247
|
+
export const CAPTURE_RECOVERY_MS = 60_000;
|
|
248
|
+
|
|
195
249
|
export default function remembrancer(pi: ExtensionAPI) {
|
|
196
250
|
let db: CheckpointStore | undefined;
|
|
197
251
|
let batch: Batch | undefined;
|
|
252
|
+
let stopLifecycle: (() => void) | undefined;
|
|
253
|
+
let noticeGeneration = 0;
|
|
198
254
|
const store = () => (db ??= new CheckpointStore());
|
|
199
255
|
|
|
256
|
+
function startLifecycle(ctx: ExtensionContext) {
|
|
257
|
+
stopLifecycle?.();
|
|
258
|
+
if (ctx.mode !== 'tui') return;
|
|
259
|
+
const database = defaultCheckpointFile();
|
|
260
|
+
const inbox = join(dirname(database), 'capture-inbox');
|
|
261
|
+
const host = captureHost();
|
|
262
|
+
let stopped = false;
|
|
263
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
264
|
+
let nextWake = 0;
|
|
265
|
+
stopLifecycle = () => {
|
|
266
|
+
stopped = true;
|
|
267
|
+
clearTimeout(timer);
|
|
268
|
+
};
|
|
269
|
+
// Recursive scheduling gives one async tick, never overlapping slow reads/launches.
|
|
270
|
+
async function tick() {
|
|
271
|
+
try {
|
|
272
|
+
const notice = await readProposalNotice(database);
|
|
273
|
+
if (stopped) return;
|
|
274
|
+
if (notice && notice.generation > noticeGeneration) {
|
|
275
|
+
noticeGeneration = notice.generation;
|
|
276
|
+
if (notice.pending)
|
|
277
|
+
ctx.ui.notify(`${notice.pending} task proposals · /remembrancer proposals`, 'info');
|
|
278
|
+
}
|
|
279
|
+
} catch {
|
|
280
|
+
// A missing/corrupt derived notice cannot suppress recovery of accepted work.
|
|
281
|
+
}
|
|
282
|
+
if (stopped) return;
|
|
283
|
+
if (Date.now() >= nextWake) {
|
|
284
|
+
nextWake = Date.now() + CAPTURE_RECOVERY_MS;
|
|
285
|
+
try {
|
|
286
|
+
await access(database).catch(async (error: NodeJS.ErrnoException) => {
|
|
287
|
+
if (error.code !== 'ENOENT') throw error;
|
|
288
|
+
await access(inbox);
|
|
289
|
+
});
|
|
290
|
+
if (stopped) return;
|
|
291
|
+
await launchCaptureWorker(database, inbox, host);
|
|
292
|
+
} catch {
|
|
293
|
+
// Failed launch/crash is retried on a later bounded wake, not a chat turn.
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (!stopped) {
|
|
297
|
+
timer = setTimeout(() => void tick(), CAPTURE_TICK_MS);
|
|
298
|
+
timer.unref();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
void tick();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function wakeCapture(ctx: ExtensionContext) {
|
|
305
|
+
const database = defaultCheckpointFile();
|
|
306
|
+
try {
|
|
307
|
+
await launchCaptureWorker(database, join(dirname(database), 'capture-inbox'), captureHost());
|
|
308
|
+
} catch {
|
|
309
|
+
ctx.ui.notify(
|
|
310
|
+
'Capture state saved; worker launch failed. A later wake can recover it.',
|
|
311
|
+
'warning',
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function controlCapture(
|
|
317
|
+
parsed: Extract<RemembrancerCommandArgs, { mode: 'capture' }>,
|
|
318
|
+
ctx: ExtensionContext,
|
|
319
|
+
) {
|
|
320
|
+
try {
|
|
321
|
+
if (parsed.action === 'now') {
|
|
322
|
+
if (ctx.mode !== 'tui' || !ctx.hasUI)
|
|
323
|
+
throw new Error('Capture now requires an interactive Pi terminal.');
|
|
324
|
+
if (!ctx.isIdle())
|
|
325
|
+
throw new Error(
|
|
326
|
+
'Pi is busy. Wait for the current run to finish, then retry capture now.',
|
|
327
|
+
);
|
|
328
|
+
const source = currentSource(ctx);
|
|
329
|
+
if (!source) throw new Error('Capture now requires a saved Pi session.');
|
|
330
|
+
const config = loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted());
|
|
331
|
+
if (config.disabled || !config.autoCapture)
|
|
332
|
+
throw new Error(
|
|
333
|
+
'Capture now requires pi-remembrancer.autoCapture true and pi-remembrancer.disabled false in settings.',
|
|
334
|
+
);
|
|
335
|
+
const database = defaultCheckpointFile();
|
|
336
|
+
const accepted = await preserveHandoff({
|
|
337
|
+
id: randomUUID(),
|
|
338
|
+
inbox: join(dirname(database), 'capture-inbox'),
|
|
339
|
+
source,
|
|
340
|
+
execution: captureExecution(ctx),
|
|
341
|
+
});
|
|
342
|
+
await wakeCapture(ctx);
|
|
343
|
+
ctx.ui.notify(
|
|
344
|
+
`Capture accepted: ${accepted.manifest.id}. Worker wake requested; review may wait. Check /remembrancer capture status and /remembrancer proposals.${accepted.cleanupDiagnostic ? `\n${accepted.cleanupDiagnostic}` : ''}`,
|
|
345
|
+
accepted.cleanupDiagnostic ? 'warning' : 'info',
|
|
346
|
+
);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (parsed.action === 'status') {
|
|
350
|
+
const status = store().captureStatus();
|
|
351
|
+
ctx.ui.notify(
|
|
352
|
+
[
|
|
353
|
+
`Capture: ${status.paused ? 'paused' : 'running permitted'}`,
|
|
354
|
+
...(status.jobs.length ? status.jobs.map(captureJobStatus) : ['No unresolved jobs.']),
|
|
355
|
+
].join('\n\n'),
|
|
356
|
+
'info',
|
|
357
|
+
);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (parsed.action === 'pause' || parsed.action === 'resume') {
|
|
361
|
+
store().setCapturePaused(parsed.action === 'pause');
|
|
362
|
+
ctx.ui.notify(
|
|
363
|
+
parsed.action === 'pause'
|
|
364
|
+
? 'Capture paused. Active attempts revoked; cancellation is observed by the worker.'
|
|
365
|
+
: 'Capture resumed. Existing allowances, delays and predecessor ordering are unchanged.',
|
|
366
|
+
'info',
|
|
367
|
+
);
|
|
368
|
+
if (parsed.action === 'resume') await wakeCapture(ctx);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (ctx.mode !== 'tui' || !ctx.hasUI)
|
|
372
|
+
throw new Error(
|
|
373
|
+
'Capture retry requires explicit UI confirmation. No retry was authorized.',
|
|
374
|
+
);
|
|
375
|
+
const status = store().captureStatus();
|
|
376
|
+
const job = status.jobs.find((job) => job.manifest.id === parsed.jobId);
|
|
377
|
+
if (!job) throw new Error('No unresolved capture job with that exact full ID.');
|
|
378
|
+
if (job.state !== 'failed' || job.retryEligible || job.activeAttemptId)
|
|
379
|
+
throw new Error('Only stopped, inactive capture jobs can be deliberately retried.');
|
|
380
|
+
const confirmed = await ctx.ui.confirm(
|
|
381
|
+
'Retry capture job?',
|
|
382
|
+
`${captureJobStatus(job)}\n\nReplace the current allowance with ${CAPTURE_MAX_ATTEMPTS} fresh whole-review attempts? Capture ${status.paused ? 'is paused and stays paused' : 'pause state is unchanged'}. Predecessors still block this job.`,
|
|
383
|
+
);
|
|
384
|
+
if (!confirmed) {
|
|
385
|
+
ctx.ui.notify('Capture retry cancelled. No allowance changed.', 'info');
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
store().retryCaptureJob(parsed.jobId, job.revision);
|
|
389
|
+
ctx.ui.notify(
|
|
390
|
+
`Capture retry queued: ${parsed.jobId}. Pause and predecessor ordering are unchanged.`,
|
|
391
|
+
'info',
|
|
392
|
+
);
|
|
393
|
+
await wakeCapture(ctx);
|
|
394
|
+
} catch (error) {
|
|
395
|
+
ctx.ui.notify(
|
|
396
|
+
`Capture control failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
397
|
+
'error',
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
200
402
|
function currentSource(ctx: ExtensionContext): Source | undefined {
|
|
201
403
|
const sm = ctx.sessionManager;
|
|
202
404
|
const file = sm.getSessionFile();
|
|
@@ -233,7 +435,7 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
233
435
|
}
|
|
234
436
|
|
|
235
437
|
pi.registerCommand(REMEMBRANCER_COMMAND_NAME, {
|
|
236
|
-
description: 'Review
|
|
438
|
+
description: 'Review proposals, seed history, capture this session or control capture jobs',
|
|
237
439
|
getArgumentCompletions: getRemembrancerArgumentCompletions,
|
|
238
440
|
handler: async (args, ctx) => {
|
|
239
441
|
const parsed = parseRemembrancerCommandArgs(args);
|
|
@@ -245,6 +447,10 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
245
447
|
ctx.ui.notify(REMEMBRANCER_HELP, 'info');
|
|
246
448
|
return;
|
|
247
449
|
}
|
|
450
|
+
if (parsed.mode === 'capture') {
|
|
451
|
+
await controlCapture(parsed, ctx);
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
248
454
|
if (loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted()).disabled) {
|
|
249
455
|
ctx.ui.notify(
|
|
250
456
|
'Remembrancer is disabled in settings. Set pi-remembrancer.disabled to false to enable it.',
|
|
@@ -359,6 +565,8 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
359
565
|
}
|
|
360
566
|
|
|
361
567
|
pi.on('session_start', (_event, ctx) => {
|
|
568
|
+
// Recovery/notices are independent of authorization for NEW handoffs.
|
|
569
|
+
startLifecycle(ctx);
|
|
362
570
|
if (loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted()).disabled) return;
|
|
363
571
|
registerReviewTool();
|
|
364
572
|
pi.registerTool({
|
|
@@ -376,23 +584,61 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
376
584
|
});
|
|
377
585
|
enroll(ctx);
|
|
378
586
|
if (ctx.mode === 'tui') {
|
|
379
|
-
const
|
|
380
|
-
|
|
587
|
+
const notice = store().proposalNotice();
|
|
588
|
+
noticeGeneration = notice.generation;
|
|
589
|
+
if (notice.pending)
|
|
590
|
+
ctx.ui.notify(`${notice.pending} task proposals · /remembrancer proposals`, 'info');
|
|
381
591
|
}
|
|
382
592
|
});
|
|
383
593
|
pi.on('session_shutdown', async (event, ctx) => {
|
|
594
|
+
stopLifecycle?.();
|
|
595
|
+
let phase = 'manual-release';
|
|
596
|
+
let artifactId = 'no-handoff';
|
|
384
597
|
try {
|
|
385
|
-
const deadline = Date.now() + CAPTURE_BUDGET_MS;
|
|
386
598
|
try {
|
|
387
|
-
// Abandon manual coverage
|
|
599
|
+
// Abandon unfinished manual coverage; the worker never inherits that lock.
|
|
388
600
|
release();
|
|
389
|
-
|
|
601
|
+
const source = ctx.mode === 'tui' ? currentSource(ctx) : undefined;
|
|
602
|
+
if (source) {
|
|
603
|
+
phase = 'admission-configuration';
|
|
604
|
+
const config = loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted());
|
|
605
|
+
if (config.autoCapture && !config.disabled) {
|
|
606
|
+
artifactId = randomUUID();
|
|
607
|
+
const execution = captureExecution(ctx);
|
|
608
|
+
const database = defaultCheckpointFile();
|
|
609
|
+
const inbox = join(dirname(database), 'capture-inbox');
|
|
610
|
+
phase = 'preservation';
|
|
611
|
+
const accepted = await preserveHandoff({ id: artifactId, inbox, source, execution });
|
|
612
|
+
if (accepted.cleanupDiagnostic) {
|
|
613
|
+
try {
|
|
614
|
+
ctx.ui.notify(
|
|
615
|
+
`Remembrancer accepted capture: ${accepted.cleanupDiagnostic}`,
|
|
616
|
+
'warning',
|
|
617
|
+
);
|
|
618
|
+
} catch {
|
|
619
|
+
// Notification failure cannot revoke acceptance or suppress launch.
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// A failed launch leaves the durable ready manifest for the next wake.
|
|
623
|
+
phase = 'worker-launch';
|
|
624
|
+
await launchCaptureWorker(database, inbox, execution.host!);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
390
627
|
} finally {
|
|
391
|
-
|
|
392
|
-
|
|
628
|
+
try {
|
|
629
|
+
const previousPhase = phase;
|
|
630
|
+
phase = 'foreground-close';
|
|
631
|
+
db?.close();
|
|
632
|
+
phase = previousPhase;
|
|
633
|
+
} finally {
|
|
634
|
+
db = undefined;
|
|
635
|
+
}
|
|
393
636
|
}
|
|
394
637
|
} catch (error) {
|
|
395
|
-
const detail =
|
|
638
|
+
const detail =
|
|
639
|
+
error instanceof CaptureHandoffError
|
|
640
|
+
? error.message
|
|
641
|
+
: new CaptureHandoffError(phase, 'shutdown-failed', artifactId, error).message;
|
|
396
642
|
ctx.ui.notify(`Remembrancer shutdown (${event.reason}) failed:\n${detail}`, 'warning');
|
|
397
643
|
}
|
|
398
644
|
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { chmodSync, closeSync, openSync } from 'node:fs';
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
|
|
4
|
+
/** @param {string} filename */
|
|
5
|
+
export function openPrivateSqlite(filename) {
|
|
6
|
+
if (filename !== ':memory:') {
|
|
7
|
+
// Closing a second descriptor for an existing SQLite file can drop this
|
|
8
|
+
// process's POSIX locks, even those held by another DatabaseSync instance.
|
|
9
|
+
try {
|
|
10
|
+
closeSync(openSync(filename, 'ax', 0o600));
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (error.code !== 'EEXIST') throw error;
|
|
13
|
+
chmodSync(filename, 0o600);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return new DatabaseSync(filename);
|
|
17
|
+
}
|
|
@@ -1,13 +1,227 @@
|
|
|
1
|
-
import { Type } from '@
|
|
1
|
+
import { Type, type Static } from '@sinclair/typebox';
|
|
2
|
+
import { CaptureRetryableError } from './capture-jobs.js';
|
|
2
3
|
import type { CheckpointStore } from './checkpoints.js';
|
|
4
|
+
import type { Proposal, ProposalSource } from './proposals.js';
|
|
5
|
+
import {
|
|
6
|
+
fitsResponse,
|
|
7
|
+
fitPrefixLength,
|
|
8
|
+
REVIEW_RESPONSE_MAX_BYTES,
|
|
9
|
+
safePrefixLength,
|
|
10
|
+
serializedResponse,
|
|
11
|
+
splitsSurrogatePair,
|
|
12
|
+
} from './review-pages.js';
|
|
3
13
|
|
|
4
14
|
export const proposalReadDescription =
|
|
5
|
-
'
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
15
|
+
'Discover stored proposals with compact list summaries (default action: list, nextOffset as offset). Summaries are not full proposals. Read action: detail with id/revision and join json fragments by position, then JSON.parse the joined text; sources are excluded. Read action: evidence with id/revision for exact saved quotes and source metadata. Follow next until null on detail/evidence. All positions are UTF-16; source offset is distinct from quotePosition. Every detail/evidence request checks revision, including the first. On missing/stale proposals discard partial reads and refresh list/current detail; automatic reviewers must abort, never retry in-review. Existing decided rows are temporary. Each complete JSON response is capped at 51,200 UTF-8 bytes.';
|
|
16
|
+
const cursorInteger = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
|
|
17
|
+
export const proposalReadParameters = Type.Object(
|
|
18
|
+
{
|
|
19
|
+
action: Type.Optional(Type.String({ enum: ['list', 'detail', 'evidence'] })),
|
|
20
|
+
offset: Type.Optional(cursorInteger),
|
|
21
|
+
id: Type.Optional(Type.String({ minLength: 1 })),
|
|
22
|
+
revision: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })),
|
|
23
|
+
position: Type.Optional(cursorInteger),
|
|
24
|
+
index: Type.Optional(cursorInteger),
|
|
25
|
+
quotePosition: Type.Optional(cursorInteger),
|
|
26
|
+
},
|
|
27
|
+
{ additionalProperties: false },
|
|
28
|
+
);
|
|
29
|
+
export type ProposalReadArgs = Static<typeof proposalReadParameters>;
|
|
30
|
+
const LIST_LIMIT = 20;
|
|
31
|
+
const EVIDENCE_LIMIT = 100;
|
|
32
|
+
|
|
33
|
+
function integer(value: unknown, name: string, minimum = 0): asserts value is number {
|
|
34
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum)
|
|
35
|
+
throw new Error(`Invalid proposal ${name}: expected a safe integer >= ${minimum}.`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function summary(proposal: Proposal) {
|
|
39
|
+
const current = proposal.draft ?? proposal;
|
|
40
|
+
const description =
|
|
41
|
+
current.change.operation === 'complete'
|
|
42
|
+
? (current.expected?.fields.description ?? '')
|
|
43
|
+
: (current.change.fields.description ?? current.expected?.fields.description ?? '');
|
|
44
|
+
const length = safePrefixLength(description, 0, 160);
|
|
45
|
+
return {
|
|
46
|
+
id: proposal.id,
|
|
47
|
+
revision: proposal.revision,
|
|
48
|
+
state: proposal.state,
|
|
49
|
+
operation: current.change.operation,
|
|
50
|
+
targetUuid: current.change.operation === 'add' ? null : current.change.targetUuid,
|
|
51
|
+
label: description.slice(0, length),
|
|
52
|
+
labelTruncated: length < description.length,
|
|
53
|
+
hasDraft: proposal.draft !== null,
|
|
54
|
+
hasQuestion: proposal.question !== null || current.question !== null,
|
|
55
|
+
evidenceCount: proposal.sources.length,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
type ProposalReader = Pick<CheckpointStore, 'proposal' | 'proposals'>;
|
|
60
|
+
|
|
61
|
+
function list(db: ProposalReader, offset: number) {
|
|
62
|
+
integer(offset, 'offset');
|
|
63
|
+
const candidates = db.proposals(undefined, offset, LIST_LIMIT + 1);
|
|
64
|
+
const proposals: ReturnType<typeof summary>[] = [];
|
|
65
|
+
for (const proposal of candidates.slice(0, LIST_LIMIT)) {
|
|
66
|
+
const nextOffset = offset + proposals.length + 1;
|
|
67
|
+
integer(nextOffset, 'next offset');
|
|
68
|
+
const item = summary(proposal);
|
|
69
|
+
const page = {
|
|
70
|
+
action: 'list',
|
|
71
|
+
proposals: [...proposals, item],
|
|
72
|
+
nextOffset: candidates.length > proposals.length + 1 ? nextOffset : null,
|
|
73
|
+
};
|
|
74
|
+
if (!fitsResponse(page)) {
|
|
75
|
+
if (!proposals.length) throw new Error('Proposal summary metadata or envelope cannot fit.');
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
proposals.push(item);
|
|
79
|
+
}
|
|
80
|
+
const data = {
|
|
81
|
+
action: 'list' as const,
|
|
82
|
+
proposals,
|
|
83
|
+
nextOffset: candidates.length > proposals.length ? offset + proposals.length : null,
|
|
84
|
+
};
|
|
85
|
+
serializedResponse(data);
|
|
86
|
+
return data;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function position(text: string, value: number, name: string): void {
|
|
90
|
+
integer(value, name);
|
|
91
|
+
if (value > text.length) throw new Error(`Invalid proposal ${name}: beyond the text.`);
|
|
92
|
+
if (splitsSurrogatePair(text, value))
|
|
93
|
+
throw new Error(
|
|
94
|
+
`Invalid proposal ${name}: splits a surrogate pair; use the returned next cursor.`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Size the complete encoded envelope, not just the unescaped fragment.
|
|
99
|
+
function fragmentLength(text: string, start: number, fits: (length: number) => boolean): number {
|
|
100
|
+
return fitPrefixLength(text, start, fits, REVIEW_RESPONSE_MAX_BYTES);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
type EvidenceFragment = ProposalSource & {
|
|
104
|
+
index: number;
|
|
105
|
+
quotePosition: number;
|
|
106
|
+
continues: boolean;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/** Typed read for internal callers; public detail/evidence paging uses the same checks. */
|
|
110
|
+
export function readProposal(db: ProposalReader, id: string, revision: number): Proposal {
|
|
111
|
+
if (typeof id !== 'string' || !id.trim()) throw new Error('Invalid proposal ID.');
|
|
112
|
+
integer(revision, 'revision', 1);
|
|
113
|
+
const proposal = db.proposal(id);
|
|
114
|
+
if (!proposal)
|
|
115
|
+
throw new CaptureRetryableError(
|
|
116
|
+
'Missing proposal; discard partial reads and refresh the list.',
|
|
117
|
+
);
|
|
118
|
+
if (proposal.revision !== revision)
|
|
119
|
+
throw new CaptureRetryableError(
|
|
120
|
+
'Stale proposal; discard partial reads and refresh the list/current detail.',
|
|
121
|
+
);
|
|
122
|
+
return proposal;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function readProposals(db: ProposalReader, args: ProposalReadArgs) {
|
|
126
|
+
const action = args.action ?? 'list';
|
|
127
|
+
const allowed =
|
|
128
|
+
action === 'list'
|
|
129
|
+
? ['action', 'offset']
|
|
130
|
+
: action === 'detail'
|
|
131
|
+
? ['action', 'id', 'revision', 'position']
|
|
132
|
+
: action === 'evidence'
|
|
133
|
+
? ['action', 'id', 'revision', 'index', 'quotePosition']
|
|
134
|
+
: [];
|
|
135
|
+
if (!allowed.length || Object.keys(args).some((key) => !allowed.includes(key)))
|
|
136
|
+
throw new Error('Invalid proposal read action or cursor fields.');
|
|
137
|
+
if (action === 'list') return list(db, args.offset ?? 0);
|
|
138
|
+
if (typeof args.id !== 'string' || !args.id.trim()) throw new Error('Invalid proposal ID.');
|
|
139
|
+
integer(args.revision, 'revision', 1);
|
|
140
|
+
const proposal = readProposal(db, args.id, args.revision);
|
|
141
|
+
const identity = { id: proposal.id, revision: proposal.revision };
|
|
142
|
+
if (action === 'detail') {
|
|
143
|
+
const text = JSON.stringify(
|
|
144
|
+
Object.fromEntries(Object.entries(proposal).filter(([key]) => key !== 'sources')),
|
|
145
|
+
);
|
|
146
|
+
const start = args.position ?? 0;
|
|
147
|
+
position(text, start, 'position');
|
|
148
|
+
const build = (length: number) => ({
|
|
149
|
+
action: 'detail' as const,
|
|
150
|
+
...identity,
|
|
151
|
+
position: start,
|
|
152
|
+
json: text.slice(start, start + length),
|
|
153
|
+
next:
|
|
154
|
+
start + length < text.length
|
|
155
|
+
? { action: 'detail' as const, ...identity, position: start + length }
|
|
156
|
+
: null,
|
|
157
|
+
});
|
|
158
|
+
const length = fragmentLength(text, start, (length) => fitsResponse(build(length)));
|
|
159
|
+
if (length === 0 && start < text.length)
|
|
160
|
+
throw new Error('Proposal detail metadata or envelope cannot fit with positive progress.');
|
|
161
|
+
const data = build(length);
|
|
162
|
+
serializedResponse(data);
|
|
163
|
+
return data;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let index = args.index ?? 0;
|
|
167
|
+
let quotePosition = args.quotePosition ?? 0;
|
|
168
|
+
integer(index, 'evidence index');
|
|
169
|
+
integer(quotePosition, 'quotePosition');
|
|
170
|
+
if (index > proposal.sources.length || (index === proposal.sources.length && quotePosition !== 0))
|
|
171
|
+
throw new Error('Invalid proposal evidence cursor: beyond the sources.');
|
|
172
|
+
const entries: EvidenceFragment[] = [];
|
|
173
|
+
const build = (items: EvidenceFragment[], nextIndex: number, nextPosition: number) => ({
|
|
174
|
+
action: 'evidence' as const,
|
|
175
|
+
...identity,
|
|
176
|
+
entries: items,
|
|
177
|
+
next:
|
|
178
|
+
nextIndex < proposal.sources.length
|
|
179
|
+
? {
|
|
180
|
+
action: 'evidence' as const,
|
|
181
|
+
...identity,
|
|
182
|
+
index: nextIndex,
|
|
183
|
+
quotePosition: nextPosition,
|
|
184
|
+
}
|
|
185
|
+
: null,
|
|
186
|
+
});
|
|
187
|
+
while (index < proposal.sources.length && entries.length < EVIDENCE_LIMIT) {
|
|
188
|
+
const source = proposal.sources[index]!;
|
|
189
|
+
position(source.quote, quotePosition, 'quotePosition');
|
|
190
|
+
if (quotePosition === source.quote.length && quotePosition !== 0)
|
|
191
|
+
throw new Error('Invalid proposal quotePosition: completed quotes must advance the index.');
|
|
192
|
+
const candidate = (length: number) => {
|
|
193
|
+
const end = quotePosition + length;
|
|
194
|
+
const continues = end < source.quote.length;
|
|
195
|
+
const entry = {
|
|
196
|
+
...source,
|
|
197
|
+
index,
|
|
198
|
+
quotePosition,
|
|
199
|
+
quote: source.quote.slice(quotePosition, end),
|
|
200
|
+
continues,
|
|
201
|
+
};
|
|
202
|
+
return { entry, nextIndex: continues ? index : index + 1, nextPosition: continues ? end : 0 };
|
|
203
|
+
};
|
|
204
|
+
const length = fragmentLength(source.quote, quotePosition, (length) => {
|
|
205
|
+
const { entry, nextIndex, nextPosition } = candidate(length);
|
|
206
|
+
return fitsResponse(build([...entries, entry], nextIndex, nextPosition));
|
|
207
|
+
});
|
|
208
|
+
const { entry, nextIndex, nextPosition } = candidate(length);
|
|
209
|
+
if (
|
|
210
|
+
(length === 0 && source.quote.length > 0) ||
|
|
211
|
+
!fitsResponse(build([...entries, entry], nextIndex, nextPosition))
|
|
212
|
+
) {
|
|
213
|
+
if (!entries.length)
|
|
214
|
+
throw new Error(
|
|
215
|
+
'Proposal evidence metadata or envelope cannot fit with positive progress.',
|
|
216
|
+
);
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
entries.push(entry);
|
|
220
|
+
index = nextIndex;
|
|
221
|
+
quotePosition = nextPosition;
|
|
222
|
+
if (entry.continues) break;
|
|
223
|
+
}
|
|
224
|
+
const data = build(entries, index, quotePosition);
|
|
225
|
+
serializedResponse(data);
|
|
226
|
+
return data;
|
|
13
227
|
}
|