pi-posthorse 0.10.3 → 0.10.4

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.
@@ -6,21 +6,30 @@ import {
6
6
  type ToolCallLike,
7
7
  } from "./contracts.ts";
8
8
  import { textOf, toolCalls } from "./message-text.ts";
9
+ import { bareToolName, noteOperationKind, verifiedNoteOperations } from "./note-tool-effects.ts";
10
+ import { matchNoteDirectory, type NoteOwner } from "./note-scopes.ts";
9
11
 
10
12
  export type ScannedNoteEntry = {
11
13
  readonly entry: EntryLike;
12
14
  readonly entryId: string;
13
15
  readonly inRetained: boolean;
14
16
  };
15
- type NoteOpKind = "full-write" | "partial-write" | "read" | "clear";
16
- export type NoteTarget = { readonly notePath: string; readonly absPath?: string | undefined };
17
+ type NoteOpKind = "full-write" | "partial-write" | "read" | "clear" | "observed-write";
18
+ export type NoteTarget = {
19
+ readonly notePath: string;
20
+ readonly absPath?: string | undefined;
21
+ readonly referenceScope?: string | undefined;
22
+ };
17
23
  export type NoteTouch = NoteTarget & {
18
24
  readonly kind: NoteOpKind;
19
25
  readonly entryId: string;
20
26
  readonly inRetained: boolean;
27
+ readonly receiptId?: string | undefined;
28
+ readonly owner?: NoteOwner | undefined;
21
29
  };
