@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,153 +1,279 @@
1
- import { Type, type TSchema, type Static } from '@earendil-works/pi-ai';
2
- import type { ExtensionContext, ToolDefinition } from '@earendil-works/pi-coding-agent';
3
- import { CheckpointStore } from './checkpoints.js';
4
- import { loadRemembrancerConfig } from './config.js';
5
- import { serializedResponse, type Selected } from './review-pages.js';
6
- import { proposalParameters, stringEnumSchema, type ProposalSubmission } from './proposals.js';
7
- import { proposalReadDescription, proposalReadParameters, readProposals } from './proposal-read.js';
8
- import { runReviewer } from './reviewer.js';
9
- import { lookupTasks } from './taskwarrior.js';
1
+ import { Type } from '@sinclair/typebox';
2
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
3
+ import { CaptureArtifacts } from './capture-artifacts.js';
4
+ import { captureSubmitParameters, validateCaptureSubmission } from './capture-submission.js';
5
+ import { CaptureRetryableError } from './capture-jobs.js';
6
+ import type { CheckpointStore } from './checkpoints.js';
7
+ import type { CaptureReview } from './capture-review.js';
8
+ import {
9
+ proposalReadDescription,
10
+ proposalReadParameters,
11
+ readProposal,
12
+ readProposals,
13
+ type ProposalReadArgs,
14
+ } from './proposal-read.js';
15
+ import type { Proposal, ProposalSubmission } from './proposals.js';
16
+ import {
17
+ fitsResponse,
18
+ fitPrefixLength,
19
+ safePrefixLength,
20
+ serializedResponse,
21
+ splitsSurrogatePair,
22
+ } from './review-pages.js';
23
+ import { buildOpeningPrompt, runReviewer, type ReviewerInput } from './reviewer.js';
24
+ import { readTaskCatalog, type TaskRecord } from './taskwarrior.js';
10
25
 
11
- export const CAPTURE_BUDGET_MS = 300_000;
26
+ export { CAPTURE_BUDGET_MS } from './capture-jobs.js';
27
+ const cursor = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
12
28
 
