@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.
Files changed (29) hide show
  1. package/README.md +58 -17
  2. package/extensions/remembrancer/capture-artifacts.ts +211 -0
  3. package/extensions/remembrancer/capture-handoff.ts +714 -0
  4. package/extensions/remembrancer/capture-jobs.ts +112 -0
  5. package/extensions/remembrancer/capture-matches.ts +145 -0
  6. package/extensions/remembrancer/capture-notices.ts +54 -0
  7. package/extensions/remembrancer/capture-publication-lock.mjs +37 -0
  8. package/extensions/remembrancer/capture-review.ts +84 -12
  9. package/extensions/remembrancer/capture-sizing.ts +63 -0
  10. package/extensions/remembrancer/capture-submission.ts +289 -0
  11. package/extensions/remembrancer/capture-worker-bootstrap.mjs +53 -0
  12. package/extensions/remembrancer/capture-worker.ts +341 -0
  13. package/extensions/remembrancer/capture.ts +262 -136
  14. package/extensions/remembrancer/checkpoints.ts +687 -119
  15. package/extensions/remembrancer/config.ts +31 -1
  16. package/extensions/remembrancer/evidence.ts +318 -74
  17. package/extensions/remembrancer/index.ts +260 -14
  18. package/extensions/remembrancer/private-sqlite.mjs +17 -0
  19. package/extensions/remembrancer/proposal-read.ts +223 -9
  20. package/extensions/remembrancer/proposal-ui.ts +608 -191
  21. package/extensions/remembrancer/proposals.ts +44 -9
  22. package/extensions/remembrancer/review-findings.ts +178 -0
  23. package/extensions/remembrancer/review-pages.ts +58 -16
  24. package/extensions/remembrancer/review-plan.ts +27 -0
  25. package/extensions/remembrancer/reviewer-budget.ts +53 -0
  26. package/extensions/remembrancer/reviewer.ts +166 -30
  27. package/extensions/remembrancer/taskwarrior.ts +95 -14
  28. package/package.json +5 -4
  29. package/skills/remembrancer/SKILL.md +35 -19
