@robhowley/pi-remembrancer 0.6.0 → 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.
@@ -708,5 +708,7 @@ export async function cleanupCompletedSnapshot(
708
708
  if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
709
709
  }
710
710
  await synchronize(inbox);
711
+ // A crash before this write leaves retryable debt, including an absent file.
712
+ store.acknowledgeSnapshotCleanup(owner, id);
711
713
  return true;
712
714
  }
@@ -5,6 +5,7 @@ import type { DatabaseSync } from 'node:sqlite';
5
5
  import { openPrivateSqlite } from './private-sqlite.mjs';
6
6
  import type { ReadyManifest } from './capture-handoff.js';
7
7
 
8
+ export const CAPTURE_BUDGET_MS = 300_000;
8
9
  export const CAPTURE_MAX_ATTEMPTS = 2;
9
10
  export const CAPTURE_RETRY_DELAY_MS = 60_000;
10
11
 
@@ -8,6 +8,9 @@ export type ProposalNotice = { generation: number; pending: number };
8
8
  /** Derived only from committed SQLite state. The singleton worker serializes replacement. */
9
9
  export async function publishProposalNotice(store: CheckpointStore): Promise<void> {
10
10
  const notice = store.proposalNotice();
11
+ // Read and validate on every publication so deleted/corrupt sidecars are repaired.
12
+ const previous = await readProposalNotice(store.file).catch(() => undefined);
13
+ if (previous?.generation === notice.generation && previous.pending === notice.pending) return;
11
14
  const target = store.file + '.notice.json';
12
15
  const temporary = target + '.' + randomUUID() + '.tmp';
13
16
  try {
@@ -7,6 +7,7 @@ import {
7
7
  CaptureWorkerOwnership,
8
8
  CapturePreparationError,
9
9
  CaptureRetryableError,
10
+ CAPTURE_BUDGET_MS,
10
11
  type CaptureAttempt,
11
12
  } from './capture-jobs.js';
12
13
  import {
@@ -15,8 +16,7 @@ import {
15
16
  importReadyHandoff,
16
17
  type HandoffInput,
17
18
  } from './capture-handoff.js';
18
- import { CAPTURE_BUDGET_MS, reviewPreparedCapture } from './capture.js';
19
- import { getPackageDir, ModelRuntime, SettingsManager } from '@earendil-works/pi-coding-agent';
19
+ import type { reviewPreparedCapture } from './capture.js';
20
20
  import type { ProposalSubmission } from './proposals.js';
21
21
  import { publishProposalNotice } from './capture-notices.js';
22
22
 
@@ -78,7 +78,7 @@ export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
78
78
  let store: CheckpointStore | undefined;
79
79
  const seenSignals = new Set<string>();
80
80
  const blockedSignals = new Set<string>();
81
- const cleaned = new Set<string>();
81
+ const attemptedCleanup = new Set<string>();
82
82
  const diagnose = async (message: string) => {
83
83
  try {
84
84
  await appendFile(database + '.capture.log', `${new Date().toISOString()} ${message}\n`, {
@@ -96,11 +96,11 @@ export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
96
96
  } catch (error) {
97
97
  await localFailure('notice-publication', 'store', error);
98
98
  }
99
- for (const id of store!.completedCaptureJobIds(owner!)) {
100
- if (cleaned.has(id)) continue;
101
- cleaned.add(id);
99
+ for (const id of store!.pendingSnapshotCleanupIds(owner!)) {
100
+ if (attemptedCleanup.has(id)) continue;
101
+ attemptedCleanup.add(id);
102
102
  try {
103
- await cleanupCompletedSnapshot(store!, owner!, id);
103
+ if (await cleanupCompletedSnapshot(store!, owner!, id)) attemptedCleanup.delete(id);
104
104
  } catch (error) {
105
105
  await localFailure('snapshot-cleanup', id, error);
106
106
  }
@@ -146,7 +146,7 @@ export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
146
146
  }
147
147
  // Completed rows, not ready files or model replay, authorize repair on every wake.
148
148
  await repairCompleted();
149
- const job = store.runnableCaptureJobs(owner)[0];
149
+ const job = store.nextRunnableCaptureJob(owner);
150
150
  if (!job) {
151
151
  // Repair commits arriving during the preceding asynchronous sidecar write.
152
152
  await repairCompleted();
@@ -242,6 +242,9 @@ export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
242
242
  const { execution, source } = job.manifest;
243
243
  const { runtime } = execution;
244
244
  phase = 'reviewer-setup-prompt-cleanup';
245
+ const { getPackageDir, ModelRuntime, SettingsManager } =
246
+ await import('@earendil-works/pi-coding-agent');
247
+ check();
245
248
  // The SDK caches stored-auth command output process-wide. Clear the
246
249
  // selected host's own cache before resolving another project's auth.
247
250
  const { clearApiKeyCache } = await import(
@@ -272,7 +275,9 @@ export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
272
275
  throw Error('Originating model headers are unavailable from Pi configuration');
273
276
  }
274
277
  check();
275
- submissions = await (options.review ?? reviewPreparedCapture)(
278
+ const review = options.review ?? (await import('./capture.js')).reviewPreparedCapture;
279
+ check();
280
+ submissions = await review(
276
281
  current,
277
282
  store,
278
283
  {
@@ -23,7 +23,7 @@ import {
23
23
  import { buildOpeningPrompt, runReviewer, type ReviewerInput } from './reviewer.js';
24
24
  import { readTaskCatalog, type TaskRecord } from './taskwarrior.js';
25
25
 
26
- export const CAPTURE_BUDGET_MS = 300_000;
26
+ export { CAPTURE_BUDGET_MS } from './capture-jobs.js';
27
27
  const cursor = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
28
28
 
29
29
  /** One continuing reviewer stages results. Disposal and artifact cleanup precede publication. */
@@ -246,7 +246,8 @@ export async function reviewPreparedCapture(
246
246
  artifacts.assertDelivered();
247
247
  submitted = true;
248
248
  if (view)
249
- for (const proposal of view.proposals) readProposal(db, proposal.id, proposal.revision);
249
+ for (const proposal of view.proposals)
250
+ db.assertProposalRevision(proposal.id, proposal.revision);
250
251
  staged = validateCaptureSubmission(args, current, view?.tasks ?? [], view?.proposals ?? []);
251
252
  assertFresh();
252
253
  return { ...reply({ accepted: true }), terminate: true };
@@ -267,7 +268,8 @@ export async function reviewPreparedCapture(
267
268
  artifacts.assertDelivered();
268
269
  if (!submitted || staged === undefined) throw new Error('Reviewer did not submit a result');
269
270
  if (view)
270
- for (const proposal of view.proposals) readProposal(db, proposal.id, proposal.revision);
271
+ for (const proposal of view.proposals)
272
+ db.assertProposalRevision(proposal.id, proposal.revision);
271
273
  } finally {
272
274
  // runReviewer has already awaited disposal, including cancellation cleanup.
273
275
  artifacts.dispose();
@@ -61,6 +61,17 @@ function absoluteTimestamp(value: string | null | undefined): string | null {
61
61
  return new Date(milliseconds).toISOString();
62
62
  }
63
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
+
64
75
  function tableHasColumn(db: DatabaseSync, table: string, column: string): boolean {
65
76
  return (db.prepare(`PRAGMA table_info(${table})`).all() as { name?: string }[]).some(
66
77
  (item) => item.name === column,
@@ -102,8 +113,18 @@ export class CheckpointStore {
102
113
  this.filename = filename;
103
114
  this.db = openPrivate(filename);
104
115
  if (filename !== ':memory:') this.filename = realpathSync(filename);
116
+ let migrating = false;
105
117
  try {
106
- 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
+ }
107
128
  this.db.exec(`
108
129
  CREATE TABLE IF NOT EXISTS sources (
109
130
  session_id TEXT PRIMARY KEY,
@@ -139,25 +160,27 @@ export class CheckpointStore {
139
160
  OR (state = 'failed' AND diagnostic IS NOT NULL AND length(trim(diagnostic)) > 0))
140
161
  );
141
162
  `);
163
+ // Version 3 installs these triggers once, including on existing version 2 databases.
142
164
  // Triggers keep each mutation and its generation in the same transaction,
143
165
  // including existing single-statement manual proposal/application writes.
144
- for (const table of ['sources', 'reviewed_boundaries', 'proposals']) {
145
- for (const operation of ['INSERT', 'UPDATE', 'DELETE']) {
146
- this.db.exec(`DROP TRIGGER IF EXISTS context_${table}_${operation}`);
147
- let condition = '';
148
- if (table === 'sources' && operation === 'INSERT')
149
- condition = 'WHEN NEW.seed_since IS NOT NULL';
150
- if (table === 'sources' && operation === 'UPDATE')
151
- condition = 'WHEN NEW.seed_since IS NOT OLD.seed_since';
152
- this.db.exec(`CREATE TRIGGER context_${table}_${operation}
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}
153
176
  AFTER ${operation} ON ${table} ${condition} BEGIN
154
177
  UPDATE review_context SET generation = generation + 1
155
178
  ${table === 'proposals' ? ', notice_generation = notice_generation + 1' : ''}
156
179
  WHERE singleton = 1;
157
180
  END`);
181
+ }
158
182
  }
159
- }
160
- if (Number(this.db.prepare('PRAGMA user_version').get()!['user_version']) < 1) {
183
+ if (version < 1) {
161
184
  const update = this.db.prepare('UPDATE proposals SET revision = ?, body = ? WHERE id = ?');
162
185
  for (const row of this.db.prepare('SELECT id, revision, body FROM proposals').iterate()) {
163
186
  const proposal = JSON.parse(row['body'] as string) as Proposal & { history?: unknown };
@@ -171,7 +194,7 @@ export class CheckpointStore {
171
194
  }
172
195
  this.db.exec('PRAGMA user_version = 1');
173
196
  }
174
- if (Number(this.db.prepare('PRAGMA user_version').get()!['user_version']) < 2) {
197
+ if (version < 2) {
175
198
  this.db.exec(`
176
199
  ALTER TABLE capture_jobs ADD COLUMN attempt_count INTEGER NOT NULL DEFAULT 0
177
200
  CHECK(attempt_count >= 0 AND attempt_count <= ${CAPTURE_MAX_ATTEMPTS});
@@ -190,10 +213,23 @@ export class CheckpointStore {
190
213
  PRAGMA user_version = 2;
191
214
  `);
192
215
  }
193
- this.db.exec('COMMIT');
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`);
194
230
  } catch (error) {
195
231
  try {
196
- this.db.exec('ROLLBACK');
232
+ if (migrating) this.db.exec('ROLLBACK');
197
233
  } finally {
198
234
  this.db.close();
199
235
  }
@@ -260,6 +296,18 @@ export class CheckpointStore {
260
296
  );
261
297
  }
262
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
+
263
311
  proposal(id: string): Proposal | undefined {
264
312
  const row = this.db.prepare('SELECT body FROM proposals WHERE id = ?').get(id);
265
313
  return row ? (JSON.parse(row['body'] as string) as Proposal) : undefined;
@@ -534,14 +582,27 @@ export class CheckpointStore {
534
582
  });
535
583
  }
536
584
 
537
- completedCaptureJobIds(owner: CaptureWorkerOwnership): string[] {
585
+ pendingSnapshotCleanupIds(owner: CaptureWorkerOwnership): string[] {
538
586
  owner.assertStore(this.filename);
539
587
  return this.db
540
- .prepare("SELECT id FROM capture_jobs WHERE state = 'completed' ORDER BY rowid")
588
+ .prepare(
589
+ `SELECT id FROM capture_jobs
590
+ WHERE state = 'completed' AND snapshot_cleanup_pending = 1 ORDER BY rowid`,
591
+ )
541
592
  .all()
542
593
  .map((row) => row['id'] as string);
543
594
  }
544
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
+
545
606
  unresolvedSnapshot(snapshot: string): boolean {
546
607
  return !!this.db
547
608
  .prepare("SELECT 1 FROM capture_jobs WHERE snapshot = ? AND state <> 'completed' LIMIT 1")
@@ -562,6 +623,12 @@ export class CheckpointStore {
562
623
  if (existing) {
563
624
  if (JSON.stringify(existing.manifest) !== JSON.stringify(manifest))
564
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);
565
632
  return existing;
566
633
  }
567
634
  // Publication sequences belong to one durable inbox, not the importer or
@@ -603,19 +670,31 @@ export class CheckpointStore {
603
670
  return this.runnableCaptureJobIds(nowMs).map((id) => this.captureJob(id)!);
604
671
  }
605
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
+
606
682
  // Read-only exit-race check. A subsequent claim still grants authority.
607
683
  captureRecoveryPending(nowMs = Date.now()): boolean {
608
- return this.runnableCaptureJobIds(nowMs).length > 0;
684
+ return this.runnableCaptureJobIds(nowMs, 1).length > 0;
609
685
  }
610
686
 
611
- private runnableCaptureJobIds(nowMs: number): string[] {
687
+ private runnableCaptureJobIds(nowMs: number, limit = -1, jobId?: string): string[] {
612
688
  // Drain every visible ready signal before selection, regardless of discovery order.
613
689
  const first = this.db.prepare('SELECT snapshot FROM capture_jobs LIMIT 1').get();
614
690
  if (
615
691
  first &&
616
692
  readdirSync(dirname(first['snapshot'] as string)).some(
617
693
  (name) =>
618
- name.endsWith('.ready.json') && !this.captureJob(name.slice(0, -'.ready.json'.length)),
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)),
619
698
  )
620
699
  )
621
700
  return [];
@@ -627,9 +706,11 @@ export class CheckpointStore {
627
706
  AND (job.state = 'queued' OR (job.state = 'failed' AND job.retry_eligible = 1))
628
707
  AND job.active_attempt_id IS NULL AND job.attempt_count < ?
629
708
  AND (job.next_attempt_at IS NULL OR job.next_attempt_at <= ?)
630
- AND NOT EXISTS (${predecessor}) ORDER BY job.admission_order`,
709
+ AND NOT EXISTS (${predecessor})
710
+ ${jobId === undefined ? '' : 'AND job.id = ?'}
711
+ ORDER BY job.admission_order LIMIT ?`,
631
712
  )
632
- .all(CAPTURE_MAX_ATTEMPTS, nowMs)
713
+ .all(CAPTURE_MAX_ATTEMPTS, nowMs, ...(jobId === undefined ? [] : [jobId]), limit)
633
714
  .map((row) => row['id'] as string);
634
715
  }
635
716
 
@@ -642,7 +723,7 @@ export class CheckpointStore {
642
723
  try {
643
724
  return this.coordinateCapture(owner, () =>
644
725
  this.transaction(() => {
645
- if (!this.runnableCaptureJobIds(nowMs).includes(jobId)) return undefined;
726
+ if (!this.runnableCaptureJobIds(nowMs, 1, jobId).length) return undefined;
646
727
  attempt = owner.startAttempt(jobId);
647
728
  this.db
648
729
  .prepare(
@@ -419,6 +419,7 @@ export async function openProposals(
419
419
  ? [...feedback.slice(0, 2), ...wrap('Full feedback is in the body.')]
420
420
  : feedback;
421
421
  let body: string[] = [];
422
+ const summaryRows = view === 'inbox' && !expanded ? queue.length * 2 : 0;
422
423
  let focusLine = 0;
423
424
  if (view === 'source')
424
425
  body = wrapTextWithAnsi(sourceBody || 'No saved sources.', bodyWidth);
@@ -463,9 +464,7 @@ export async function openProposals(
463
464
  bodyWidth,
464
465
  );
465
466
  } else {
466
- body = queue.length
467
- ? queue.flatMap((item, index) => summary(item, index === selected))
468
- : ['No proposals in Inbox. History remains available.'];
467
+ if (!queue.length) body = ['No proposals in Inbox. History remains available.'];
469
468
  focusLine = selected * 2;
470
469
  }
471
470
  if (feedback.length > 3) {
@@ -474,9 +473,10 @@ export async function openProposals(
474
473
  }
475
474
  // Keep collapsed summaries whole at both paging endpoints.
476
475
  if (view === 'inbox' && !expanded && body.length % 2) body.push('');
476
+ const bodyLength = summaryRows + body.length;
477
477
  // Reserve the longest range cue before allocating the single local viewport.
478
478
  const cueRows = wrap(
479
- `Rows ${body.length}-${body.length}/${body.length} · above · more below`,
479
+ `Rows ${bodyLength}-${bodyLength}/${bodyLength} · above · more below`,
480
480
  ).length;
481
481
  pageSize = Math.max(
482
482
  1,
@@ -494,7 +494,7 @@ export async function openProposals(
494
494
  ).slice(0, height);
495
495
  }
496
496
  if (view === 'inbox' && !expanded) pageSize = Math.max(2, pageSize - (pageSize % 2));
497
- const maxOffset = Math.max(0, body.length - pageSize);
497
+ const maxOffset = Math.max(0, bodyLength - pageSize);
498
498
  let offset = Math.max(0, Math.min(offsets[view], maxOffset));
499
499
  if (reveal && ((view === 'inbox' && !expanded) || view === 'history')) {
500
500
  const focusEnd = focusLine + (view === 'inbox' ? 2 : 1);
@@ -506,13 +506,24 @@ export async function openProposals(
506
506
  offsets[view] = offset;
507
507
  const thumbSize = Math.max(
508
508
  1,
509
- Math.floor(pageSize * Math.min(1, pageSize / Math.max(1, body.length))),
509
+ Math.floor(pageSize * Math.min(1, pageSize / Math.max(1, bodyLength))),
510
510
  );
511
511
  const thumbStart = maxOffset
512
512
  ? Math.round((offset / maxOffset) * (pageSize - thumbSize))
513
513
  : 0;
514
+ const firstSummary = Math.floor(offset / 2);
515
+ const visibleSummaries = summaryRows
516
+ ? queue
517
+ .slice(firstSummary, Math.ceil(Math.min(offset + pageSize, summaryRows) / 2))
518
+ .flatMap((item, index) => summary(item, firstSummary + index === selected))
519
+ : [];
514
520
  const rows = Array.from({ length: pageSize }, (_, index) => {
515
- const line = sliceByColumn(body[offset + index] ?? '', 0, bodyWidth, true);
521
+ const position = offset + index;
522
+ const text =
523
+ position < summaryRows
524
+ ? visibleSummaries[position - firstSummary * 2]
525
+ : body[position - summaryRows];
526
+ const line = sliceByColumn(text ?? '', 0, bodyWidth, true);
516
527
  const track = index >= thumbStart && index < thumbStart + thumbSize ? '█' : '│';
517
528
  return (
518
529
  line +
@@ -521,7 +532,7 @@ export async function openProposals(
521
532
  );
522
533
  });
523
534
  const cue = wrap(
524
- `Rows ${body.length ? offset + 1 : 0}-${Math.min(offset + pageSize, body.length)}/${body.length} · ${offset ? 'above · ' : ''}${offset < maxOffset ? 'more below' : 'end'}`,
535
+ `Rows ${bodyLength ? offset + 1 : 0}-${Math.min(offset + pageSize, bodyLength)}/${bodyLength} · ${offset ? 'above · ' : ''}${offset < maxOffset ? 'more below' : 'end'}`,
525
536
  );
526
537
  while (cue.length < cueRows) cue.push('');
527
538
  const row = (line: string) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robhowley/pi-remembrancer",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Track and review commitments across Pi sessions to keep your personal Taskwarrior list current.",
6
6
  "engines": {