@robhowley/pi-remembrancer 0.3.0 → 0.4.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.
@@ -152,26 +152,191 @@ const selectedParameters = Type.Object({
152
152
  editId: Type.Union([Type.String(), Type.Null()]),
153
153
  });
154
154
 
155
- // Return every character, even when one message is larger than an entire page.
156
- function page(batch: Batch) {
157
- const entries = [];
158
- let remaining = 12000;
159
- while (remaining > 0 && entries.length < 40 && batch.index < batch.evidence.length) {
160
- const evidence = batch.evidence[batch.index];
161
- if (!evidence) break;
162
- const { text, ...source } = evidence;
163
- const start = batch.offset;
164
- const excerpt = text.slice(start, start + remaining);
165
- remaining -= excerpt.length;
166
- batch.offset += excerpt.length;
167
- const continues = batch.offset < text.length;
168
- entries.push({ ...source, text: excerpt, offset: start, continues });
169
- if (!continues) {
170
- batch.index++;
171
- batch.offset = 0;
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);
172
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
+ });
173
226
  }
174
- return { batch: batch.token, entries, hasMore: batch.index < batch.evidence.length };
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
+ function page(batch: Batch, envelope: Record<string, unknown> = {}) {
331
+ const result = boundedEvidencePage(batch.evidence, batch, (entries, cursor) => ({
332
+ batch: batch.token,
333
+ groups: groupEvidencePage(entries),
334
+ hasMore: cursor.index < batch.evidence.length,
335
+ ...envelope,
336
+ }));
337
+ batch.index = result.cursor.index;
338
+ batch.offset = result.cursor.offset;
339
+ return result.data;
175
340
  }
176
341
 