@@ -1,13 +1,28 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { chmodSync, closeSync, mkdirSync, openSync } from 'node:fs';
2
+ import { mkdirSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { dirname, isAbsolute, join } from 'node:path';
5
- import { DatabaseSync } from 'node:sqlite';
5
+ import type { DatabaseSync } from 'node:sqlite';
6
+ import { isDeepStrictEqual } from 'node:util';
6
7
 
8
+ import { openPrivateSqlite } from './private-sqlite.mjs';
7
9
  import { CaptureReview } from './capture-review.js';
10
+ import {
11
+ CAPTURE_MAX_ATTEMPTS,
12
+ CAPTURE_RETRY_DELAY_MS,
13
+ CapturePreparationError,
14
+ CaptureRetryableError,
15
+ CaptureWorkerOwnership,
16
+ type CaptureAttempt,
17
+ type CaptureJob,
18
+ type CaptureStatus,
19
+ } from './capture-jobs.js';
20
+ import { physicalInbox, validateReadyManifest, type ReadyManifest } from './capture-handoff.js';
21
+ import { prepareHistoricalReview } from './evidence.js';
8
22
  import {
9
23
  validateDraft,
10
24
  validateSnapshot,
25
+ unionProposalSources,
11
26
  type Proposal,
12
27
  type ProposalDraft,
13
28
  type ProposalSubmission,
@@ -25,7 +40,7 @@ export type FinishPlan = {
25
40
  checkpoints?: readonly (Tip | Checkpoint)[];
26
41
  };
27
42
 
28
- function defaultFile(): string {
43
+ export function defaultCheckpointFile(): string {
29
44
  const state = process.env['XDG_STATE_HOME'];
30
45
  return join(
31
46
  state && isAbsolute(state) ? state : join(homedir(), '.local', 'state'),
@@ -35,18 +50,8 @@ function defaultFile(): string {
35
50
  }
36
51
 
37
52
  function openPrivate(filename: string): DatabaseSync {
38
- if (filename !== ':memory:') {
39
- mkdirSync(dirname(filename), { recursive: true, mode: 0o700 });
40
- // Closing a second descriptor for an existing SQLite file can drop this
41
- // process's POSIX locks, even those held by another DatabaseSync instance.
42
- try {
43
- closeSync(openSync(filename, 'ax', 0o600));
44
- } catch (error) {
45
- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
46
- chmodSync(filename, 0o600);
47
- }
48
- }
49
- return new DatabaseSync(filename);
53
+ if (filename !== ':memory:') mkdirSync(dirname(filename), { recursive: true, mode: 0o700 });
54
+ return openPrivateSqlite(filename);
50
55
  }
51
56
 
52
57
  function absoluteTimestamp(value: string | null | undefined): string | null {
@@ -56,6 +61,17 @@ function absoluteTimestamp(value: string | null | undefined): string | null {
56
61
  return new Date(milliseconds).toISOString();
57
62
  }
58
63
 
64
+ const SCHEMA_VERSION = 5;
65
+
66
+ function schemaVersion(db: DatabaseSync): number {
67
+ const version = Number(db.prepare('PRAGMA user_version').get()!['user_version']);
68
+ if (version > SCHEMA_VERSION)
69
+ throw new Error(
70
+ `Unsupported remembrancer schema version ${version} (maximum ${SCHEMA_VERSION})`,
71
+ );
72
+ return version;
73
+ }
74
+
59
75
  function tableHasColumn(db: DatabaseSync, table: string, column: string): boolean {
60
76
  return (db.prepare(`PRAGMA table_info(${table})`).all() as { name?: string }[]).some(
61
77
  (item) => item.name === column,
@@ -67,17 +83,48 @@ function checkpointFromTip(tip: Tip): Checkpoint {
67
83
  return { ...tip, since: candidate.since ?? null };
68
84
  }
69
85
 
86
+ // Unsupported rows fence their session even when their order cannot be interpreted.
87
+ const predecessor = `SELECT earlier.id FROM capture_jobs AS earlier
88
+ WHERE earlier.id <> job.id AND earlier.session_id = job.session_id
89
+ AND earlier.state <> 'completed'
90
+ AND (json_extract(earlier.body, '$.version') IS NOT 3
91
+ OR earlier.admission_order < job.admission_order)
92
+ ORDER BY earlier.admission_order LIMIT 1`;
93
+
70
94
  export class CheckpointStore {
71
95
  private db: DatabaseSync;
72
96
  private filename: string;
73
97
  private reviewLock: DatabaseSync | undefined;
74
- private capture: CaptureReview | undefined;
98
+ private jobCapture:
99
+ | {
100
+ owner: CaptureWorkerOwnership;
101
+ attempt: CaptureAttempt;
102
+ review: CaptureReview;
103
+ generation: number;
104
+ body: string;
105
+ }
106
+ | undefined;
75
107
 
76
- constructor(filename = defaultFile()) {
108
+ get file(): string {
109
+ return this.filename;
110
+ }
111
+
112
+ constructor(filename = defaultCheckpointFile()) {
77
113
  this.filename = filename;
78
114
  this.db = openPrivate(filename);
115
+ if (filename !== ':memory:') this.filename = realpathSync(filename);
116
+ let migrating = false;
79
117
  try {
80
- this.db.exec('PRAGMA busy_timeout = 5000; BEGIN IMMEDIATE;');
118
+ this.db.exec('PRAGMA busy_timeout = 5000');
119
+ if (schemaVersion(this.db) === SCHEMA_VERSION) return;
120
+ this.db.exec('BEGIN IMMEDIATE');
121
+ migrating = true;
122
+ // Another opener may have migrated while this connection waited for the lock.
123
+ const version = schemaVersion(this.db);
124
+ if (version === SCHEMA_VERSION) {
125
+ this.db.exec('COMMIT');
126
+ return;
127
+ }
81
128
  this.db.exec(`
82
129
  CREATE TABLE IF NOT EXISTS sources (
83
130
  session_id TEXT PRIMARY KEY,
@@ -98,10 +145,91 @@ export class CheckpointStore {
98
145
  id TEXT PRIMARY KEY, revision INTEGER NOT NULL, state TEXT NOT NULL,
99
146
  body TEXT NOT NULL
100
147
  )`);
101
- this.db.exec('COMMIT');
148
+ this.db.exec(`
149
+ CREATE TABLE IF NOT EXISTS review_context (
150
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
151
+ generation INTEGER NOT NULL, notice_generation INTEGER NOT NULL
152
+ );
153
+ INSERT OR IGNORE INTO review_context VALUES (1, 0, 0);
154
+ CREATE TABLE IF NOT EXISTS capture_jobs (
155
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, snapshot TEXT NOT NULL,
156
+ accepted_at TEXT NOT NULL, admission_order TEXT NOT NULL, body TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('queued', 'completed', 'failed')),
157
+ retry_eligible INTEGER NOT NULL CHECK(retry_eligible IN (0, 1)), diagnostic TEXT,
158
+ CHECK ((state = 'queued' AND retry_eligible = 1 AND diagnostic IS NULL)
159
+ OR (state = 'completed' AND retry_eligible = 0 AND diagnostic IS NULL)
160
+ OR (state = 'failed' AND diagnostic IS NOT NULL AND length(trim(diagnostic)) > 0))
161
+ );
162
+ `);
163
+ // Version 3 installs these triggers once, including on existing version 2 databases.
164
+ // Triggers keep each mutation and its generation in the same transaction,
165
+ // including existing single-statement manual proposal/application writes.
166
+ if (version < 3)
167
+ for (const table of ['sources', 'reviewed_boundaries', 'proposals']) {
168
+ for (const operation of ['INSERT', 'UPDATE', 'DELETE']) {
169
+ this.db.exec(`DROP TRIGGER IF EXISTS context_${table}_${operation}`);
170
+ let condition = '';
171
+ if (table === 'sources' && operation === 'INSERT')
172
+ condition = 'WHEN NEW.seed_since IS NOT NULL';
173
+ if (table === 'sources' && operation === 'UPDATE')
174
+ condition = 'WHEN NEW.seed_since IS NOT OLD.seed_since';
175
+ this.db.exec(`CREATE TRIGGER context_${table}_${operation}
176
+ AFTER ${operation} ON ${table} ${condition} BEGIN
177
+ UPDATE review_context SET generation = generation + 1
178
+ ${table === 'proposals' ? ', notice_generation = notice_generation + 1' : ''}
179
+ WHERE singleton = 1;
180
+ END`);
181
+ }
182
+ }
183
+ if (version < 1) {
184
+ const update = this.db.prepare('UPDATE proposals SET revision = ?, body = ? WHERE id = ?');
185
+ for (const row of this.db.prepare('SELECT id, revision, body FROM proposals').iterate()) {
186
+ const proposal = JSON.parse(row['body'] as string) as Proposal & { history?: unknown };
187
+ const sources = unionProposalSources(proposal.sources);
188
+ if (!Object.hasOwn(proposal, 'history') && sources.length === proposal.sources.length)
189
+ continue;
190
+ delete proposal.history;
191
+ proposal.sources = sources;
192
+ proposal.revision = Number(row['revision']) + 1;
193
+ update.run(proposal.revision, JSON.stringify(proposal), row['id'] as string);
194
+ }
195
+ this.db.exec('PRAGMA user_version = 1');
196
+ }
197
+ if (version < 2) {
198
+ this.db.exec(`
199
+ ALTER TABLE capture_jobs ADD COLUMN attempt_count INTEGER NOT NULL DEFAULT 0
200
+ CHECK(attempt_count >= 0 AND attempt_count <= ${CAPTURE_MAX_ATTEMPTS});
201
+ ALTER TABLE capture_jobs ADD COLUMN active_attempt_id TEXT;
202
+ ALTER TABLE capture_jobs ADD COLUMN next_attempt_at INTEGER;
203
+ ALTER TABLE capture_jobs ADD COLUMN revision INTEGER NOT NULL DEFAULT 1 CHECK(revision > 0);
204
+ CREATE TABLE capture_control (
205
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
206
+ paused INTEGER NOT NULL CHECK(paused IN (0, 1))
207
+ );
208
+ INSERT INTO capture_control (singleton, paused) VALUES (1, 0);
209
+ UPDATE capture_jobs SET state = 'failed', retry_eligible = 0,
210
+ diagnostic = CASE WHEN diagnostic IS NULL THEN '' ELSE diagnostic || '; ' END
211
+ || 'Historical attempts unknown; explicit retry required'
212
+ WHERE state <> 'completed';
213
+ PRAGMA user_version = 2;
214
+ `);
215
+ }
216
+ this.db.exec(`
217
+ CREATE INDEX IF NOT EXISTS capture_jobs_runnable_order ON capture_jobs(admission_order)
218
+ WHERE state = 'queued' OR (state = 'failed' AND retry_eligible = 1);
219
+ CREATE INDEX IF NOT EXISTS capture_jobs_unresolved_session_order
220
+ ON capture_jobs(session_id, admission_order) WHERE state <> 'completed';
221
+ `);
222
+ if (version < 5)
223
+ this.db.exec(`
224
+ ALTER TABLE capture_jobs ADD COLUMN snapshot_cleanup_pending INTEGER NOT NULL DEFAULT 1
225
+ CHECK(snapshot_cleanup_pending IN (0, 1));
226
+ CREATE INDEX capture_jobs_snapshot_cleanup ON capture_jobs(snapshot_cleanup_pending)
227
+ WHERE state = 'completed' AND snapshot_cleanup_pending = 1;
228
+ `);
229
+ this.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}; COMMIT`);
102
230
  } catch (error) {
103
231
  try {
104
- this.db.exec('ROLLBACK');
232
+ if (migrating) this.db.exec('ROLLBACK');
105
233
  } finally {
106
234
  this.db.close();
107
235
  }
@@ -112,6 +240,16 @@ export class CheckpointStore {
112
240
  // A separate lock file lets other Pi sessions enroll during an interactive review.
113
241
  // SQLite releases this transaction's OS lock on close, including process death.
114
242
  claimReview(): void {
243
+ this.claimReviewLock();
244
+ try {
245
+ this.db.exec('UPDATE review_context SET generation = generation + 1 WHERE singleton = 1');
246
+ } catch (error) {
247
+ this.releaseReview();
248
+ throw error;
249
+ }
250
+ }
251
+
252
+ private claimReviewLock(): void {
115
253
  if (this.reviewLock) throw new Error('A remembrancer review is already open');
116
254
  const lock = openPrivate(this.filename === ':memory:' ? ':memory:' : this.filename + '.lock');
117
255
  try {
@@ -128,7 +266,6 @@ export class CheckpointStore {
128
266
  releaseReview(): void {
129
267
  this.reviewLock?.close();
130
268
  this.reviewLock = undefined;
131
- this.capture = undefined;
132
269
  }
133
270
 
134
271
  proposals(state?: ProposalState, offset = 0, limit = 50): Proposal[] {
@@ -159,14 +296,25 @@ export class CheckpointStore {
159
296
  );
160
297
  }
161
298
 
299
+ assertProposalRevision(id: string, revision: number): void {
300
+ const row = this.db.prepare('SELECT revision FROM proposals WHERE id = ?').get(id);
301
+ if (!row)
302
+ throw new CaptureRetryableError(
303
+ 'Missing proposal; discard partial reads and refresh the list.',
304
+ );
305
+ if (row['revision'] !== revision)
306
+ throw new CaptureRetryableError(
307
+ 'Stale proposal; discard partial reads and refresh the list/current detail.',
308
+ );
309
+ }
310
+
162
311
  proposal(id: string): Proposal | undefined {
163
312
  const row = this.db.prepare('SELECT body FROM proposals WHERE id = ?').get(id);
164
313
  return row ? (JSON.parse(row['body'] as string) as Proposal) : undefined;
165
314
  }
166
315
 
167
- private saveProposal(proposal: Proposal, expectedRevision?: number): void {
168
- // Draft decisions have no active application. Outcomes retain the claim and
169
- // snapshot they describe; previous applications live only in history.
316
+ private saveProposal(proposal: Proposal, expectedRevision?: number): Proposal {
317
+ // Draft decisions have no active application. Outcomes retain their claim and snapshot.
170
318
  const { state, claim, result, applicationBefore } = proposal;
171
319
  const valid =
172
320
  state === 'pending' || state === 'dismissed'
@@ -178,6 +326,17 @@ export class CheckpointStore {
178
326
  : ['applied', 'already_satisfied', 'uncertain'].includes(state) &&
179
327
  result?.state === state);
180
328
  if (!valid) throw new Error('Invalid proposal application state');
329
+ if (expectedRevision !== undefined) {
330
+ const row = this.db
331
+ .prepare('SELECT revision, body FROM proposals WHERE id = ?')
332
+ .get(proposal.id);
333
+ if (!row || row['revision'] !== expectedRevision)
334
+ throw new Error('Proposal revision conflict');
335
+ const previous = JSON.parse(row['body'] as string) as Proposal;
336
+ if (isDeepStrictEqual(proposal, previous)) return previous;
337
+ proposal.revision = expectedRevision + 1;
338
+ proposal.updatedAt = new Date().toISOString();
339
+ }
181
340
  if (expectedRevision === undefined) {
182
341
  this.db
183
342
  .prepare('INSERT INTO proposals VALUES (?, ?, ?, ?)')
@@ -197,39 +356,32 @@ export class CheckpointStore {
197
356
  ) {
198
357
  throw new Error('Proposal revision conflict');
199
358
  }
359
+ return proposal;
200
360
  }
201
361
 
202
- private changedProposal(id: string, revision: number, states: ProposalState[]): Proposal {
362
+ private checkedProposal(id: string, revision: number, states: ProposalState[]): Proposal {
203
363
  const value = this.proposal(id);
204
364
  if (!value || value.revision !== revision) throw new Error('Proposal revision conflict');
205
365
  if (!states.includes(value.state)) throw new Error('Illegal proposal state transition');
206
- const { history = [], ...previous } = value;
207
- return {
208
- ...value,
209
- history: [...history, previous],
210
- revision: revision + 1,
211
- updatedAt: new Date().toISOString(),
212
- };
366
+ return value;
213
367
  }
214
368
 
215
369
  editProposal(id: string, revision: number, draft: ProposalDraft): Proposal {
216
370
  validateDraft(draft);
217
- const value = this.changedProposal(id, revision, ['pending']);
371
+ const value = this.checkedProposal(id, revision, ['pending']);
218
372
  value.draft = structuredClone(draft);
219
- this.saveProposal(value, revision);
220
- return value;
373
+ return this.saveProposal(value, revision);
221
374
  }
222
375
 
223
376
  dismissProposal(id: string, revision: number): Proposal {
224
- const value = this.changedProposal(id, revision, ['pending']);
377
+ const value = this.checkedProposal(id, revision, ['pending']);
225
378
  value.state = 'dismissed';
226
- this.saveProposal(value, revision);
227
- return value;
379
+ return this.saveProposal(value, revision);
228
380
  }
229
381
 
230
382
  claimProposal(id: string, revision: number, before?: TaskSnapshot | null): Proposal {
231
383
  if (before) validateSnapshot(before);
232
- const value = this.changedProposal(id, revision, ['pending']);
384
+ const value = this.checkedProposal(id, revision, ['pending']);
233
385
  if ((value.draft ?? value).question !== null)
234
386
  throw new Error('Resolve proposal question before applying');
235
387
  const change = (value.draft ?? value).change;
@@ -241,8 +393,7 @@ export class CheckpointStore {
241
393
  value.state = 'applying';
242
394
  value.claim = randomUUID();
243
395
  value.result = null;
244
- this.saveProposal(value, revision);
245
- return value;
396
+ return this.saveProposal(value, revision);
246
397
  }
247
398
 
248
399
  recordProposalResult(
@@ -251,7 +402,7 @@ export class CheckpointStore {
251
402
  claim: string,
252
403
  result: ApplicationResult,
253
404
  ): Proposal {
254
- const value = this.changedProposal(id, revision, ['applying', 'uncertain']);
405
+ const value = this.checkedProposal(id, revision, ['applying', 'uncertain']);
255
406
  if (!claim || value.claim !== claim) throw new Error('Application claim mismatch');
256
407
  if (!['applied', 'already_satisfied', 'uncertain'].includes(result.state))
257
408
  throw new Error('Invalid application result');
@@ -270,94 +421,503 @@ export class CheckpointStore {
270
421
  throw new Error('Verified task does not match target');
271
422
  value.state = result.state;
272
423
  value.result = structuredClone(result);
273
- this.saveProposal(value, revision);
274
- return value;
275
- }
276
-
277
- // Capture uses the existing process lock. Its identity is memory-only and has
278
- // no expiry; the caller releases ownership after reviewer cleanup and commit.
279
- prepareCapture(source: Pick<Source, 'sessionId' | 'file'>): CaptureReview {
280
- if (!this.reviewLock) throw new Error('Capture requires review ownership');
281
- if (this.capture) throw new Error('A capture is already frozen');
282
- const enrolled = this.sources().find((item) => item.sessionId === source.sessionId);
283
- const review = new CaptureReview(
284
- { ...source, seedSince: enrolled?.seedSince ?? null },
285
- this.reviewed(),
286
- () => {
287
- if (!this.reviewLock || this.capture !== review)
288
- throw new Error('No matching active capture');
289
- },
290
- );
291
- this.capture = review;
292
- return review;
424
+ return this.saveProposal(value, revision);
293
425
  }
294
426
 
295
- private validatedCapture(id: string, submissions: readonly ProposalSubmission[]) {
296
- if (!this.reviewLock || !this.capture || this.capture.id !== id)
297
- throw new Error('No matching active capture');
298
- const frozen = this.capture.completion(submissions);
427
+ private saveCapture(
428
+ capture: ReturnType<CaptureReview['completion']>,
429
+ submissions: readonly ProposalSubmission[],
430
+ ): Proposal[] {
431
+ const enrolled = new Map(this.sources().map((source) => [source.sessionId, source.file]));
432
+ const plan = this.normalizePlan({
433
+ ...capture.plan,
434
+ sources: (capture.plan.sources ?? []).map((source) => ({
435
+ ...source,
436
+ file: enrolled.get(source.sessionId) ?? source.file,
437
+ })),
438
+ });
439
+ const saved: Proposal[] = [];
299
440
  const ids = new Set<string>();
300
- for (const submission of submissions) {
441
+ for (const [index, submission] of submissions.entries()) {
442
+ const references = capture.sources[index]!;
443
+ const now = new Date().toISOString();
444
+ let proposal: Proposal;
301
445
  if (submission.id !== undefined) {
302
446
  if (ids.has(submission.id)) throw new Error('Repeated proposal revision');
303
447
  ids.add(submission.id);
304
- this.changedProposal(submission.id, submission.expectedRevision!, ['pending']);
448
+ const previous = this.proposal(submission.id);
449
+ if (!previous || previous.revision !== submission.expectedRevision)
450
+ throw new CaptureRetryableError('Proposal revision conflict');
451
+ if (previous.state !== 'pending')
452
+ throw new CaptureRetryableError('Illegal proposal state transition');
453
+ const conflict =
454
+ 'New evidence conflicts with an edited draft. Review both before applying.';
455
+ proposal = {
456
+ ...previous,
457
+ change: submission.change,
458
+ expected: submission.expected,
459
+ question: submission.question,
460
+ explanation: submission.explanation,
461
+ sources: unionProposalSources(previous.sources, references),
462
+ };
463
+ if (
464
+ proposal.draft &&
465
+ !isDeepStrictEqual(proposal, {
466
+ ...previous,
467
+ sources: unionProposalSources(previous.sources),
468
+ })
469
+ ) {
470
+ proposal.draft = { ...proposal.draft, question: conflict };
471
+ }
472
+ } else {
473
+ proposal = {
474
+ id: randomUUID(),
475
+ revision: 1,
476
+ change: submission.change,
477
+ expected: submission.expected,
478
+ question: submission.question,
479
+ draft: null,
480
+ explanation: submission.explanation,
481
+ sources: references,
482
+ state: 'pending',
483
+ claim: null,
484
+ result: null,
485
+ createdAt: now,
486
+ updatedAt: now,
487
+ };
305
488
  }
489
+ saved.push(this.saveProposal(proposal, submission.expectedRevision));
306
490
  }
307
- return frozen;
308
- }
309
-
310
- validateCapture(id: string, submissions: readonly ProposalSubmission[]): void {
311
- this.validatedCapture(id, submissions);
312
- }
313
-
314
- finishCapture(id: string, submissions: readonly ProposalSubmission[]): Proposal[] {
315
- const saved = this.transaction(() => {
316
- const capture = this.validatedCapture(id, submissions);
317
- const plan = this.normalizePlan(capture.plan);
318
- const saved: Proposal[] = [];
319
- for (const [index, submission] of submissions.entries()) {
320
- const references = capture.sources[index]!;
321
- const now = new Date().toISOString();
322
- let proposal: Proposal;
323
- if (submission.id !== undefined) {
324
- proposal = this.changedProposal(submission.id, submission.expectedRevision!, ['pending']);
325
- proposal = {
326
- ...proposal,
327
- change: submission.change,
328
- expected: submission.expected,
329
- question: proposal.draft
330
- ? 'New evidence conflicts with an edited draft. Review both before applying.'
331
- : submission.question,
332
- explanation: submission.explanation,
333
- sources: [...proposal.sources, ...references],
334
- };
335
- if (proposal.draft) proposal.draft = { ...proposal.draft, question: proposal.question };
336
- } else {
337
- proposal = {
338
- id: randomUUID(),
339
- revision: 1,
340
- change: submission.change,
341
- expected: submission.expected,
342
- question: submission.question,
343
- draft: null,
344
- explanation: submission.explanation,
345
- sources: references,
346
- state: 'pending',
347
- claim: null,
348
- result: null,
349
- createdAt: now,
350
- updatedAt: now,
351
- };
352
- }
353
- this.saveProposal(proposal, submission.expectedRevision);
354
- saved.push(proposal);
491
+
492
+ this.writeCoverage(plan);
493
+ return saved;
494
+ }
495
+
496
+ contextGeneration(): number {
497
+ return Number(
498
+ this.db.prepare('SELECT generation FROM review_context WHERE singleton = 1').get()![
499
+ 'generation'
500
+ ],
501
+ );
502
+ }
503
+
504
+ proposalNotice(): { generation: number; pending: number } {
505
+ const row = this.db
506
+ .prepare(
507
+ `SELECT notice_generation AS generation,
508
+ (SELECT count(*) FROM proposals WHERE state = 'pending') AS pending
509
+ FROM review_context WHERE singleton = 1`,
510
+ )
511
+ .get()!;
512
+ return { generation: Number(row['generation']), pending: Number(row['pending']) };
513
+ }
514
+
515
+ claimCaptureWorker(): CaptureWorkerOwnership {
516
+ return CaptureWorkerOwnership.claim(this.filename);
517
+ }
518
+
519
+ captureJob(id: string): CaptureJob | undefined {
520
+ const row = this.db.prepare('SELECT * FROM capture_jobs WHERE id = ?').get(id);
521
+ if (!row) return undefined;
522
+ return {
523
+ manifest: JSON.parse(row['body'] as string) as ReadyManifest,
524
+ state: row['state'] as CaptureJob['state'],
525
+ retryEligible: Boolean(row['retry_eligible']),
526
+ diagnostic: row['diagnostic'] as string | null,
527
+ attemptCount: Number(row['attempt_count']),
528
+ activeAttemptId: row['active_attempt_id'] as string | null,
529
+ nextAttemptAt: row['next_attempt_at'] as number | null,
530
+ revision: Number(row['revision']),
531
+ };
532
+ }
533
+
534
+ captureStatus(): CaptureStatus {
535
+ const jobs = this.db
536
+ .prepare(
537
+ `SELECT job.id, (${predecessor}) AS blocked_by FROM capture_jobs AS job
538
+ WHERE job.state <> 'completed' ORDER BY job.admission_order`,
539
+ )
540
+ .all()
541
+ .map((row) => ({
542
+ ...this.captureJob(row['id'] as string)!,
543
+ blockedBy: row['blocked_by'] as string | null,
544
+ }));
545
+ return { paused: this.capturePaused(), jobs };
546
+ }
547
+
548
+ private capturePaused(): boolean {
549
+ return Boolean(
550
+ this.db.prepare('SELECT paused FROM capture_control WHERE singleton = 1').get()!['paused'],
551
+ );
552
+ }
553
+
554
+ setCapturePaused(paused: boolean, nowMs = Date.now()): void {
555
+ this.transaction(() => {
556
+ this.db
557
+ .prepare('UPDATE capture_control SET paused = ? WHERE singleton = 1')
558
+ .run(Number(paused));
559
+ if (paused) this.interruptCaptureAttempts('Capture interrupted by pause', nowMs);
560
+ });
561
+ }
562
+
563
+ retryCaptureJob(id: string, expectedRevision: number): CaptureJob {
564
+ return this.transaction(() => {
565
+ const job = this.captureJob(id);
566
+ if (
567
+ !job ||
568
+ job.state !== 'failed' ||
569
+ job.retryEligible ||
570
+ job.activeAttemptId !== null ||
571
+ job.revision !== expectedRevision
572
+ )
573
+ throw Error('Capture retry confirmation is stale or job is not stopped');
574
+ this.db
575
+ .prepare(
576
+ `UPDATE capture_jobs SET state = 'queued', retry_eligible = 1,
577
+ diagnostic = NULL, attempt_count = 0, next_attempt_at = NULL, revision = revision + 1
578
+ WHERE id = ?`,
579
+ )
580
+ .run(id);
581
+ return this.captureJob(id)!;
582
+ });
583
+ }
584
+
585
+ pendingSnapshotCleanupIds(owner: CaptureWorkerOwnership): string[] {
586
+ owner.assertStore(this.filename);
587
+ return this.db
588
+ .prepare(
589
+ `SELECT id FROM capture_jobs
590
+ WHERE state = 'completed' AND snapshot_cleanup_pending = 1 ORDER BY rowid`,
591
+ )
592
+ .all()
593
+ .map((row) => row['id'] as string);
594
+ }
595
+
596
+ acknowledgeSnapshotCleanup(owner: CaptureWorkerOwnership, id: string): void {
597
+ owner.assertStore(this.filename);
598
+ this.db
599
+ .prepare(
600
+ `UPDATE capture_jobs SET snapshot_cleanup_pending = 0
601
+ WHERE id = ? AND state = 'completed'`,
602
+ )
603
+ .run(id);
604
+ }
605
+
606
+ unresolvedSnapshot(snapshot: string): boolean {
607
+ return !!this.db
608
+ .prepare("SELECT 1 FROM capture_jobs WHERE snapshot = ? AND state <> 'completed' LIMIT 1")
609
+ .get(snapshot);
610
+ }
611
+
612
+ importCaptureJob(owner: CaptureWorkerOwnership, value: ReadyManifest): CaptureJob {
613
+ owner.assertStore(this.filename);
614
+ const manifest = validateReadyManifest(value, dirname(value.snapshot));
615
+ return this.transaction(() => {
616
+ owner.assertStore(this.filename);
617
+ const existing = this.captureJob(manifest.id);
618
+ if (!existing || existing.state !== 'completed') {
619
+ const snapshot = statSync(manifest.snapshot);
620
+ if (!snapshot.isFile() || snapshot.size !== manifest.source.bytes)
621
+ throw Error('Retained snapshot extent differs from handoff');
355
622
  }
623
+ if (existing) {
624
+ if (JSON.stringify(existing.manifest) !== JSON.stringify(manifest))
625
+ throw Error('Handoff ID metadata conflict');
626
+ // A replay can restore the snapshot after an earlier cleanup. Commit the
627
+ // maintenance debt before its ready signal can be removed again.
628
+ if (existing.state === 'completed')
629
+ this.db
630
+ .prepare('UPDATE capture_jobs SET snapshot_cleanup_pending = 1 WHERE id = ?')
631
+ .run(manifest.id);
632
+ return existing;
633
+ }
634
+ // Publication sequences belong to one durable inbox, not the importer or
635
+ // the wall clock. Never compare counters from different inboxes.
636
+ const previous = this.db.prepare('SELECT snapshot FROM capture_jobs LIMIT 1').get();
637
+ if (
638
+ previous &&
639
+ physicalInbox(dirname(previous['snapshot'] as string)) !==
640
+ physicalInbox(dirname(manifest.snapshot))
641
+ )
642
+ throw Error('Capture publication order requires one inbox per database');
643
+ if (
644
+ this.db
645
+ .prepare('SELECT 1 FROM capture_jobs WHERE admission_order = ?')
646
+ .get(manifest.admissionOrder)
647
+ )
648
+ throw Error('Conflicting capture publication order');
649
+ this.db
650
+ .prepare(
651
+ `INSERT INTO capture_jobs
652
+ (id, session_id, snapshot, accepted_at, admission_order, body, state,
653
+ retry_eligible, diagnostic, attempt_count, active_attempt_id, next_attempt_at, revision)
654
+ VALUES (?, ?, ?, ?, ?, ?, 'queued', 1, NULL, 0, NULL, NULL, 1)`,
655
+ )
656
+ .run(
657
+ manifest.id,
658
+ manifest.source.sessionId,
659
+ manifest.snapshot,
660
+ manifest.acceptedAt,
661
+ manifest.admissionOrder,
662
+ JSON.stringify(manifest),
663
+ );
664
+ return this.captureJob(manifest.id)!;
665
+ });
666
+ }
356
667
 
357
- this.writeCoverage(plan);
358
- return saved;
668
+ runnableCaptureJobs(owner: CaptureWorkerOwnership, nowMs = Date.now()): CaptureJob[] {
669
+ owner.assertStore(this.filename);
670
+ return this.runnableCaptureJobIds(nowMs).map((id) => this.captureJob(id)!);
671
+ }
672
+
673
+ nextRunnableCaptureJob(
674
+ owner: CaptureWorkerOwnership,
675
+ nowMs = Date.now(),
676
+ ): CaptureJob | undefined {
677
+ owner.assertStore(this.filename);
678
+ const id = this.runnableCaptureJobIds(nowMs, 1)[0];
679
+ return id === undefined ? undefined : this.captureJob(id);
680
+ }
681
+
682
+ // Read-only exit-race check. A subsequent claim still grants authority.
683
+ captureRecoveryPending(nowMs = Date.now()): boolean {
684
+ return this.runnableCaptureJobIds(nowMs, 1).length > 0;
685
+ }
686
+
687
+ private runnableCaptureJobIds(nowMs: number, limit = -1, jobId?: string): string[] {
688
+ // Drain every visible ready signal before selection, regardless of discovery order.
689
+ const first = this.db.prepare('SELECT snapshot FROM capture_jobs LIMIT 1').get();
690
+ if (
691
+ first &&
692
+ readdirSync(dirname(first['snapshot'] as string)).some(
693
+ (name) =>
694
+ name.endsWith('.ready.json') &&
695
+ !this.db
696
+ .prepare('SELECT 1 FROM capture_jobs WHERE id = ?')
697
+ .get(name.slice(0, -'.ready.json'.length)),
698
+ )
699
+ )
700
+ return [];
701
+ return this.db
702
+ .prepare(
703
+ `SELECT job.id FROM capture_jobs AS job
704
+ WHERE (SELECT paused FROM capture_control WHERE singleton = 1) = 0
705
+ AND json_extract(job.body, '$.version') = 3
706
+ AND (job.state = 'queued' OR (job.state = 'failed' AND job.retry_eligible = 1))
707
+ AND job.active_attempt_id IS NULL AND job.attempt_count < ?
708
+ AND (job.next_attempt_at IS NULL OR job.next_attempt_at <= ?)
709
+ AND NOT EXISTS (${predecessor})
710
+ ${jobId === undefined ? '' : 'AND job.id = ?'}
711
+ ORDER BY job.admission_order LIMIT ?`,
712
+ )
713
+ .all(CAPTURE_MAX_ATTEMPTS, nowMs, ...(jobId === undefined ? [] : [jobId]), limit)
714
+ .map((row) => row['id'] as string);
715
+ }
716
+
717
+ claimCaptureAttempt(
718
+ owner: CaptureWorkerOwnership,
719
+ jobId: string,
720
+ nowMs = Date.now(),
721
+ ): CaptureAttempt | undefined {
722
+ let attempt: CaptureAttempt | undefined;
723
+ try {
724
+ return this.coordinateCapture(owner, () =>
725
+ this.transaction(() => {
726
+ if (!this.runnableCaptureJobIds(nowMs, 1, jobId).length) return undefined;
727
+ attempt = owner.startAttempt(jobId);
728
+ this.db
729
+ .prepare(
730
+ `UPDATE capture_jobs SET attempt_count = attempt_count + 1,
731
+ active_attempt_id = ?, state = 'queued', retry_eligible = 1, diagnostic = NULL,
732
+ next_attempt_at = NULL, revision = revision + 1 WHERE id = ?`,
733
+ )
734
+ .run(attempt.id, jobId);
735
+ return attempt;
736
+ }),
737
+ );
738
+ } catch (error) {
739
+ // Never leave an executable in-memory identity after a failed durable commit.
740
+ if (attempt) owner.abandon(attempt);
741
+ throw error;
742
+ }
743
+ }
744
+
745
+ assertCaptureAttempt(owner: CaptureWorkerOwnership, attempt: CaptureAttempt): void {
746
+ owner.assertStore(this.filename);
747
+ owner.assertAttempt(attempt);
748
+ // One statement observes identity and pause together, including quick pause/resume.
749
+ if (
750
+ !this.db
751
+ .prepare(
752
+ `SELECT 1 FROM capture_jobs
753
+ WHERE id = ? AND state = 'queued' AND active_attempt_id = ?
754
+ AND (SELECT paused FROM capture_control WHERE singleton = 1) = 0`,
755
+ )
756
+ .get(attempt.jobId, attempt.id)
757
+ )
758
+ throw Error('No matching durable capture attempt');
759
+ }
760
+
761
+ recoverInterruptedCaptureAttempts(owner: CaptureWorkerOwnership, nowMs = Date.now()): void {
762
+ owner.assertStore(this.filename);
763
+ this.transaction(() => this.interruptCaptureAttempts('Capture worker interrupted', nowMs));
764
+ }
765
+
766
+ private interruptCaptureAttempts(diagnostic: string, nowMs: number): void {
767
+ for (const row of this.db
768
+ .prepare('SELECT id FROM capture_jobs WHERE active_attempt_id IS NOT NULL')
769
+ .all()) {
770
+ const job = this.captureJob(row['id'] as string)!;
771
+ this.writeCaptureFailure(job, diagnostic, true, nowMs);
772
+ }
773
+ }
774
+
775
+ private writeCaptureFailure(
776
+ job: CaptureJob,
777
+ diagnostic: string,
778
+ temporary: boolean,
779
+ nowMs: number,
780
+ ): void {
781
+ const retry = temporary && job.attemptCount < CAPTURE_MAX_ATTEMPTS;
782
+ this.db
783
+ .prepare(
784
+ `UPDATE capture_jobs SET state = 'failed', retry_eligible = ?, diagnostic = ?,
785
+ active_attempt_id = NULL, next_attempt_at = ?, revision = revision + 1 WHERE id = ?`,
786
+ )
787
+ .run(
788
+ Number(retry),
789
+ temporary && !retry ? `Capture attempt allowance exhausted: ${diagnostic}` : diagnostic,
790
+ retry ? nowMs + CAPTURE_RETRY_DELAY_MS : null,
791
+ job.manifest.id,
792
+ );
793
+ }
794
+
795
+ private coordinateCapture<T>(owner: CaptureWorkerOwnership, operation: () => T): T {
796
+ owner.assertStore(this.filename);
797
+ try {
798
+ this.claimReviewLock();
799
+ } catch (error) {
800
+ if (
801
+ error instanceof Error &&
802
+ error.message.startsWith('A remembrancer review is already open')
803
+ )
804
+ throw new CaptureRetryableError(error.message);
805
+ throw error;
806
+ }
807
+ try {
808
+ return operation();
809
+ } finally {
810
+ this.releaseReview();
811
+ }
812
+ }
813
+
814
+ prepareCaptureJob(owner: CaptureWorkerOwnership, attempt: CaptureAttempt): CaptureReview {
815
+ if (this.jobCapture?.attempt === attempt) throw Error('Attempt already has a frozen capture');
816
+ const frozen = this.coordinateCapture(owner, () =>
817
+ this.transaction(() => {
818
+ this.assertCaptureAttempt(owner, attempt);
819
+ const job = this.captureJob(attempt.jobId)!;
820
+ const enrolled = this.sources().find(
821
+ (source) => source.sessionId === job.manifest.source.sessionId,
822
+ );
823
+ return {
824
+ job,
825
+ source: {
826
+ file: job.manifest.source.file,
827
+ sessionId: job.manifest.source.sessionId,
828
+ seedSince: enrolled?.seedSince ?? null,
829
+ },
830
+ liveSourceFile: enrolled?.file ?? job.manifest.source.file,
831
+ reviewed: this.reviewed(),
832
+ generation: this.contextGeneration(),
833
+ body: JSON.stringify(job.manifest),
834
+ };
835
+ }),
836
+ );
837
+ // Parsing and historical applicability are deliberately outside manual ownership.
838
+ const result = prepareHistoricalReview(
839
+ frozen.source,
840
+ frozen.job.manifest.snapshot,
841
+ frozen.reviewed,
842
+ undefined,
843
+ frozen.liveSourceFile,
844
+ );
845
+ this.assertCaptureAttempt(owner, attempt);
846
+ if ('retryEligible' in result) {
847
+ this.failCaptureJob(owner, attempt, result.diagnostic, result.retryEligible);
848
+ throw new CapturePreparationError(result.diagnostic, result.category, result.retryEligible);
849
+ }
850
+ const review = new CaptureReview(result.review, () => {
851
+ this.assertCaptureAttempt(owner, attempt);
852
+ if (this.jobCapture?.review !== review) throw Error('No matching frozen capture job');
853
+ });
854
+ this.jobCapture = { owner, attempt, review, generation: frozen.generation, body: frozen.body };
855
+ return review;
856
+ }
857
+
858
+ failCaptureJob(
859
+ owner: CaptureWorkerOwnership,
860
+ attempt: CaptureAttempt,
861
+ diagnostic: string,
862
+ retryEligible: boolean,
863
+ nowMs = Date.now(),
864
+ ): boolean {
865
+ owner.assertStore(this.filename);
866
+ if (!diagnostic.trim()) throw Error('Capture failure requires a diagnostic');
867
+ const failed = this.transaction(() => {
868
+ const job = this.captureJob(attempt.jobId);
869
+ if (!job || job.state !== 'queued' || job.activeAttemptId !== attempt.id) return false;
870
+ owner.assertAttempt(attempt);
871
+ this.writeCaptureFailure(job, diagnostic, retryEligible, nowMs);
872
+ return true;
359
873
  });
360
- this.capture = undefined;
874
+ if (failed) {
875
+ this.jobCapture = undefined;
876
+ owner.abandon(attempt);
877
+ }
878
+ return failed;
879
+ }
880
+
881
+ finishCaptureJob(
882
+ owner: CaptureWorkerOwnership,
883
+ attempt: CaptureAttempt,
884
+ submissions: readonly ProposalSubmission[],
885
+ ): Proposal[] {
886
+ const saved = this.coordinateCapture(owner, () =>
887
+ this.transaction(() => {
888
+ this.assertCaptureAttempt(owner, attempt);
889
+ const active = this.jobCapture;
890
+ const job = this.captureJob(attempt.jobId);
891
+ if (
892
+ !active ||
893
+ active.owner !== owner ||
894
+ active.attempt !== attempt ||
895
+ !job ||
896
+ job.state !== 'queued' ||
897
+ JSON.stringify(job.manifest) !== active.body ||
898
+ this.db
899
+ .prepare(
900
+ `SELECT (${predecessor}) AS blocked_by FROM capture_jobs AS job WHERE job.id = ?`,
901
+ )
902
+ .get(attempt.jobId)!['blocked_by'] !== null
903
+ )
904
+ throw Error('No matching durable capture job');
905
+ validateReadyManifest(job.manifest, dirname(job.manifest.snapshot));
906
+ if (this.contextGeneration() !== active.generation)
907
+ throw new CaptureRetryableError('Capture review context changed; reprepare');
908
+ const capture = active.review.completion(submissions);
909
+ const proposals = this.saveCapture(capture, submissions);
910
+ this.db
911
+ .prepare(
912
+ `UPDATE capture_jobs SET state = 'completed', retry_eligible = 0, diagnostic = NULL,
913
+ active_attempt_id = NULL, next_attempt_at = NULL, revision = revision + 1 WHERE id = ?`,
914
+ )
915
+ .run(attempt.jobId);
916
+ return proposals;
917
+ }),
918
+ );
919
+ this.jobCapture = undefined;
920
+ owner.abandon(attempt);
361
921
  return saved;
362
922
  }
363
923
 
@@ -493,6 +1053,14 @@ export class CheckpointStore {
493
1053
 
494
1054
  close(): void {
495
1055
  this.releaseReview();
1056
+ if (this.jobCapture) {
1057
+ try {
1058
+ this.jobCapture.owner.abandon(this.jobCapture.attempt);
1059
+ } catch {
1060
+ /* Ownership release already invalidated the attempt. */
1061
+ }
1062
+ this.jobCapture = undefined;
1063
+ }
496
1064
  this.db.close();
497
1065
  }
498
1066
  }