13
- /** Own one outgoing review through SDK cleanup. The extension owns the database lifetime. */
14
- export async function captureOutgoing(
15
- ctx: ExtensionContext,
16
- store: () => CheckpointStore,
17
- deadline: number,
18
- ): Promise<void> {
19
- const file = ctx.sessionManager.getSessionFile();
20
- if (ctx.mode !== 'tui' || !file) return;
21
- let owned: CheckpointStore | undefined;
22
- let timer: ReturnType<typeof setTimeout> | undefined;
23
- const sessionId = ctx.sessionManager.getSessionId();
24
- try {
25
- const config = loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted());
26
- if (config.disabled || !config.autoCapture) return;
27
- const controller = new AbortController();
28
- const checkDeadline = () => {
29
- if (Date.now() >= deadline) controller.abort(new Error('Review timed out'));
30
- controller.signal.throwIfAborted();
31
- };
29
+ /** One continuing reviewer stages results. Disposal and artifact cleanup precede publication. */
30
+ export async function reviewPreparedCapture(
31
+ current: CaptureReview,
32
+ db: CheckpointStore,
33
+ input: Omit<ReviewerInput, 'tools'>,
34
+ checkDeadline: () => void,
35
+ ): Promise<ProposalSubmission[]> {
36
+ if (!input.model) throw new Error('Remembrancer reviewer requires the outgoing model');
37
+ checkDeadline();
38
+ const generation = db.contextGeneration();
39
+ const artifacts = new CaptureArtifacts(current);
40
+ let view: { tasks: TaskRecord[]; proposals: Proposal[] } | undefined;
41
+ let staged: ProposalSubmission[] | undefined;
42
+ let submitted = false;
43
+ const acceptedReads = new WeakMap<object, () => void>();
44
+ const assertFresh = () => {
32
45
  checkDeadline();
33
- timer = setTimeout(
34
- () => controller.abort(new Error('Review timed out')),
35
- deadline - Date.now(),
36
- );
37
- const db = store();
38
- db.claimReview();
39
- owned = db;
40
- const current = db.prepareCapture({ sessionId, file });
41
- if (current.incomplete) throw new Error('Cannot capture incomplete evidence');
42
- if (!current.hasEvidence) return;
43
- let staged: ProposalSubmission[] | undefined;
44
- let failed = false;
45
- const tool = <T extends TSchema>(
46
- name: string,
47
- description: string,
48
- parameters: T,
49
- execute: (args: Static<T>) => object | Promise<object>,
50
- submission = false,
51
- ): ToolDefinition => ({
52
- name,
53
- label: name,
54
- description,
55
- parameters: parameters as unknown as ToolDefinition['parameters'],
46
+ input.signal?.throwIfAborted();
47
+ if (db.contextGeneration() !== generation)
48
+ throw new CaptureRetryableError('Capture review context changed; reprepare');
49
+ };
50
+ const guardRead = () => {
51
+ assertFresh();
52
+ artifacts.assertSkillDelivered();
53
+ if (submitted) throw new Error('Capture submission is terminal');
54
+ };
55
+ // The first matching lookup owns one complete, typed export and proposal view.
56
+ // All subsequent reads, including saved drafts/sources/results, use these originals.
57
+ const matchingView = async () => {
58
+ guardRead();
59
+ if (!view) {
60
+ const tasks = await readTaskCatalog(undefined, { cwd: input.cwd, signal: input.signal });
61
+ assertFresh();
62
+ const proposals: Proposal[] = [];
63
+ for (let offset = 0; ; offset += 100) {
64
+ assertFresh();
65
+ const page = db.proposals(undefined, offset, 100);
66
+ proposals.push(...page);
67
+ if (page.length < 100) break;
68
+ }
69
+ assertFresh();
70
+ view = structuredClone({ tasks, proposals });
71
+ }
72
+ return view;
73
+ };
74
+ const reply = (data: object) => ({
75
+ content: [{ type: 'text' as const, text: serializedResponse(data) }],
76
+ details: {},
77
+ });
78
+ const tools: ToolDefinition[] = [
79
+ {
80
+ name: 'remembrancer_read',
81
+ label: 'Read capture evidence or skill',
82
+ description: `Read only the exact installed skill path or generated review path from the opening prompt. Page is zero-based (default 0). Read the complete skill first. Evidence has ${artifacts.pageCount} pages: read the next page in order, or reread a prior page. Each result is complete text, at most 51,200 UTF-8 bytes. No other paths or directory reads are allowed. The skill's commitment, correction, deduplication, promised-outcome, ambiguity and historical-evidence guidance applies; its task mutation, approval and manual cross-session workflows do not.`,
83
+ parameters: Type.Object(
84
+ { path: Type.String(), page: Type.Optional(cursor) },
85
+ { additionalProperties: false },
86
+ ),
56
87
  executionMode: 'sequential',
57
88
  async execute(_id, args) {
58
- try {
59
- checkDeadline();
60
- if (failed) throw new Error('Review failed');
61
- if (staged !== undefined) {
62
- if (submission) throw new Error('Duplicate submission');
63
- return {
64
- content: [{ type: 'text', text: 'Review closed.' }],
65
- details: {},
66
- terminate: true,
67
- };
68
- }
69
- const data = await execute(args as Static<T>);
70
- checkDeadline();
71
- return {
72
- content: [{ type: 'text', text: serializedResponse(data) }],
73
- details: {},
74
- terminate: staged !== undefined,
75
- };
76
- } catch (error) {
77
- failed = true;
78
- throw error;
79
- }
89
+ assertFresh();
90
+ if (submitted) throw new Error('Capture submission is terminal');
91
+ const { path, page } = args as { path: string; page?: number };
92
+ const read = artifacts.read(path, page);
93
+ const result = { content: [{ type: 'text' as const, text: read.text }], details: {} };
94
+ acceptedReads.set(result, () => {
95
+ assertFresh();
96
+ read.accept();
97
+ });
98
+ return result;
80
99
  },
81
- });
82
- const tools = [
83
- tool(
84
- 'remembrancer_read_evidence',
85
- 'Read the next frozen evidence page. Read every continuation before submission.',
86
- Type.Object({}),
87
- () => current.page(),
88
- ),
89
- tool(
90
- 'remembrancer_context',
91
- 'Read earlier frozen context for an eligible evidence item; not additional extraction scope.',
92
- Type.Object({
93
- selected: Type.Object({
94
- sessionId: Type.String(),
95
- branchId: Type.String(),
96
- entryId: Type.String(),
97
- editId: Type.Union([Type.String(), Type.Null()]),
98
- }),
100
+ },
101
+ {
102
+ name: 'remembrancer_context',
103
+ label: 'Earlier frozen conversation',
104
+ description:
105
+ 'Read earlier conversation in the owned frozen branch. Supporting context only, never eligible evidence or coverage. Select an evidence sessionId/branchId/entryId/editId from review.jsonl. Each window has at most 40 earlier entries. Finish nextOffset text continuations for that window, then use nextSkip as skip (offset 0) for the next older window, until null.',
106
+ parameters: Type.Object(
107
+ {
108
+ selected: Type.Object(
109
+ {
110
+ sessionId: Type.String(),
111
+ branchId: Type.String(),
112
+ entryId: Type.String(),
113
+ editId: Type.Union([Type.String(), Type.Null()]),
114
+ },
115
+ { additionalProperties: false },
116
+ ),
99
117
  before: Type.Optional(Type.Integer({ minimum: 1, maximum: 40 })),
100
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
101
- }),
102
- (args: { selected: Selected; before?: number; offset?: number }) =>
103
- current.context({ ...args, batch: current.id }),
118
+ skip: Type.Optional(cursor),
119
+ offset: Type.Optional(cursor),
120
+ },
121
+ { additionalProperties: false },
104
122
  ),
105
- tool(
106
- 'remembrancer_tasks',
107
- 'Read tasks, including completed tasks. No writes or arbitrary filters.',
108
- Type.Object({
123
+ executionMode: 'sequential',
124
+ async execute(_id, args) {
125
+ guardRead();
126
+ return reply(
127
+ current.context({
128
+ skip: 0,
129
+ ...(args as Parameters<CaptureReview['context']>[0]),
130
+ batch: current.id,
131
+ }),
132
+ );
133
+ },
134
+ },
135
+ {
136
+ name: 'remembrancer_tasks',
137
+ label: 'Read retained tasks',
138
+ description:
139
+ 'Read-only retained Taskwarrior export, including completed tasks. List with optional case-insensitive query and offset; follow nextOffset. Summaries are discovery only. For exact task detail provide uuid and optional position, concatenate json fragments until next is null. All reads use one retained attempt-local export. No task writes. Each JSON result is at most 51,200 UTF-8 bytes.',
140
+ parameters: Type.Object(
141
+ {
142
+ query: Type.Optional(Type.String()),
143
+ offset: Type.Optional(cursor),
109
144
  uuid: Type.Optional(Type.String()),
110
- status: Type.Optional(stringEnumSchema(['pending', 'completed'] as const)),
111
- offset: Type.Optional(Type.Integer({ minimum: 0 })),
112
- }),
113
- lookupTasks,
114
- ),
115
- tool(
116
- 'remembrancer_proposals',
117
- proposalReadDescription,
118
- proposalReadParameters,
119
- (args: { offset?: number }) => readProposals(db, args),
120
- ),
121
- tool(
122
- 'remembrancer_submit',
123
- 'Submit final proposals once, alone in its tool batch. Empty is valid. Does not approve or apply tasks.',
124
- Type.Object({ proposals: Type.Array(proposalParameters) }),
125
- (args: { proposals: ProposalSubmission[] }) => {
126
- db.validateCapture(current.id, args.proposals);
127
- staged = structuredClone(args.proposals);
128
- return { submitted: true };
145
+ position: Type.Optional(cursor),
129
146
  },
130
- true,
147
+ { additionalProperties: false },
131
148
  ),
132
- ];
133
- checkDeadline();
149
+ executionMode: 'sequential',
150
+ async execute(_id, args) {
151
+ const { tasks } = await matchingView();
152
+ const {
153
+ query,
154
+ offset = 0,
155
+ uuid,
156
+ position = 0,
157
+ } = args as { query?: string; offset?: number; uuid?: string; position?: number };
158
+ if (uuid !== undefined) {
159
+ if (query !== undefined || 'offset' in (args as object))
160
+ throw new Error('Task detail cannot use list fields');
161
+ const task = tasks.find((item) => item['uuid'] === uuid);
162
+ if (!task) throw new Error('Missing retained task');
163
+ const json = JSON.stringify(task);
164
+ if (
165
+ !Number.isSafeInteger(position) ||
166
+ position < 0 ||
167
+ position > json.length ||
168
+ splitsSurrogatePair(json, position)
169
+ )
170
+ throw new Error('Invalid task detail position');
171
+ const build = (length: number) => ({
172
+ uuid,
173
+ position,
174
+ json: json.slice(position, position + length),
175
+ next: position + length < json.length ? { uuid, position: position + length } : null,
176
+ });
177
+ const length = fitPrefixLength(json, position, (length) => fitsResponse(build(length)));
178
+ if (!length && position < json.length) throw new Error('Task detail cannot fit');
179
+ return reply(build(length));
180
+ }
181
+ if ('position' in (args as object) || !Number.isSafeInteger(offset) || offset < 0)
182
+ throw new Error('Invalid task list cursor');
183
+ const term = query?.toLowerCase() ?? '';
184
+ const matching = tasks.filter((task) =>
185
+ ['uuid', 'description', 'project', 'waitingon'].some((key) =>
186
+ String(task[key] ?? '')
187
+ .toLowerCase()
188
+ .includes(term),
189
+ ),
190
+ );
191
+ const entries: object[] = [];
192
+ for (const task of matching.slice(offset, offset + 20)) {
193
+ const description = String(task['description'] ?? '');
194
+ const length = safePrefixLength(description, 0, 160);
195
+ const item = {
196
+ uuid: task['uuid'],
197
+ status: task['status'],
198
+ description: description.slice(0, length),
199
+ truncated: length < description.length,
200
+ };
201
+ if (!fitsResponse({ tasks: [...entries, item], nextOffset: offset + entries.length + 1 }))
202
+ break;
203
+ entries.push(item);
204
+ }
205
+ if (!entries.length && offset < matching.length) throw new Error('Task summary cannot fit');
206
+ return reply({
207
+ tasks: entries,
208
+ nextOffset: offset + entries.length < matching.length ? offset + entries.length : null,
209
+ });
210
+ },
211
+ },
212
+ {
213
+ name: 'remembrancer_proposals',
214
+ label: 'Read retained proposals',
215
+ description: proposalReadDescription,
216
+ parameters: proposalReadParameters,
217
+ executionMode: 'sequential',
218
+ async execute(_id, args) {
219
+ const { proposals } = await matchingView();
220
+ const request = args as ProposalReadArgs;
221
+ if (request.id !== undefined) readProposal(db, request.id, request.revision!);
222
+ assertFresh();
223
+ return reply(
224
+ readProposals(
225
+ {
226
+ proposals: (state, offset = 0, limit = 50) =>
227
+ proposals
228
+ .filter((proposal) => state === undefined || proposal.state === state)
229
+ .slice(offset, offset + limit),
230
+ proposal: (id) => proposals.find((proposal) => proposal.id === id),
231
+ },
232
+ request,
233
+ ),
234
+ );
235
+ },
236
+ },
237
+ {
238
+ name: 'remembrancer_submit',
239
+ label: 'Submit finalized capture',
240
+ description:
241
+ 'Terminal submission, once and alone in its batch, only after complete skill and ordered evidence delivery. records reports commitments, not exhaustive discovery. Each record has a unique local key, exact observations (kind and eligible reference), one FoldedFinding state per observed branch, identity ambiguity (not conflicting requested changes), and declared task/proposal candidate judgments (same/different/ambiguous). Proposal candidates require retained revision; task IDs are full UUIDs. dispositions groups record keys by definite matched identity, each key exactly once, with nonempty reason and either null for verified no-change or finalized {change,question,explanation}. Preserve required questions verbatim within the final question. Never supply expected snapshots, proposal publication IDs, revisions or references in a disposition. Code binds those. Ambiguous identity needs an add-shaped question, never a guessed target. Conflicting changes to a uniquely matched task require a question while preserving that task target, never an addition. Applying/uncertain matches permit only host-verified satisfaction and null. Empty records and dispositions are valid after all delivery, meaning no commitments reported, not proven absence. Acceptance stages only in memory; cleanup and publication guards may still fail.',
242
+ parameters: captureSubmitParameters,
243
+ executionMode: 'sequential',
244
+ async execute(_id, args) {
245
+ guardRead();
246
+ artifacts.assertDelivered();
247
+ submitted = true;
248
+ if (view)
249
+ for (const proposal of view.proposals)
250
+ db.assertProposalRevision(proposal.id, proposal.revision);
251
+ staged = validateCaptureSubmission(args, current, view?.tasks ?? [], view?.proposals ?? []);
252
+ assertFresh();
253
+ return { ...reply({ accepted: true }), terminate: true };
254
+ },
255
+ },
256
+ ];
257
+ try {
134
258
  await runReviewer({
135
- cwd: ctx.cwd,
136
- model: ctx.model,
137
- sessionId,
259
+ ...input,
138
260
  tools,
139
- signal: controller.signal,
261
+ instruction: buildOpeningPrompt(artifacts.skillPath, artifacts.reviewPath),
262
+ acceptToolResult(result) {
263
+ acceptedReads.get(result)?.();
264
+ acceptedReads.delete(result);
265
+ },
140
266
  });
141
- // runReviewer has awaited prompt/abort settlement and disposed the temporary session.
142
- checkDeadline();
143
- if (failed || staged === undefined)
144
- throw new Error('Review did not submit a valid final result');
145
- db.finishCapture(current.id, staged);
146
- } catch (error) {
147
- const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
148
- ctx.ui.notify(`Remembrancer capture ${sessionId} failed:\n${detail}`, 'warning');
267
+ assertFresh();
268
+ artifacts.assertDelivered();
269
+ if (!submitted || staged === undefined) throw new Error('Reviewer did not submit a result');
270
+ if (view)
271
+ for (const proposal of view.proposals)
272
+ db.assertProposalRevision(proposal.id, proposal.revision);
149
273
  } finally {
150
- if (timer !== undefined) clearTimeout(timer);
151
- owned?.releaseReview();
274
+ // runReviewer has already awaited disposal, including cancellation cleanup.
275
+ artifacts.dispose();
152
276
  }
277
+ assertFresh();
278
+ return staged;
153
279
  }