@robhowley/pi-remembrancer 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,20 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { chmodSync, closeSync, mkdirSync, openSync } from 'node:fs';
2
3
  import { homedir } from 'node:os';
3
4
  import { dirname, isAbsolute, join } from 'node:path';
4
5
  import { DatabaseSync } from 'node:sqlite';
5
6
 
7
+ import { CaptureReview } from './capture-review.js';
8
+ import {
9
+ validateDraft,
10
+ validateSnapshot,
11
+ type Proposal,
12
+ type ProposalDraft,
13
+ type ProposalSubmission,
14
+ type ProposalState,
15
+ type ApplicationResult,
16
+ type TaskSnapshot,
17
+ } from './proposals.js';
6
18
  import type { Checkpoint, SeedDefault, Source, Tip } from './evidence.js';
7
19
 
8
20
  export type StoredSource = Omit<Source, 'seedSince'> & { seedSince: string | null };
@@ -59,6 +71,7 @@ export class CheckpointStore {
59
71
  private db: DatabaseSync;
60
72
  private filename: string;
61
73
  private reviewLock: DatabaseSync | undefined;
74
+ private capture: CaptureReview | undefined;
62
75
 
63
76
  constructor(filename = defaultFile()) {
64
77
  this.filename = filename;
@@ -81,6 +94,10 @@ export class CheckpointStore {
81
94
  this.db.exec('ALTER TABLE sources ADD COLUMN seed_since TEXT');
82
95
  if (!tableHasColumn(this.db, 'reviewed_boundaries', 'since'))
83
96
  this.db.exec('ALTER TABLE reviewed_boundaries ADD COLUMN since TEXT');
97
+ this.db.exec(`CREATE TABLE IF NOT EXISTS proposals (
98
+ id TEXT PRIMARY KEY, revision INTEGER NOT NULL, state TEXT NOT NULL,
99
+ body TEXT NOT NULL
100
+ )`);
84
101
  this.db.exec('COMMIT');
85
102
  } catch (error) {
86
103
  try {
@@ -111,6 +128,237 @@ export class CheckpointStore {
111
128
  releaseReview(): void {
112
129
  this.reviewLock?.close();
113
130
  this.reviewLock = undefined;
131
+ this.capture = undefined;
132
+ }
133
+
134
+ proposals(state?: ProposalState, offset = 0, limit = 50): Proposal[] {
135
+ if (
136
+ !Number.isSafeInteger(offset) ||
137
+ offset < 0 ||
138
+ !Number.isSafeInteger(limit) ||
139
+ limit < 1 ||
140
+ limit > 100
141
+ )
142
+ throw new Error('Invalid proposal page');
143
+ const rows =
144
+ state === undefined
145
+ ? this.db
146
+ .prepare('SELECT body FROM proposals ORDER BY rowid LIMIT ? OFFSET ?')
147
+ .all(limit, offset)
148
+ : this.db
149
+ .prepare('SELECT body FROM proposals WHERE state = ? ORDER BY rowid LIMIT ? OFFSET ?')
150
+ .all(state, limit, offset);
151
+ return rows.map((row) => JSON.parse(row['body'] as string) as Proposal);
152
+ }
153
+
154
+ proposalCount(state: ProposalState = 'pending'): number {
155
+ return Number(
156
+ this.db.prepare('SELECT count(*) AS count FROM proposals WHERE state = ?').get(state)![
157
+ 'count'
158
+ ],
159
+ );
160
+ }
161
+
162
+ proposal(id: string): Proposal | undefined {
163
+ const row = this.db.prepare('SELECT body FROM proposals WHERE id = ?').get(id);
164
+ return row ? (JSON.parse(row['body'] as string) as Proposal) : undefined;
165
+ }
166
+
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.
170
+ const { state, claim, result, applicationBefore } = proposal;
171
+ const valid =
172
+ state === 'pending' || state === 'dismissed'
173
+ ? claim === null && result === null && applicationBefore === undefined
174
+ : typeof claim === 'string' &&
175
+ claim.length > 0 &&
176
+ (state === 'applying'
177
+ ? result === null
178
+ : ['applied', 'already_satisfied', 'uncertain'].includes(state) &&
179
+ result?.state === state);
180
+ if (!valid) throw new Error('Invalid proposal application state');
181
+ if (expectedRevision === undefined) {
182
+ this.db
183
+ .prepare('INSERT INTO proposals VALUES (?, ?, ?, ?)')
184
+ .run(proposal.id, proposal.revision, proposal.state, JSON.stringify(proposal));
185
+ } else if (
186
+ !this.db
187
+ .prepare(
188
+ 'UPDATE proposals SET revision = ?, state = ?, body = ? WHERE id = ? AND revision = ?',
189
+ )
190
+ .run(
191
+ proposal.revision,
192
+ proposal.state,
193
+ JSON.stringify(proposal),
194
+ proposal.id,
195
+ expectedRevision,
196
+ ).changes
197
+ ) {
198
+ throw new Error('Proposal revision conflict');
199
+ }
200
+ }
201
+
202
+ private changedProposal(id: string, revision: number, states: ProposalState[]): Proposal {
203
+ const value = this.proposal(id);
204
+ if (!value || value.revision !== revision) throw new Error('Proposal revision conflict');
205
+ 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
+ };
213
+ }
214
+
215
+ editProposal(id: string, revision: number, draft: ProposalDraft): Proposal {
216
+ validateDraft(draft);
217
+ const value = this.changedProposal(id, revision, ['pending']);
218
+ value.draft = structuredClone(draft);
219
+ this.saveProposal(value, revision);
220
+ return value;
221
+ }
222
+
223
+ dismissProposal(id: string, revision: number): Proposal {
224
+ const value = this.changedProposal(id, revision, ['pending']);
225
+ value.state = 'dismissed';
226
+ this.saveProposal(value, revision);
227
+ return value;
228
+ }
229
+
230
+ claimProposal(id: string, revision: number, before?: TaskSnapshot | null): Proposal {
231
+ if (before) validateSnapshot(before);
232
+ const value = this.changedProposal(id, revision, ['pending']);
233
+ if ((value.draft ?? value).question !== null)
234
+ throw new Error('Resolve proposal question before applying');
235
+ const change = (value.draft ?? value).change;
236
+ if (before !== undefined) {
237
+ if (change.operation === 'add' ? before !== null : before?.uuid !== change.targetUuid)
238
+ throw new Error('Application snapshot does not match target');
239
+ value.applicationBefore = structuredClone(before);
240
+ }
241
+ value.state = 'applying';
242
+ value.claim = randomUUID();
243
+ value.result = null;
244
+ this.saveProposal(value, revision);
245
+ return value;
246
+ }
247
+
248
+ recordProposalResult(
249
+ id: string,
250
+ revision: number,
251
+ claim: string,
252
+ result: ApplicationResult,
253
+ ): Proposal {
254
+ const value = this.changedProposal(id, revision, ['applying', 'uncertain']);
255
+ if (!claim || value.claim !== claim) throw new Error('Application claim mismatch');
256
+ if (!['applied', 'already_satisfied', 'uncertain'].includes(result.state))
257
+ throw new Error('Invalid application result');
258
+ if (result.verified !== null) validateSnapshot(result.verified);
259
+ if (result.state === 'applied' || result.state === 'already_satisfied') {
260
+ if (!result.verified || result.error !== null)
261
+ throw new Error('Success requires verified task');
262
+ } else if (typeof result.error !== 'string' || !result.error.trim())
263
+ throw new Error('Failure requires error');
264
+ const effective = value.draft ?? value;
265
+ if (
266
+ result.verified &&
267
+ effective.change.operation !== 'add' &&
268
+ result.verified.uuid !== effective.change.targetUuid
269
+ )
270
+ throw new Error('Verified task does not match target');
271
+ value.state = result.state;
272
+ 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;
293
+ }
294
+
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);
299
+ const ids = new Set<string>();
300
+ for (const submission of submissions) {
301
+ if (submission.id !== undefined) {
302
+ if (ids.has(submission.id)) throw new Error('Repeated proposal revision');
303
+ ids.add(submission.id);
304
+ this.changedProposal(submission.id, submission.expectedRevision!, ['pending']);
305
+ }
306
+ }
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);
355
+ }
356
+
357
+ this.writeCoverage(plan);
358
+ return saved;
359
+ });
360
+ this.capture = undefined;
361
+ return saved;
114
362
  }