22
30
  type ToolResultInfo = {
23
31
  readonly entryId: string;
32
+ readonly sourceId: string;
24
33
  readonly inRetained: boolean;
25
34
  readonly isError: boolean;
26
35
  readonly toolName: string;
@@ -29,18 +38,11 @@ type ToolResultInfo = {
29
38
  };
30
39
  type TouchContext = {
31
40
  readonly entryId: string;
41
+ readonly sourceId: string;
32
42
  readonly inRetained: boolean;
33
43
  readonly knownDirs: ReadonlySet<string>;
34
44
  };
35
45
 
36
- function bareToolName(name: string | undefined): string {
37
- if (name === undefined || name === "") {
38
- return "";
39
- }
40
- const cut = Math.max(name.lastIndexOf(":"), name.lastIndexOf("/"));
41
- return cut >= 0 ? name.slice(cut + 1) : name;
42
- }
43
-
44
46
  function normalizeRelPath(raw: string): string {
45
47
  const cleaned = raw
46
48
  .trim()
@@ -74,15 +76,14 @@ function matchMarkerPath(slash: string): string | undefined {
74
76
  return /\/\.pi\/(?:agent\/)?notes\/[^/]+\/[^/]+\/[^/]+\/(.+)$/u.exec(slash)?.[1];
75
77
  }
76
78
 
77
- function matchKnownDir(slash: string, knownDirs: ReadonlySet<string>): string | undefined {
78
- for (const dir of knownDirs) {
79
- if (slash.startsWith(`${dir}/`)) {
80
- return slash.slice(dir.length + 1);
81
- }
79
+ function unscopedNoteTarget(trimmed: string, slash: string): NoteTarget | undefined {
80
+ if (slash.startsWith("/") || /^[A-Za-z]:\//u.test(slash)) {
81
+ const base = normalizeRelPath(slash.slice(slash.lastIndexOf("/") + 1));
82
+ return base === "" ? undefined : { notePath: base, absPath: trimmed };
82
83
  }
83
- return undefined;
84
+ const rel = normalizeRelPath(slash);
85
+ return rel === "" ? undefined : { notePath: rel };
84
86
  }
85
-
86
87
  function resolveNoteTarget(
87
88
  rawPath: string | undefined,
88
89
  knownDirs: ReadonlySet<string>,
@@ -93,20 +94,12 @@ function resolveNoteTarget(
93
94
  }
94
95
  const trimmed = rawPath.trim();
95
96
  const slash = trimmed.replaceAll("\\", "/");
96
- const matched = matchKnownDir(slash, knownDirs) ?? matchMarkerPath(slash);
97
+ const matched = matchNoteDirectory(slash, [...knownDirs])?.path ?? matchMarkerPath(slash);
97
98
  if (matched !== undefined) {
98
- const rel = normalizeRelPath(matched);
99
+ const rel = matched.startsWith(".forks/") ? "" : normalizeRelPath(matched);
99
100
  return rel === "" ? undefined : { notePath: rel, absPath: trimmed };
100
101
  }
101
- if (!fromNotesTool) {
102
- return undefined;
103
- }
104
- if (slash.startsWith("/") || /^[A-Za-z]:\//u.test(slash)) {
105
- const base = normalizeRelPath(slash.slice(slash.lastIndexOf("/") + 1));
106
- return base === "" ? undefined : { notePath: base, absPath: trimmed };
107
- }
108
- const rel = normalizeRelPath(slash);
109
- return rel === "" ? undefined : { notePath: rel };
102
+ return fromNotesTool ? unscopedNoteTarget(trimmed, slash) : undefined;
110
103
  }
111
104
 
112
105
  function extractNotesResultTarget(
@@ -141,6 +134,7 @@ function collectResultMap(
141
134
  ) {
142
135
  results.set(callId, {
143
136
  entryId: item.entryId,
137
+ sourceId: item.entry.id ?? item.entryId,
144
138
  inRetained: item.inRetained,
145
139
  isError: msg.isError === true,
146
140
  toolName: bareToolName(msg.toolName),
@@ -205,84 +199,23 @@ function learnNotesDirs(
205
199
  return dirs;
206
200
  }
207
201
 
208
- function pathsFromFileList(value: unknown): string[] {
209
- if (!Array.isArray(value)) {
210
- return [];
211
- }
212
- return value.flatMap((item: unknown) => {
213
- if (typeof item === "string") {
214
- return [item];
215
- }
216
- const itemPath = isRecord(item) ? optionalString(item.path) : undefined;
217
- const skipped =
218
- isRecord(item) && (item.status === "failed" || item.status === "unattempted");
219
- return itemPath !== undefined && !skipped ? [itemPath] : [];
220
- });
221
- }
222
-
223
- function patchPaths(input: unknown): string[] {
224
- return typeof input === "string"
225
- ? Array.from(
226
- input.matchAll(/^\*\*\* (?:Update File|Add File|Move to): ([^\r\n]+)$/gmu),
227
- (m) => m[1] ?? "",
228
- )
229
- : [];
230
- }
231
-
232
- function detailFilePaths(details: unknown): string[] {
233
- return isRecord(details)
234
- ? [...pathsFromFileList(details.modifiedFiles), ...pathsFromFileList(details.files)]
235
- : [];
236
- }
237
-
238
- function extractFileToolSpec(
239
- tool: string,
240
- args: Readonly<Record<string, unknown>>,
241
- details: unknown,
242
- ): { readonly kind: NoteOpKind; readonly rawPaths: readonly string[] } | undefined {
243
- if (args.preview === true) {
244
- return undefined;
245
- }
246
- const directPath = optionalString(args.path);
247
- const directKinds: Readonly<Record<string, NoteOpKind | undefined>> = {
248
- write: args.content === "" ? "clear" : "full-write",
249
- edit: "partial-write",
250
- read: "read",
251
- };
252
- const directKind = directKinds[tool];
253
- if (directKind !== undefined && directPath !== undefined) {
254
- return { kind: directKind, rawPaths: [directPath] };
255
- }
256
- if (tool === "write_files" || tool === "replace_text") {
257
- const kind: NoteOpKind = tool === "write_files" ? "full-write" : "partial-write";
258
- return { kind, rawPaths: [...pathsFromFileList(args.files), ...detailFilePaths(details)] };
259
- }
260
- return tool === "apply_patch"
261
- ? {
262
- kind: "partial-write",
263
- rawPaths: [...patchPaths(args.input), ...detailFilePaths(details)],
264
- }
265
- : undefined;
266
- }
267
-
268
202
  function fileToolTouches(
269
203
  tool: string,
270
204
  args: Readonly<Record<string, unknown>>,
271
- details: unknown,
205
+ result: { readonly details: unknown; readonly isError: boolean },
272
206
  context: TouchContext,
273
207
  ): NoteTouch[] {
274
- const spec = extractFileToolSpec(tool, args, details);
275
- if (spec === undefined) {
276
- return [];
277
- }
278
- return spec.rawPaths.flatMap((raw) => {
279
- const target = resolveNoteTarget(raw, context.knownDirs, false);
208
+ return verifiedNoteOperations(tool, args, result).flatMap((operation) => {
209
+ const target = resolveNoteTarget(operation.path, context.knownDirs, false);
280
210
  return target === undefined
281
211
  ? []
282
212
  : [
283
213
  {
284
214
  ...target,
285
- kind: spec.kind,
215
+ kind:
216
+ tool === "apply_patch" && operation.action !== "delete"
217
+ ? "partial-write"
218
+ : noteOperationKind(operation.action),
286
219
  entryId: context.entryId,
287
220
  inRetained: context.inRetained,
288
221
  },
@@ -317,7 +250,10 @@ function notesToolTouches(
317
250
  ): NoteTouch[] {
318
251
  const parsed = resultText === undefined ? undefined : extractNotesResultTarget(resultText);
319
252
  const kind = notesCallKind(args) ?? parsed?.kind;
320
- const callTarget = resolveNoteTarget(optionalString(args.path), context.knownDirs, true);
253
+ const path = optionalString(args.path);
254
+ const scopedPath =
255
+ typeof args.scope === "string" && path !== undefined ? `${args.scope}/${path}` : path;
256
+ const callTarget = resolveNoteTarget(scopedPath, context.knownDirs, true);
321
257
  const resTarget = resolveNoteTarget(parsed?.rawPath, context.knownDirs, true);
322
258
  const merged = mergeNoteTargets(callTarget, resTarget);
323
259
  return kind === undefined || merged === undefined
@@ -357,15 +293,25 @@ function touchesFromNested(message: MessageLike, context: TouchContext): NoteTou
357
293
  !isRecord(raw) ||
358
294
  raw.isError === true ||
359
295
  raw.status === "error" ||
296
+ raw.status === "unfinished" ||
360
297
  (typeof raw.error === "string" && raw.error !== "")
361
298
  ) {
362
299
  return [];
363
300
  }
364
301
  const name = bareToolName(optionalString(raw.name) ?? optionalString(raw.toolName));
365
302
  const args = nestedArgs(raw);
366
- return name === "notes"
367
- ? notesToolTouches(args, optionalString(raw.result), context)
368
- : fileToolTouches(name, args, raw.result, context);
303
+ const touches =
304
+ name === "notes"
305
+ ? notesToolTouches(args, optionalString(raw.result), context)
306
+ : fileToolTouches(name, args, { details: raw.result, isError: false }, context);
307
+ return touches.map((touch) =>
308
+ Object.assign({}, touch, {
309
+ kind:
310
+ touch.kind === "read" || touch.kind === "clear" ? touch.kind : "observed-write",
311
+ inRetained: false,
312
+ receiptId: context.sourceId,
313
+ }),
314
+ );
369
315
  });
370
316
  }
371
317
 
@@ -377,16 +323,19 @@ function touchesFromAssistantCall(
377
323
  const callId = optionalString(call.id);
378
324
  const res = callId === undefined ? undefined : results.get(callId);
379
325
  const consumedCallId = callId !== undefined && res !== undefined ? callId : undefined;
380
- if (res?.isError === true) {
326
+ if (res === undefined || (res.isError && bareToolName(call.name) === "notes")) {
381
327
  return { consumedCallId, touches: [] };
382
328
  }
383
329
  const tool = bareToolName(call.name);
384
330
  const args = isRecord(call.arguments) ? call.arguments : {};
385
331
  const touches =
386
332
  tool === "notes"
387
- ? notesToolTouches(args, res?.text, context)
388
- : fileToolTouches(tool, args, res?.details, context);
389
- return { consumedCallId, touches };
333
+ ? notesToolTouches(args, res.text, context)
334
+ : fileToolTouches(tool, args, res, context);
335
+ return {
336
+ consumedCallId,
337
+ touches: touches.map((touch) => Object.assign({}, touch, { receiptId: res.sourceId })),
338
+ };
390
339
  }
391
340
 
392
341
  function touchesFromToolResult(
@@ -405,18 +354,22 @@ function touchesFromToolResult(
405
354
  return [...direct, ...touchesFromNested(msg, context)];
406
355
  }
407
356
 
408
- export function collectTouches(entries: readonly ScannedNoteEntry[]): {
357
+ export function collectTouches(
358
+ entries: readonly ScannedNoteEntry[],
359
+ directories: ReadonlySet<string> = new Set(),
360
+ ): {
409
361
  readonly touches: readonly NoteTouch[];
410
362
  readonly defaultDir?: string | undefined;
411
363
  } {
412
364
  const results = collectResultMap(entries);
413
- const knownDirs = learnNotesDirs(entries, results);
365
+ const knownDirs = new Set([...directories, ...learnNotesDirs(entries, results)]);
414
366
  const handledResultIds = new Set<string>();
415
367
  const touches: NoteTouch[] = [];
416
368
  for (const item of entries) {
417
369
  const msg = item.entry.message;
418
370
  const context: TouchContext = {
419
371
  entryId: item.entryId,
372
+ sourceId: item.entry.id ?? item.entryId,
420
373
  inRetained: item.inRetained,
421
374
  knownDirs,
422
375
  };
@@ -1,11 +1,6 @@
1
1
  import type { EntryLike, ProjectedEntry } from "./contracts.ts";
2
- import { contextEdits } from "./history-entries.ts";
3
- import {
4
- collectTouches,
5
- type ScannedNoteEntry,
6
- type NoteTarget,
7
- type NoteTouch,
8
- } from "./recovery-note-touches.ts";
2
+ import { sessionNoteTouches, scopeRecoveryTouches, type NotesRecovery } from "./note-evidence.ts";
3
+ import type { NoteTarget, NoteTouch } from "./recovery-note-touches.ts";
9
4
 
10
5
  const MAX_WRITTEN_NOTES = 4;
11
6
  const MAX_READ_NOTES = 3;
@@ -13,6 +8,7 @@ const MAX_READ_NOTES = 3;
13
8
  export type RetainedSpan = { readonly firstId: string; readonly lastId: string };
14
9
  type TrackedNote = NoteTarget & {
15
10
  readonly written: boolean;
11
+ readonly metadataOnly: boolean;
16
12
  readonly lastEntryId: string;
17
13
  readonly lastInRetained: boolean;
18
14
  readonly lastWriteEntryId?: string | undefined;
@@ -27,14 +23,14 @@ function applyReadTouch(
27
23
  ): TrackedNote {
28
24
  const wasWritten = previous?.written === true;
29
25
  return {
26
+ ...previous,
30
27
  notePath: touch.notePath,
31
28
  absPath: touch.absPath ?? previous?.absPath,
32
29
  written: wasWritten,
30
+ metadataOnly: previous?.metadataOnly ?? false,
31
+ referenceScope: touch.referenceScope ?? previous?.referenceScope,
33
32
  lastEntryId: touch.entryId,
34
33
  lastInRetained: touch.inRetained,
35
- lastWriteEntryId: previous?.lastWriteEntryId,
36
- fullWriteRetainedEntryId: previous?.fullWriteRetainedEntryId,
37
- partialEditRetainedEntryId: previous?.partialEditRetainedEntryId,
38
34
  order: wasWritten ? previous.order : order,
39
35
  };
40
36
  }
@@ -44,17 +40,19 @@ function applyWriteTouch(
44
40
  touch: NoteTouch,
45
41
  order: number,
46
42
  ): TrackedNote {
43
+ const previousFull =
44
+ touch.kind === "observed-write" ? undefined : previous?.fullWriteRetainedEntryId;
47
45
  return {
48
46
  notePath: touch.notePath,
49
47
  absPath: touch.absPath ?? previous?.absPath,
50
48
  written: true,
49
+ metadataOnly: touch.kind === "observed-write",
50
+ referenceScope: touch.referenceScope,
51
51
  lastEntryId: touch.entryId,
52
52
  lastInRetained: touch.inRetained,
53
53
  lastWriteEntryId: touch.entryId,
54
54
  fullWriteRetainedEntryId:
55
- touch.kind === "full-write" && touch.inRetained
56
- ? touch.entryId
57
- : previous?.fullWriteRetainedEntryId,
55
+ touch.kind === "full-write" && touch.inRetained ? touch.entryId : previousFull,
58
56
  partialEditRetainedEntryId:
59
57
  touch.kind === "partial-write" && touch.inRetained
60
58
  ? touch.entryId
@@ -64,6 +62,9 @@ function applyWriteTouch(
64
62
  }
65
63
 
66
64
  function formatNoteLabel(note: TrackedNote): string {
65
+ if (note.referenceScope !== undefined) {
66
+ return `${note.notePath} (read-only reference; notes read ${JSON.stringify({ scope: note.referenceScope, path: note.notePath })})`;
67
+ }
67
68
  return note.absPath !== undefined && note.absPath !== note.notePath
68
69
  ? `${note.notePath} (${note.absPath})`
69
70
  : note.notePath;
@@ -72,6 +73,9 @@ function formatNoteLabel(note: TrackedNote): string {
72
73
  function formatWrittenNoteLine(note: TrackedNote, span: RetainedSpan | undefined): string {
73
74
  const label = formatNoteLabel(note);
74
75
  const writeId = note.lastWriteEntryId ?? note.lastEntryId;
76
+ if (note.metadataOnly) {
77
+ return `- Active note (written): ${label} [verified effect at entry ${writeId}; full content is not retained — read this note now]`;
78
+ }
75
79
  if (span === undefined) {
76
80
  return `- Active note (written): ${label} [compacted at entry ${writeId} — read this note now]`;
77
81
  }
@@ -112,56 +116,10 @@ function formatNotesAction(
112
116
  return `Read ${primaryWritten.notePath} (notes read or read on its path) before continuing to restore the saved goal, progress, decisions, and next steps, then keep that note current as work progresses.`;
113
117
  }
114
118
 
115
- function projectNoteEntries(
116
- chainEntries: readonly EntryLike[],
117
- allEntries: readonly EntryLike[],
118
- projected: readonly ProjectedEntry[],
119
- retained: ReadonlySet<string>,
120
- ): ScannedNoteEntry[] {
121
- const edits = contextEdits(allEntries);
122
- const omittedIds = new Set(
123
- projected
124
- .filter(({ messages }) => messages.length === 0)
125
- .map(({ sourceEntry }) => sourceEntry.id),
126
- );
127
- return chainEntries.flatMap((entry) => {
128
- const rawId = entry.id ?? "";
129
- const edit = edits.get(rawId);
130
- if (omittedIds.has(rawId) || edit?.replacement === null) {
131
- return [];
132
- }
133
- const effective =
134
- edit?.replacement !== undefined && entry.type === "message"
135
- ? {
136
- ...entry,
137
- id: edit.id,
138
- message: { ...entry.message, content: edit.replacement.content },
139
- }
140
- : entry;
141
- const resolvedId = (effective.id ?? rawId).slice(0, 120);
142
- return [
143
- {
144
- entry: effective,
145
- entryId: resolvedId === "" ? "unknown" : resolvedId,
146
- inRetained: retained.has(rawId),
147
- },
148
- ];
149
- });
150
- }
151
-
152
- export function renderSessionNotes(
153
- chainEntries: readonly EntryLike[],
154
- allEntries: readonly EntryLike[],
155
- projected: readonly ProjectedEntry[],
156
- options: {
157
- readonly retained: ReadonlySet<string>;
158
- readonly span: RetainedSpan | undefined;
159
- readonly maxChars: number;
160
- },
161
- ): string | undefined {
162
- const { retained, span, maxChars } = options;
163
- const entries = projectNoteEntries(chainEntries, allEntries, projected, retained);
164
- const { touches, defaultDir } = collectTouches(entries);
119
+ function trackedNotes(
120
+ touches: readonly NoteTouch[],
121
+ defaultDir: string | undefined,
122
+ ): TrackedNote[] {
165
123
  const tracked = new Map<string, TrackedNote>();
166
124
  let order = 0;
167
125
  for (const rawTouch of touches) {
@@ -170,18 +128,41 @@ export function renderSessionNotes(
170
128
  rawTouch.absPath === undefined && defaultDir !== undefined
171
129
  ? { ...rawTouch, absPath: `${defaultDir}/${rawTouch.notePath}` }
172
130
  : rawTouch;
131
+ const key = `${touch.referenceScope ?? touch.absPath ?? ""}\0${touch.notePath}`;
173
132
  if (touch.kind === "clear") {
174
- tracked.delete(touch.notePath);
133
+ tracked.delete(key);
175
134
  } else if (touch.kind === "read") {
176
- tracked.set(touch.notePath, applyReadTouch(tracked.get(touch.notePath), touch, order));
135
+ tracked.set(key, applyReadTouch(tracked.get(key), touch, order));
177
136
  } else {
178
- tracked.set(touch.notePath, applyWriteTouch(tracked.get(touch.notePath), touch, order));
137
+ tracked.set(key, applyWriteTouch(tracked.get(key), touch, order));
179
138
  }
180
139
  }
181
- if (tracked.size === 0) {
182
- return undefined;
140
+ return [...tracked.values()].sort((a, b) => b.order - a.order);
141
+ }
142
+ export function renderSessionNotes(
143
+ chainEntries: readonly EntryLike[],
144
+ allEntries: readonly EntryLike[],
145
+ projected: readonly ProjectedEntry[],
146
+ options: {
147
+ readonly retained: ReadonlySet<string>;
148
+ readonly span: RetainedSpan | undefined;
149
+ readonly maxChars: number;
150
+ readonly notes?: NotesRecovery | undefined;
151
+ },
152
+ ): string | undefined {
153
+ const { retained, span, maxChars } = options;
154
+ const collected = sessionNoteTouches({
155
+ branch: chainEntries,
156
+ allEntries: options.notes?.entries ?? allEntries,
157
+ projected,
158
+ retained,
159
+ });
160
+ const touches = scopeRecoveryTouches(collected.touches, options.notes);
161
+ const { defaultDir } = collected;
162
+ const all = trackedNotes(touches, defaultDir);
163
+ if (all.length === 0) {
164
+ return;
183
165
  }
184
- const all = [...tracked.values()].sort((a, b) => b.order - a.order);
185
166
  const written = all.filter((note) => note.written).slice(0, MAX_WRITTEN_NOTES);
186
167
  const readOnly = all.filter((note) => !note.written).slice(0, MAX_READ_NOTES);
187
168
  const lines = [
package/src/recovery.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  recoveryRecord,
8
8
  type RecoveryRecord,
9
9
  } from "./recovery-records.ts";
10
+ import type { NotesRecovery } from "./note-evidence.ts";
10
11
  import { renderSessionNotes, type RetainedSpan } from "./recovery-notes.ts";
11
12
  import {
12
13
  recoverableToolResults,
@@ -380,6 +381,7 @@ function rolloverPreambleWithNotes(
380
381
  options: {
381
382
  readonly retained: ReadonlySet<string>;
382
383
  readonly reserveParts: readonly (string | undefined)[];
384
+ readonly notes?: NotesRecovery | undefined;
383
385
  readonly maxChars: number;
384
386
  },
385
387
  ): string {
@@ -394,6 +396,7 @@ function rolloverPreambleWithNotes(
394
396
  {
395
397
  retained,
396
398
  span,
399
+ notes: options.notes,
397
400
  maxChars: Math.min(
398
401
  MAX_NOTES_SECTION_CHARS,
399
402
  Math.max(0, maxChars - reserveLen - HANDOFF_OVERHEAD_RESERVE),
@@ -410,6 +413,7 @@ export function buildAutoHandoff(
410
413
  options: {
411
414
  readonly ownerQuestionRegistered: boolean;
412
415
  readonly retainedEntryIds?: ReadonlySet<string>;
416
+ readonly notes?: NotesRecovery | undefined;
413
417
  },
414
418
  ): string {
415
419
  const { ownerQuestionRegistered, retainedEntryIds: retained = new Set<string>() } = options;
@@ -441,6 +445,7 @@ export function buildAutoHandoff(
441
445
  retained,
442
446
  reserveParts,
443
447
  maxChars,
448
+ notes: options.notes,
444
449
  });
445
450
  const minimum = [preamble, ...reserveParts];
446
451
  const plan = planBatch(
package/src/retention.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  type MessageLike,
15
15
  type PolicyContext,
16
16
  } from "./contracts.ts";
17
+ import type { NotesRecovery } from "./note-evidence.ts";
17
18
  import { buildAutoHandoff } from "./recovery.ts";
18
19
 
19
20
  type RecoveryCapacity = {
@@ -21,6 +22,7 @@ type RecoveryCapacity = {
21
22
  readonly toolTokens: number;
22
23
  readonly pendingMessages?: readonly MessageLike[];
23
24
  readonly firstKeptEntryId?: string | undefined;
25
+ readonly notes?: NotesRecovery | undefined;
24
26
  };
25
27
  type RetainedTail = {
26
28
  readonly firstKeptEntryId?: string | undefined;
@@ -199,6 +201,7 @@ export function automaticRecovery(
199
201
  const handoff = buildAutoHandoff(entries, projected, limit, {
200
202
  ownerQuestionRegistered,
201
203
  retainedEntryIds: retained.ids,
204
+ notes: capacity.notes,
202
205
  });
203
206
  return handoff.length > limit
204
207
  ? undefined
package/src/rollover.ts CHANGED
@@ -20,6 +20,11 @@ import { registerGuidance } from "./guidance.ts";
20
20
  import { safeJsonStringify } from "./message-text.ts";
21
21
  import { hasRetainedRolloverMarker } from "./recovery.ts";
22
22
  import { automaticRecovery } from "./retention.ts";
23
+ import type { NotesRecovery } from "./note-evidence.ts";
24
+ type RolloverResources = {
25
+ readonly resetPages: () => void;
26
+ readonly notes: (ctx: ExtensionContext) => NotesRecovery | undefined;
27
+ };
23
28
  import {
24
29
  countRetainedMessages,
25
30
  createReminderLookup,
@@ -313,7 +318,11 @@ function thresholdFallback(
313
318
  pi: ExtensionAPI,
314
319
  event: TurnEndEvent,
315
320
  ctx: ExtensionContext,
316
- capacity: { readonly host: PolicyContext; readonly toolTokens: () => number },
321
+ capacity: {
322
+ readonly host: PolicyContext;
323
+ readonly toolTokens: () => number;
324
+ readonly notes: RolloverResources["notes"];
325
+ },
317
326
  ): BoundaryResult | undefined {
318
327
  if (!fallbackTurnEligible(event, ctx)) {
319
328
  return undefined;
@@ -332,7 +341,12 @@ function thresholdFallback(
332
341
  const recovery = automaticRecovery(
333
342
  ctx.sessionManager.getBranch(),
334
343
  projected,
335
- { host, toolTokens: toolTokens(), pendingMessages: event.context.pendingMessages },
344
+ {
345
+ host,
346
+ toolTokens: toolTokens(),
347
+ pendingMessages: event.context.pendingMessages,
348
+ notes: capacity.notes(ctx),
349
+ },
336
350
  ownerQuestionRegistered,
337
351
  );
338
352
  if (recovery === undefined) {
@@ -357,6 +371,7 @@ function registerAutomaticRollover(
357
371
  pi: ExtensionAPI,
358
372
  policy: SnapshotReader,
359
373
  activeToolTokens: () => number,
374
+ notes: RolloverResources["notes"],
360
375
  ): void {
361
376
  pi.on("session_before_compact", (event, ctx) => {
362
377
  if (event.reason === "manual") {
@@ -381,6 +396,7 @@ function registerAutomaticRollover(
381
396
  host,
382
397
  toolTokens: activeToolTokens(),
383
398
  firstKeptEntryId: event.preparation.firstKeptEntryId,
399
+ notes: notes(ctx),
384
400
  },
385
401
  ownerQuestionRegistered,
386
402
  );
@@ -411,13 +427,13 @@ export function registerRollover(
411
427
  pi: ExtensionAPI,
412
428
  policy: SnapshotReader,
413
429
  activeToolTokens: () => number,
414
- resetPages: () => void,
430
+ resources: RolloverResources,
415
431
  ): void {
416
432
  const resetRequests = new Map<string, string>();
417
433
  const reminders = createReminderLookup();
418
434
  const resetTurn = () => {
419
435
  resetRequests.clear();
420
- resetPages();
436
+ resources.resetPages();
421
437
  };
422
438
  pi.on("turn_start", resetTurn);
423
439
  pi.on("session_start", () => {
@@ -429,7 +445,7 @@ export function registerRollover(
429
445
  });
430
446
  registerGuidance(pi, policy);
431
447
  registerReminderFilter(pi, policy, reminders);
432
- registerAutomaticRollover(pi, policy, activeToolTokens);
448
+ registerAutomaticRollover(pi, policy, activeToolTokens, resources.notes);
433
449
  pi.on("turn_end", (event, ctx) => {
434
450
  const requested = event.toolResults.find(
435
451
  (result) => result.toolName === "new_context" && resetRequests.has(result.toolCallId),
@@ -452,6 +468,7 @@ export function registerRollover(
452
468
  const fallback = thresholdFallback(pi, event, ctx, {
453
469
  host,
454
470
  toolTokens: activeToolTokens,
471
+ notes: resources.notes,
455
472
  });
456
473
  if (fallback !== undefined) {
457
474
  return fallback;
@@ -177,13 +177,15 @@ function messageFrom(value: unknown): MessageLike | undefined {
177
177
  toolName: optionalString(value.toolName),
178
178
  namespace: optionalString(value.namespace),
179
179
  toolCallId: optionalString(value.toolCallId),
180
+ details: value.details,
181
+ nestedCalls: value.nestedCalls,
180
182
  isError: value.isError === true,
181
183
  command: optionalString(value.command),
182
184
  output: optionalString(value.output),
183
185
  excludeFromContext: value.excludeFromContext === true,
184
186
  };
185
187
  }
186
- function parsedEntry(line: string): EntryLike | undefined {
188
+ export function parseSessionLine(line: string): EntryLike | undefined {
187
189
  try {
188
190
  const value: unknown = JSON.parse(line);
189
191
  if (!isRecord(value)) {
@@ -202,6 +204,9 @@ function parsedEntry(line: string): EntryLike | undefined {
202
204
  customType: optionalString(value.customType),
203
205
  content: value.content,
204
206
  details: value.details,
207
+ data: value.data,
208
+ cwd: optionalString(value.cwd),
209
+ parentSession: optionalString(value.parentSession),
205
210
  display: value.display === true,
206
211
  handoff: optionalString(value.handoff),
207
212
  firstKeptEntryId: optionalString(value.firstKeptEntryId),
@@ -234,7 +239,7 @@ async function readEntry(
234
239
  if (head !== undefined && (!line.matches || !wanted(head))) {
235
240
  return { entry: head, selected: false };
236
241
  }
237
- const entry = parsedEntry(await line.text());
242
+ const entry = parseSessionLine(await line.text());
238
243
  return entry === undefined
239
244
  ? undefined
240
245
  : {