@robhowley/pi-remembrancer 0.4.0 → 0.5.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.
@@ -4,6 +4,9 @@ import { StringEnum, Type } from '@earendil-works/pi-ai';
4
4
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
5
5
  import { CheckpointStore } from './checkpoints.js';
6
6
  import { loadRemembrancerConfig } from './config.js';
7
+ import { captureOutgoing, CAPTURE_BUDGET_MS } from './capture.js';
8
+ import { openProposals } from './proposal-ui.js';
9
+ import { proposalReadDescription, proposalReadParameters, readProposals } from './proposal-read.js';
7
10
  import { discoverSources } from './discovery.js';
8
11
  import {
9
12
  renderReviewCall,
@@ -13,7 +16,6 @@ import {
13
16
  } from './render.js';
14
17
  import { copyWarnings, warningMessages, type WarningRecord } from './warnings.js';
15
18
  import {
16
- branchEvidence,
17
19
  prepareReview,
18
20
  resolveSeedSince,
19
21
  ReviewBudget,
@@ -24,13 +26,21 @@ import {
24
26
  type Source,
25
27
  type Tip,
26
28
  } from './evidence.js';
27
-
28
- type Selected = {
29
- sessionId: string;
30
- branchId: string;
31
- entryId: string;
32
- editId: string | null;
33
- };
29
+ import {
30
+ boundedEvidencePage,
31
+ frozenContext,
32
+ groupEvidencePage,
33
+ serializedResponse,
34
+ type Selected,
35
+ } from './review-pages.js';
36
+
37
+ export {
38
+ REVIEW_RESPONSE_MAX_BYTES,
39
+ boundedEvidencePage,
40
+ groupEvidencePage,
41
+ type EvidencePageEntry,
42
+ type PageCursor,
43
+ } from './review-pages.js';
34
44
 
35
45
  type ReviewArgs = {
36
46
  action: 'begin' | 'next' | 'finish' | 'cancel' | 'context';
@@ -60,7 +70,7 @@ type Batch = {
60
70
 
61
71
  export const REMEMBRANCER_COMMAND_NAME = 'remembrancer';
62
72
  export const REMEMBRANCER_COMMAND_USAGE =
63
- 'Usage: /remembrancer seed <Nd>\n /remembrancer help';
73
+ 'Usage: /remembrancer seed <Nd>\n /remembrancer proposals\n /remembrancer help';
64
74
  export const REMEMBRANCER_HELP = [
65
75
  REMEMBRANCER_COMMAND_USAGE,
66
76
  'Seed saved-session evidence from a bounded historical window, then follow the Remembrancer skill.',
@@ -68,6 +78,7 @@ export const REMEMBRANCER_HELP = [
68
78
  ].join('\n');
69
79
 
70
80
  const REMEMBRANCER_SUBCOMMANDS = [
81
+ { value: 'proposals', label: 'proposals', description: 'Review stored task proposals locally' },
71
82
  {
72
83
  value: 'seed ',
73
84
  label: 'seed',
@@ -85,6 +96,7 @@ const REMEMBRANCER_SEED_DURATIONS = [
85
96
 
86
97
  type RemembrancerCommandArgs =
87
98
  | { ok: true; mode: 'help' }
99
+ | { ok: true; mode: 'proposals' }
88
100
  | { ok: true; mode: 'seed'; duration: string }
89
101
  | { ok: false; message: string };
90
102
 
@@ -94,6 +106,7 @@ export function parseRemembrancerCommandArgs(args: string): RemembrancerCommandA
94
106
 
95
107
  if (tokens.length === 0 || (subcommand === 'help' && tokens.length === 1))
96
108
  return { ok: true, mode: 'help' };
109
+ if (subcommand === 'proposals' && tokens.length === 1) return { ok: true, mode: 'proposals' };
97
110
  if (subcommand === 'help')
98
111
  return { ok: false, message: `Help does not accept arguments. ${REMEMBRANCER_COMMAND_USAGE}` };
99
112
  if (subcommand !== 'seed')
@@ -152,181 +165,6 @@ const selectedParameters = Type.Object({
152
165
  editId: Type.Union([Type.String(), Type.Null()]),
153
166
  });
154
167
 
155
- export const REVIEW_RESPONSE_MAX_BYTES = 50 * 1024;
156
- const PAGE_MAX_TEXT_UNITS = 48_000;
157
- const PAGE_MAX_ENTRIES = 200;
158
-
159
- export type EvidencePageEntry = Evidence & { offset: number; continues: boolean };
160
- type EvidencePageItem = Pick<Evidence, 'entryId' | 'role' | 'text' | 'timestamp' | 'editId'> & {
161
- offset: number;
162
- continues: boolean;
163
- };
164
- type EvidenceGroup = Pick<
165
- Evidence,
166
- 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'
167
- > & {
168
- entries: EvidencePageItem[];
169
- };
170
- export type PageCursor = { index: number; offset: number };
171
-
172
- function serializedResponse(data: object): string {
173
- const text = JSON.stringify(data);
174
- if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
175
- const bytes = Buffer.byteLength(text, 'utf8');
176
- if (bytes > REVIEW_RESPONSE_MAX_BYTES)
177
- throw new Error(
178
- `Remembrancer response is ${bytes} UTF-8 bytes, over the ${REVIEW_RESPONSE_MAX_BYTES}-byte limit; metadata or envelope cannot fit.`,
179
- );
180
- return text;
181
- }
182
-
183
- function fitsResponse(data: object): boolean {
184
- const text = JSON.stringify(data);
185
- if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
186
- return Buffer.byteLength(text, 'utf8') <= REVIEW_RESPONSE_MAX_BYTES;
187
- }
188
-
189
- function sameGroup(
190
- a: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
191
- b: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
192
- ): boolean {
193
- return (
194
- a.file === b.file &&
195
- a.sessionId === b.sessionId &&
196
- a.cwd === b.cwd &&
197
- a.branchId === b.branchId &&
198
- a.reviewedThrough === b.reviewedThrough
199
- );
200
- }
201
-
202
- export function groupEvidencePage(entries: readonly EvidencePageEntry[]): EvidenceGroup[] {
203
- const groups: EvidenceGroup[] = [];
204
- for (const entry of entries) {
205
- let group = groups.at(-1);
206
- if (!group || !sameGroup(group, entry)) {
207
- group = {
208
- file: entry.file,
209
- sessionId: entry.sessionId,
210
- cwd: entry.cwd,
211
- branchId: entry.branchId,
212
- reviewedThrough: entry.reviewedThrough,
213
- entries: [],
214
- };
215
- groups.push(group);
216
- }
217
- group.entries.push({
218
- entryId: entry.entryId,
219
- role: entry.role,
220
- text: entry.text,
221
- timestamp: entry.timestamp,
222
- editId: entry.editId,
223
- offset: entry.offset,
224
- continues: entry.continues,
225
- });
226
- }
227
- return groups;
228
- }
229
-
230
- function splitsSurrogatePair(text: string, boundary: number): boolean {
231
- if (boundary <= 0 || boundary >= text.length) return false;
232
- const before = text.charCodeAt(boundary - 1);
233
- const after = text.charCodeAt(boundary);
234
- return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff;
235
- }
236
-
237
- function safePrefixLength(text: string, start: number, maxUnits: number): number {
238
- let length = Math.min(maxUnits, text.length - start);
239
- if (length > 0 && splitsSurrogatePair(text, start + length)) length--;
240
- return length;
241
- }
242
-
243
- export function boundedEvidencePage(
244
- evidence: readonly Evidence[],
245
- initial: PageCursor,
246
- buildResponse: (entries: EvidencePageEntry[], cursor: PageCursor) => Record<string, unknown>,
247
- ): { data: Record<string, unknown>; cursor: PageCursor } {
248
- let { index, offset } = initial;
249
- const entries: EvidencePageEntry[] = [];
250
- let remainingText = PAGE_MAX_TEXT_UNITS;
251
-
252
- const candidateFits = (entry: EvidencePageEntry, cursor: PageCursor) =>
253
- fitsResponse(buildResponse([...entries, entry], cursor));
254
- const append = (item: Evidence, length: number) => {
255
- const start = offset;
256
- const continues = start + length < item.text.length;
257
- const entry: EvidencePageEntry = {
258
- ...item,
259
- text: item.text.slice(start, start + length),
260
- offset: start,
261
- continues,
262
- };
263
- const cursor = continues ? { index, offset: start + length } : { index: index + 1, offset: 0 };
264
- if (!candidateFits(entry, cursor)) return false;
265
- entries.push(entry);
266
- remainingText -= length;
267
- ({ index, offset } = cursor);
268
- return true;
269
- };
270
-
271
- while (entries.length < PAGE_MAX_ENTRIES && remainingText > 0 && index < evidence.length) {
272
- const item = evidence[index];
273
- if (!item) break;
274
- const wanted = safePrefixLength(item.text, offset, remainingText);
275
-
276
- if (item.text.length === offset) {
277
- if (!append(item, 0)) {
278
- if (entries.length === 0)
279
- throw new Error(
280
- `Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
281
- );
282
- break;
283
- }
284
- continue;
285
- }
286
- if (wanted === 0) break;
287
-
288
- if (append(item, wanted)) {
289
- if (entries.at(-1)?.continues || remainingText === 0) break;
290
- continue;
291
- }
292
-
293
- let low = 0;
294
- let high = wanted - 1;
295
- while (low < high) {
296
- const middle = Math.ceil((low + high) / 2);
297
- const length = safePrefixLength(item.text, offset, middle);
298
- if (length === 0) {
299
- low = middle + 1;
300
- continue;
301
- }
302
- const start = offset;
303
- const entry: EvidencePageEntry = {
304
- ...item,
305
- text: item.text.slice(start, start + length),
306
- offset: start,
307
- continues: true,
308
- };
309
- if (candidateFits(entry, { index, offset: start + length })) {
310
- low = middle;
311
- continue;
312
- }
313
- high = middle - 1;
314
- }
315
- const length = safePrefixLength(item.text, offset, low);
316
- if (length > 0 && append(item, length)) break;
317
- if (entries.length === 0)
318
- throw new Error(
319
- `Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
320
- );
321
- break;
322
- }
323
-
324
- const cursor = { index, offset };
325
- const data = buildResponse(entries, cursor);
326
- serializedResponse(data);
327
- return { data, cursor };
328
- }
329
-
330
168
  function page(batch: Batch, envelope: Record<string, unknown> = {}) {
331
169
  const result = boundedEvidencePage(batch.evidence, batch, (entries, cursor) => ({
332
170
  batch: batch.token,
@@ -354,46 +192,6 @@ function usesDefaultSessionDir(ctx: ExtensionContext): boolean {
354
192
  return manager.usesDefaultSessionDir();
355
193
  }
356
194
 
357
- function contextPage(batch: string, selected: Selected, items: Evidence[], offset: number) {
358
- const total = items.reduce((length, item) => length + item.text.length, 0);
359
- if (offset > total) throw new Error('Context offset is beyond the requested range');
360
-
361
- let index = 0;
362
- let localOffset = 0;
363
- let position = 0;
364
- while (index < items.length) {
365
- const item = items[index]!;
366
- if (item.text.length === 0) {
367
- if (offset === position) break;
368
- index++;
369
- continue;
370
- }
371
- const end = position + item.text.length;
372
- if (offset < end) {
373
- localOffset = offset - position;
374
- if (splitsSurrogatePair(item.text, localOffset))
375
- throw new Error('Context offset splits a surrogate pair; use a returned nextOffset.');
376
- break;
377
- }
378
- position = end;
379
- index++;
380
- }
381
-
382
- const result = boundedEvidencePage(items, { index, offset: localOffset }, (entries, cursor) => {
383
- const nextOffset =
384
- items.slice(0, cursor.index).reduce((length, item) => length + item.text.length, 0) +
385
- cursor.offset;
386
- return {
387
- batch,
388
- selected,
389
- contextOnly: true,
390
- groups: groupEvidencePage(entries),
391
- nextOffset: nextOffset < total ? nextOffset : null,
392
- };
393
- });
394
- return result.data;
395
- }
396
-
397
195
  export default function remembrancer(pi: ExtensionAPI) {
398
196
  let db: CheckpointStore | undefined;
399
197
  let batch: Batch | undefined;
@@ -435,7 +233,7 @@ export default function remembrancer(pi: ExtensionAPI) {
435
233
  }
436
234
 
437
235
  pi.registerCommand(REMEMBRANCER_COMMAND_NAME, {
438
- description: 'Start a bounded historical Remembrancer review',
236
+ description: 'Review stored task proposals or start a bounded historical review',
439
237
  getArgumentCompletions: getRemembrancerArgumentCompletions,
440
238
  handler: async (args, ctx) => {
441
239
  const parsed = parseRemembrancerCommandArgs(args);
@@ -454,6 +252,11 @@ export default function remembrancer(pi: ExtensionAPI) {
454
252
  );
455
253
  return;
456
254
  }
255
+ if (parsed.mode === 'proposals') {
256
+ if (ctx.mode !== 'tui') throw new Error('Task proposals require TUI mode');
257
+ await openProposals(ctx, store());
258
+ return;
259
+ }
457
260
  if (!ctx.isIdle()) {
458
261
  ctx.ui.notify(
459
262
  'Pi is busy. Wait for the current run to finish, then retry the seed command.',
@@ -552,58 +355,46 @@ export default function remembrancer(pi: ExtensionAPI) {
552
355
  function contextReview(args: ReviewArgs): object {
553
356
  if (!batch || args.batch !== batch.token)
554
357
  throw new Error('No matching open review in this Pi session.');
555
- const selected = args.selected;
556
- if (!selected) throw new Error('Context requires a selected evidence item.');
557
- const selectedEvidence = batch.evidence.find(
558
- (item) =>
559
- item.sessionId === selected.sessionId &&
560
- item.branchId === selected.branchId &&
561
- item.entryId === selected.entryId &&
562
- item.editId === selected.editId,
563
- );
564
- if (!selectedEvidence) throw new Error('Selected evidence is not in this review batch.');
565
-
566
- const snapshot = batch.snapshots.find(
567
- (candidate) =>
568
- candidate.source.sessionId === selected.sessionId &&
569
- resolve(candidate.source.file) === resolve(selectedEvidence.file),
570
- );
571
- if (!snapshot) throw new Error('Selected evidence snapshot is unavailable.');
572
-
573
- const branch = branchEvidence(
574
- snapshot.tree,
575
- {
576
- file: snapshot.source.file,
577
- sessionId: selected.sessionId,
578
- entryId: selected.branchId,
579
- },
580
- selectedEvidence.reviewedThrough,
581
- );
582
- const selectedIndex = branch.findIndex(
583
- (item) => item.entryId === selected.entryId && item.editId === selected.editId,
584
- );
585
- if (selectedIndex < 0) throw new Error('Selected evidence is not in the frozen branch.');
586
-
587
- const before = args.before ?? 1;
588
- const offset = args.offset ?? 0;
589
- if (!Number.isInteger(before) || before < 1 || before > 40)
590
- throw new Error('Context before must be an integer from 1 to 40.');
591
- if (!Number.isInteger(offset) || offset < 0)
592
- throw new Error('Context offset must be a nonnegative integer.');
593
-
594
- const items = branch.slice(Math.max(0, selectedIndex - before), selectedIndex);
595
- return contextPage(batch.token, selected, items, offset);
358
+ return frozenContext(batch, batch.token, args);
596
359
  }
597
360
 
598
361
  pi.on('session_start', (_event, ctx) => {
599
362
  if (loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted()).disabled) return;
600
363
  registerReviewTool();
364
+ pi.registerTool({
365
+ name: 'remembrancer_proposals',
366
+ label: 'Remembrancer proposals',
367
+ description: proposalReadDescription,
368
+ parameters: proposalReadParameters,
369
+ async execute(_id, args) {
370
+ const data = readProposals(store(), args);
371
+ return {
372
+ content: [{ type: 'text', text: serializedResponse(data) }],
373
+ details: {},
374
+ };
375
+ },
376
+ });
601
377
  enroll(ctx);
378
+ if (ctx.mode === 'tui') {
379
+ const count = store().proposalCount();
380
+ if (count) ctx.ui.notify(`${count} task proposals · /remembrancer proposals`, 'info');
381
+ }
602
382
  });
603
- pi.on('session_shutdown', () => {
604
- batch = undefined;
605
- db?.close();
606
- db = undefined;
383
+ pi.on('session_shutdown', async (event, ctx) => {
384
+ try {
385
+ const deadline = Date.now() + CAPTURE_BUDGET_MS;
386
+ try {
387
+ // Abandon manual coverage before capture claims the same process lock.
388
+ release();
389
+ await captureOutgoing(ctx, store, deadline);
390
+ } finally {
391
+ db?.close();
392
+ db = undefined;
393
+ }
394
+ } catch (error) {
395
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
396
+ ctx.ui.notify(`Remembrancer shutdown (${event.reason}) failed:\n${detail}`, 'warning');
397
+ }
607
398
  });
608
399
 
609
400
  function registerReviewTool() {
@@ -0,0 +1,13 @@
1
+ import { Type } from '@earendil-works/pi-ai';
2
+ import type { CheckpointStore } from './checkpoints.js';
3
+
4
+ export const proposalReadDescription =
5
+ 'Read stored proposals, including drafts, decisions and dismissal history. Each complete JSON response is capped at 50 KiB UTF-8.';
6
+ export const proposalReadParameters = Type.Object({
7
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
8
+ });
9
+
10
+ export function readProposals(db: CheckpointStore, { offset = 0 }: { offset?: number }) {
11
+ const proposals = db.proposals(undefined, offset, 1);
12
+ return { proposals, nextOffset: proposals.length ? offset + 1 : null };
13
+ }