115
363
 
116
364
  enroll(sessionId: string, file: string): void {
@@ -149,6 +397,11 @@ export class CheckpointStore {
149
397
  const plan: FinishPlan = Array.isArray(input)
150
398
  ? { checkpoints: input.map(checkpointFromTip) }
151
399
  : (input as FinishPlan);
400
+ const normalized = this.normalizePlan(plan);
401
+ this.transaction(() => this.writeCoverage(normalized));
402
+ }
403
+
404
+ private normalizePlan(plan: FinishPlan) {
152
405
  const sources = plan.sources ?? [];
153
406
  const sourceDefaults = (plan.sourceDefaults ?? []).map((source) => ({
154
407
  ...source,
@@ -172,11 +425,19 @@ export class CheckpointStore {
172
425
  throw new Error('Cannot finish an invalid checkpoint');
173
426
  }
174
427
 
428
+ return { sources, sourceDefaults, checkpoints };
429
+ }
430
+
431
+ // Does not own a transaction. Manual finish and capture completion share only
432
+ // this normalized coverage write, never each other's completion lifecycle.
433
+ private writeCoverage({
434
+ sources,
435
+ sourceDefaults,
436
+ checkpoints,
437
+ }: ReturnType<CheckpointStore['normalizePlan']>): void {
175
438
  const known = new Set(this.sources().map((source) => source.sessionId));
176
- this.db.exec('BEGIN IMMEDIATE');
177
- try {
178
- const enroll = this.db.prepare(
179
- `INSERT INTO sources (session_id, session_file, seed_since) VALUES (?, ?, ?)
439
+ const enroll = this.db.prepare(
440
+ `INSERT INTO sources (session_id, session_file, seed_since) VALUES (?, ?, ?)
180
441
  ON CONFLICT (session_id) DO UPDATE SET
181
442
  session_file = excluded.session_file,
182
443
  seed_since = CASE
@@ -185,40 +446,45 @@ export class CheckpointStore {
185
446
  WHEN excluded.seed_since < sources.seed_since THEN excluded.seed_since
186
447
  ELSE sources.seed_since
187
448
  END`,
188
- );
189
- for (const source of sources) {
190
- enroll.run(source.sessionId, source.file, absoluteTimestamp(source.seedSince));
191
- known.add(source.sessionId);
192
- }
449
+ );
450
+ for (const source of sources) {
451
+ enroll.run(source.sessionId, source.file, absoluteTimestamp(source.seedSince));
452
+ known.add(source.sessionId);
453
+ }
193
454
 
194
- const saveDefault = this.db.prepare(
195
- `UPDATE sources SET seed_since = CASE
455
+ const saveDefault = this.db.prepare(
456
+ `UPDATE sources SET seed_since = CASE
196
457
  WHEN seed_since IS NULL OR ? < seed_since THEN ?
197
458
  ELSE seed_since
198
459
  END
199
460
  WHERE session_id = ?`,
200
- );
201
- for (const source of sourceDefaults) {
202
- if (!known.has(source.sessionId))
203
- throw new Error('Cannot finish an unknown source default');
204
- saveDefault.run(source.since, source.since, source.sessionId);
205
- }
461
+ );
462
+ for (const source of sourceDefaults) {
463
+ if (!known.has(source.sessionId)) throw new Error('Cannot finish an unknown source default');
464
+ saveDefault.run(source.since, source.since, source.sessionId);
465
+ }
206
466
 
207
- const mark = this.db.prepare(
208
- `INSERT INTO reviewed_boundaries (session_id, tip_id, since) VALUES (?, ?, ?)
467
+ const mark = this.db.prepare(
468
+ `INSERT INTO reviewed_boundaries (session_id, tip_id, since) VALUES (?, ?, ?)
209
469
  ON CONFLICT (session_id, tip_id) DO UPDATE SET
210
470
  since = CASE
211
471
  WHEN reviewed_boundaries.since IS NULL OR excluded.since IS NULL THEN NULL
212
472
  WHEN excluded.since < reviewed_boundaries.since THEN excluded.since
213
473
  ELSE reviewed_boundaries.since
214
474
  END`,
215
- );
216
- for (const checkpoint of checkpoints) {
217
- if (!known.has(checkpoint.sessionId))
218
- throw new Error('Cannot finish an unknown checkpoint');
219
- mark.run(checkpoint.sessionId, checkpoint.entryId, checkpoint.since);
220
- }
475
+ );
476
+ for (const checkpoint of checkpoints) {
477
+ if (!known.has(checkpoint.sessionId)) throw new Error('Cannot finish an unknown checkpoint');
478
+ mark.run(checkpoint.sessionId, checkpoint.entryId, checkpoint.since);
479
+ }
480
+ }
481
+
482
+ private transaction<T>(write: () => T): T {
483
+ this.db.exec('BEGIN IMMEDIATE');
484
+ try {
485
+ const result = write();
221
486
  this.db.exec('COMMIT');
487
+ return result;
222
488
  } catch (error) {
223
489
  this.db.exec('ROLLBACK');
224
490
  throw error;
@@ -2,21 +2,32 @@ import { getAgentDir, SettingsManager } from '@earendil-works/pi-coding-agent';
2
2
 
3
3
  export interface RemembrancerConfig {
4
4
  disabled: boolean;
5
+ autoCapture: boolean;
5
6
  }
6
7
 
7
8
  export const DEFAULT_REMEMBRANCER_CONFIG: RemembrancerConfig = {
8
9
  disabled: false,
10
+ autoCapture: false,
9
11
  };
10
12
 
11
13
  export function loadRemembrancerConfig(cwd: string, projectTrusted: boolean): RemembrancerConfig {
12
14
  const settings = SettingsManager.create(cwd, getAgentDir(), { projectTrusted });
13
15
  const project = projectTrusted ? remembrancerSettings(settings.getProjectSettings()) : {};
14
16
  const global = remembrancerSettings(settings.getGlobalSettings());
15
- const disabled = (scope: Record<string, unknown>): boolean | undefined =>
16
- typeof scope['disabled'] === 'boolean' ? scope['disabled'] : undefined;
17
+ const booleanSetting = (
18
+ scope: Record<string, unknown>,
19
+ name: keyof RemembrancerConfig,
20
+ ): boolean | undefined => (typeof scope[name] === 'boolean' ? scope[name] : undefined);
17
21
 
18
22
  return {
19
- disabled: disabled(project) ?? disabled(global) ?? DEFAULT_REMEMBRANCER_CONFIG.disabled,
23
+ disabled:
24
+ booleanSetting(project, 'disabled') ??
25
+ booleanSetting(global, 'disabled') ??
26
+ DEFAULT_REMEMBRANCER_CONFIG.disabled,
27
+ autoCapture:
28
+ booleanSetting(project, 'autoCapture') ??
29
+ booleanSetting(global, 'autoCapture') ??
30
+ DEFAULT_REMEMBRANCER_CONFIG.autoCapture,
20
31
  };
21
32
  }
22
33