177
342
  function sourceKey(source: Pick<Source, 'sessionId' | 'file'>): string {
@@ -189,37 +354,44 @@ function usesDefaultSessionDir(ctx: ExtensionContext): boolean {
189
354
  return manager.usesDefaultSessionDir();
190
355
  }
191
356
 
192
- function contextPage(items: Evidence[], offset: number) {
357
+ function contextPage(batch: string, selected: Selected, items: Evidence[], offset: number) {
193
358
  const total = items.reduce((length, item) => length + item.text.length, 0);
194
359
  if (offset > total) throw new Error('Context offset is beyond the requested range');
195
360
 
196
- const entries = [];
361
+ let index = 0;
362
+ let localOffset = 0;
197
363
  let position = 0;
198
- let remaining = 12000;
199
- let written = 0;
200
- for (const item of items) {
201
- const end = position + item.text.length;
202
- if (offset >= end) {
203
- position = end;
364
+ while (index < items.length) {
365
+ const item = items[index]!;
366
+ if (item.text.length === 0) {
367
+ if (offset === position) break;
368
+ index++;
204
369
  continue;
205
370
  }
206
- const localOffset = Math.max(0, offset - position);
207
- const text = item.text.slice(localOffset, localOffset + remaining);
208
- if (text.length === 0) break;
209
- entries.push({
210
- ...item,
211
- text,
212
- offset: localOffset,
213
- continues: localOffset + text.length < item.text.length,
214
- });
215
- written += text.length;
216
- remaining -= text.length;
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
+ }
217
378
  position = end;
218
- if (remaining === 0) break;
379
+ index++;
219
380
  }
220
381
 
221
- const nextOffset = offset + written < total ? offset + written : null;
222
- return { entries, nextOffset };
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;
223
395
  }
224
396
 
225
397
  export default function remembrancer(pi: ExtensionAPI) {
@@ -245,7 +417,7 @@ export default function remembrancer(pi: ExtensionAPI) {
245
417
 
246
418
  function result(data: object, details: ReviewResultDetails) {
247
419
  return {
248
- content: [{ type: 'text' as const, text: JSON.stringify(data) }],
420
+ content: [{ type: 'text' as const, text: serializedResponse(data) }],
249
421
  details,
250
422
  };
251
423
  }
@@ -367,15 +539,14 @@ export default function remembrancer(pi: ExtensionAPI) {
367
539
  : coverageChanged
368
540
  ? 'coverage-pending'
369
541
  : 'already-covered';
370
- return {
371
- ...page(batch),
542
+ return page(batch, {
372
543
  status,
373
544
  warnings,
374
545
  incomplete,
375
546
  coverageChanged,
376
547
  ...(requestedSince === null ? {} : { requestedSince }),
377
548
  capturedTips: batch.tips.length,
378
- };
549
+ });
379
550
  }
380
551
 
381
552
  function contextReview(args: ReviewArgs): object {
@@ -421,14 +592,7 @@ export default function remembrancer(pi: ExtensionAPI) {
421
592
  throw new Error('Context offset must be a nonnegative integer.');
422
593
 
423
594
  const items = branch.slice(Math.max(0, selectedIndex - before), selectedIndex);
424
- const paged = contextPage(items, offset);
425
- return {
426
- batch: batch.token,
427
- selected,
428
- contextOnly: true,
429
- entries: paged.entries,
430
- nextOffset: paged.nextOffset,
431
- };
595
+ return contextPage(batch.token, selected, items, offset);
432
596
  }
433
597
 
434
598
  pi.on('session_start', (_event, ctx) => {
@@ -447,7 +611,7 @@ export default function remembrancer(pi: ExtensionAPI) {
447
611
  name: 'remembrancer_review',
448
612
  label: 'Remembrancer review',
449
613
  description:
450
- 'Read incremental cross-session evidence or finish a fully resolved review. Follow the remembrancer skill. Read every page before finishing.',
614
+ 'Read incremental cross-session evidence or finish a fully resolved review. Evidence is grouped by consecutive source and branch metadata. Each complete JSON response is capped at 50 KiB UTF-8. Follow the remembrancer skill and read every page before finishing.',
451
615
  renderCall: renderReviewCall,
452
616
  renderResult: renderReviewResult,
453
617
  parameters: Type.Object({
@@ -510,15 +674,9 @@ export default function remembrancer(pi: ExtensionAPI) {
510
674
  if (batch.index < batch.evidence.length)
511
675
  throw new Error('Read all evidence pages before finishing.');
512
676
 
513
- store().finish({
514
- sources: batch.stagedSources,
515
- sourceDefaults: batch.sourceDefaults,
516
- checkpoints: batch.checkpoints,
517
- });
518
677
  const reviewedTips = batch.tips.length;
519
678
  const finishedBatch = batch;
520
679
  const details = resultDetails('finish', finishedBatch);
521
- release();
522
680
  const response: Record<string, unknown> = { finished: true, reviewedTips };
523
681
  if (finishedBatch.requestedSince !== null || finishedBatch.incomplete) {
524
682
  response['coverageChanged'] = finishedBatch.coverageChanged;
@@ -532,7 +690,14 @@ export default function remembrancer(pi: ExtensionAPI) {
532
690
  if (finishedBatch.requestedSince !== null)
533
691
  response['requestedSince'] = finishedBatch.requestedSince;
534
692
  }
535
- return result(response, details);
693
+ const responseResult = result(response, details);
694
+ store().finish({
695
+ sources: finishedBatch.stagedSources,
696
+ sourceDefaults: finishedBatch.sourceDefaults,
697
+ checkpoints: finishedBatch.checkpoints,
698
+ });
699
+ release();
700
+ return responseResult;
536
701
  },
537
702
  });
538
703
  }
@@ -24,15 +24,18 @@ type EvidenceEntry = {
24
24
  text?: unknown;
25
25
  role?: unknown;
26
26
  timestamp?: unknown;
27
- sessionId?: unknown;
28
- branchId?: unknown;
29
27
  entryId?: unknown;
30
28
  editId?: unknown;
29
+ offset?: unknown;
30
+ continues?: unknown;
31
+ };
32
+ type EvidenceGroup = {
31
33
  file?: unknown;
34
+ sessionId?: unknown;
32
35
  cwd?: unknown;
36
+ branchId?: unknown;
33
37
  reviewedThrough?: unknown;
34
- offset?: unknown;
35
- continues?: unknown;
38
+ entries?: unknown;
36
39
  };
37
40
 
38
41
  type RendererContext = Parameters<ReviewRenderResult>[3];
@@ -121,7 +124,11 @@ function countValue(value: unknown): number {
121
124
  }
122
125
 
123
126
  function entryCount(payload: ResultPayload): number {
124
- return Array.isArray(payload['entries']) ? payload['entries'].length : 0;
127
+ if (!Array.isArray(payload['groups'])) return 0;
128
+ return payload['groups'].reduce((count, value) => {
129
+ const group = record(value) as EvidenceGroup | undefined;
130
+ return count + (Array.isArray(group?.entries) ? group.entries.length : 0);
131
+ }, 0);
125
132
  }
126
133
 
127
134
  function hasMore(payload: ResultPayload): boolean {
@@ -248,28 +255,34 @@ function appendWarningBlocks(
248
255
 
249
256
  function appendEvidenceBlocks(
250
257
  lines: string[],
251
- entries: readonly unknown[],
258
+ groups: readonly unknown[],
252
259
  contextOnly: boolean,
253
260
  theme: Parameters<ReviewRenderResult>[2],
254
261
  ): void {
255
- for (const [index, value] of entries.entries()) {
256
- const entry = record(value) as EvidenceEntry | undefined;
257
- lines.push('');
258
- lines.push(` ${theme.bold(`${contextOnly ? 'Context' : 'Evidence'} ${index + 1}`)}`);
259
- lines.push(` role: ${sanitizeText(String(entry?.role ?? 'unknown'))}`);
260
- lines.push(` timestamp: ${sanitizeText(String(entry?.timestamp ?? 'unknown'))}`);
261
- lines.push(` sessionId: ${sanitizeText(String(entry?.sessionId ?? 'unknown'))}`);
262
- lines.push(` branchId: ${sanitizeText(String(entry?.branchId ?? 'unknown'))}`);
263
- lines.push(` entryId: ${sanitizeText(String(entry?.entryId ?? 'unknown'))}`);
264
- lines.push(` editId: ${sanitizeText(String(entry?.editId ?? 'none'))}`);
265
- lines.push(` source: ${sanitizeText(String(entry?.file ?? 'unknown'))}`);
266
- lines.push(` cwd: ${sanitizeText(String(entry?.cwd ?? 'unknown'))}`);
267
- lines.push(` reviewedThrough: ${sanitizeText(String(entry?.reviewedThrough ?? 'none'))}`);
268
- lines.push(` offset: ${sanitizeText(String(entry?.offset ?? 0))}`);
269
- lines.push(` continues: ${entry?.continues === true ? 'true' : 'false'}`);
270
- lines.push(' text:');
271
- lines.push(indent(String(entry?.text ?? ''), ' '));
272
- if (contextOnly) lines.push(' interpretation only: true');
262
+ let index = 0;
263
+ for (const value of groups) {
264
+ const group = record(value) as EvidenceGroup | undefined;
265
+ if (!Array.isArray(group?.entries)) continue;
266
+ for (const entryValue of group.entries) {
267
+ const entry = record(entryValue) as EvidenceEntry | undefined;
268
+ index++;
269
+ lines.push('');
270
+ lines.push(` ${theme.bold(`${contextOnly ? 'Context' : 'Evidence'} ${index}`)}`);
271
+ lines.push(` role: ${sanitizeText(String(entry?.role ?? 'unknown'))}`);
272
+ lines.push(` timestamp: ${sanitizeText(String(entry?.timestamp ?? 'unknown'))}`);
273
+ lines.push(` sessionId: ${sanitizeText(String(group?.sessionId ?? 'unknown'))}`);
274
+ lines.push(` branchId: ${sanitizeText(String(group?.branchId ?? 'unknown'))}`);
275
+ lines.push(` entryId: ${sanitizeText(String(entry?.entryId ?? 'unknown'))}`);
276
+ lines.push(` editId: ${sanitizeText(String(entry?.editId ?? 'none'))}`);
277
+ lines.push(` source: ${sanitizeText(String(group?.file ?? 'unknown'))}`);
278
+ lines.push(` cwd: ${sanitizeText(String(group?.cwd ?? 'unknown'))}`);
279
+ lines.push(` reviewedThrough: ${sanitizeText(String(group?.reviewedThrough ?? 'none'))}`);
280
+ lines.push(` offset: ${sanitizeText(String(entry?.offset ?? 0))}`);
281
+ lines.push(` continues: ${entry?.continues === true ? 'true' : 'false'}`);
282
+ lines.push(' text:');
283
+ lines.push(indent(String(entry?.text ?? ''), ' '));
284
+ if (contextOnly) lines.push(' interpretation only: true');
285
+ }
273
286
  }
274
287
  }
275
288
 
@@ -407,7 +420,7 @@ export const renderReviewResult: ReviewRenderResult = (result, options, theme, c
407
420
  appendWarningBlocks(lines, details.warnings, theme);
408
421
  appendEvidenceBlocks(
409
422
  lines,
410
- Array.isArray(payload['entries']) ? payload['entries'] : [],
423
+ Array.isArray(payload['groups']) ? payload['groups'] : [],
411
424
  payload['contextOnly'] === true,
412
425
  theme,
413
426
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robhowley/pi-remembrancer",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Track and review commitments across Pi sessions to keep your personal Taskwarrior list current.",
6
6
  "engines": {
@@ -32,7 +32,7 @@ Authorization applies to every workflow:
32
32
 
33
33
  ## Taskwarrior commands
34
34
 
35
- Read actual records, including UUID, annotations, and status, before matching. Pass user or session text as one literal, safely shell-quoted argument. Never interpolate untrusted session text into shell syntax. Use the full UUID from Taskwarrior for a specific update.
35
+ Use compact records for initial task discovery. Before confirming a match or proposing a change, read the candidate’s full record, including UUID, status and annotations. Pass user or session text as one literal, safely shell-quoted argument. Never interpolate untrusted session text into shell syntax. Use the full UUID from Taskwarrior for a specific update.
36
36
 
37
37
  ```sh
38
38
  task list
@@ -54,6 +54,10 @@ task project.is:work.ranking status:pending export |
54
54
  jq -c '[.[] | {id, uuid, description, status, project, waitingon, depends}]'
55
55
  ```
56
56
 
57
+ Reuse this compact recipe for reconciliation, including catch-up, but omit
58
+ `status:pending` so completed tasks are included. Keep annotations out of
59
+ discovery output; fetch them only for candidate tasks.
60
+
57
61
  This recipe requires `jq`. If unavailable, use an equivalent local JSON
58
62
  projection rather than installing it automatically.
59
63
 
@@ -83,8 +87,8 @@ Use this procedure for evidence from both the current conversation and a frozen
83
87
 
84
88
  ## Full cross-session review
85
89
 
86
- 1. Begin the review with the requested `remembrancer_review` action. For `seed 14d`, add `seed: "14d"`. Read every returned page with `action: "next"` and the same batch token until no pages remain. Later changes are not part of the batch.
87
- 2. If a selected item needs interpretation, call `action: "context"` with the same batch token and request only the needed context. Context supports interpretation, not new proposal evidence, and does not advance pages.
90
+ 1. Begin the review with the requested `remembrancer_review` action. For `seed 14d`, add `seed: "14d"`. Read every returned page with `action: "next"` and the same batch token until no pages remain. Later changes are not part of the batch. Read evidence and context entries in `groups[].entries` order, retaining their group's source and branch metadata. Join continued text using `offset` and `continues`.
91
+ 2. If a selected item needs interpretation, call `action: "context"` with the same batch token and request only the needed context. For context `selected`, take `sessionId` and `branchId` from the group, and `entryId` and `editId` from the entry. Context supports interpretation, not new proposal evidence, and does not advance pages.
88
92
  3. Follow **Reconcile evidence** above. Report unavailable sources from warnings; they remain unreviewed but do not prevent finishing the available batch as a partial result. Unknown-time warnings are informational and do not by themselves make the review partial.
89
93
  4. After every available page is read, every proposal decided, and every accepted change applied and verified, call `remembrancer_review` with `action: "finish"` and the same batch token. An empty batch can finish. Do not finish while a proposal is undecided. If the user abandons the review, or a failure prevents resolving the available evidence or applying and verifying accepted changes, report it and call `action: "cancel"`. Later changes remain eligible.
90
94