pi-posthorse 0.10.26 → 0.10.28

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-posthorse",
3
- "version": "0.10.26",
3
+ "version": "0.10.28",
4
4
  "type": "module",
5
5
  "description": "Posthorse: fresh context, same journey. No-summary context rollover for Pi, with sparse budget reminders, handoffs, notes, and history.",
6
6
  "keywords": [
@@ -21,7 +21,7 @@
21
21
  "src"
22
22
  ],
23
23
  "engines": {
24
- "node": ">=24.12.0"
24
+ "node": "^24.22.3 || >=26.13.1"
25
25
  },
26
26
  "packageManager": "npm@12.2.0",
27
27
  "pi": {
package/src/guidance.ts CHANGED
@@ -52,6 +52,7 @@ export function activeGuidanceTools(pi: ToolRegistry): GuidanceTools {
52
52
  getContextRemaining: activeUnnamespaced.has("get_context_remaining"),
53
53
  };
54
54
  }
55
+ /** Replay oldest first: the last text per budget wins, while the first record fixes epoch tools. */
55
56
  function collectGuidanceEntries(
56
57
  entries: readonly EntryLike[],
57
58
  baseByBudget?: ReadonlyMap<string, string>,
@@ -20,6 +20,7 @@ import {
20
20
  toolIdentity,
21
21
  } from "./message-text.ts";
22
22
 
23
+ /** Native journal order is oldest first; the last edit of a target wins, regardless of timestamp. */
23
24
  export function contextEdits(entries: readonly EntryLike[]): Map<string, EntryLike> {
24
25
  return new Map(
25
26
  entries.flatMap((entry) =>
@@ -186,7 +187,10 @@ export function toWindowedEntry(
186
187
  images: imagesOf(entryContent(entry)),
187
188
  };
188
189
  }
189
- /** Window ancestry is metadata-only; extracting text/images is a separate operation. */
190
+ /**
191
+ * Feed parents before children, including entries that do not match a search. Labels follow
192
+ * ancestry, not timestamps. A fresh projection belongs to one forward journal traversal.
193
+ */
190
194
  export function windowProjection(): (entry: EntryLike) => string {
191
195
  const windows = new Map<string, string>();
192
196
  return (entry) => {
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  MIN_PAGE_CHARS,
3
3
  ESTIMATED_IMAGE_CHARS,
4
+ textResult,
4
5
  type HistoryHit,
5
6
  type PolicyContext,
6
7
  type TextResult,
@@ -80,34 +81,35 @@ export function searchPage(
80
81
  host: PolicyContext,
81
82
  pages: PageAccess,
82
83
  ): TextResult {
83
- const chars = pages.size(host);
84
- const reserve = Math.max(
85
- 0,
86
- ...matches.hits.map(
87
- (hit) => searchFooter(cursorAt(matches.key, hit, hit.text.length)).length,
88
- ),
89
- );
90
- if (reserve >= chars) {
91
- pages.error(host, "History entry id is too large for pagination.");
92
- }
93
- const skippedNote =
94
- matches.skipped > 0 && (params.cursor === undefined || params.cursor === "")
95
- ? `\n[Skipped ${matches.skipped} match${matches.skipped === 1 ? "" : "es"} already in your active context.]`
96
- : "";
97
- const page = searchParts(matches, chars - reserve - skippedNote.length);
98
- const body =
99
- page.parts.length > 0
100
- ? page.parts.join("\n")
101
- : `No history matches "${excerpt(params.query ?? "", 200)}".`;
102
- const tail =
103
- skippedNote +
104
- (page.continuation.kind === "more" ? searchFooter(page.continuation.next) : "");
105
- return pages.result(body + tail, [], {
106
- kind: "history-search",
107
- entries: [...page.spans],
108
- footerLength: tail.length,
109
- more: page.continuation.kind === "more",
110
- skipped: matches.skipped,
84
+ return pages.deliver(host, {}, (chars) => {
85
+ const reserve = Math.max(
86
+ 0,
87
+ ...matches.hits.map(
88
+ (hit) => searchFooter(cursorAt(matches.key, hit, hit.text.length)).length,
89
+ ),
90
+ );
91
+ if (reserve >= chars) {
92
+ pages.error(host, "History entry id is too large for pagination.");
93
+ }
94
+ const skippedNote =
95
+ matches.skipped > 0 && (params.cursor === undefined || params.cursor === "")
96
+ ? `\n[Skipped ${matches.skipped} match${matches.skipped === 1 ? "" : "es"} already in your active context.]`
97
+ : "";
98
+ const page = searchParts(matches, chars - reserve - skippedNote.length);
99
+ const body =
100
+ page.parts.length > 0
101
+ ? page.parts.join("\n")
102
+ : `No history matches "${excerpt(params.query ?? "", 200)}".`;
103
+ const tail =
104
+ skippedNote +
105
+ (page.continuation.kind === "more" ? searchFooter(page.continuation.next) : "");
106
+ return textResult(body + tail, [], {
107
+ kind: "history-search",
108
+ entries: [...page.spans],
109
+ footerLength: tail.length,
110
+ more: page.continuation.kind === "more",
111
+ skipped: matches.skipped,
112
+ });
111
113
  });
112
114
  }
113
115
  function readOffsets(
@@ -144,33 +146,37 @@ export function historyReadPage(
144
146
  const shownId = shownEntryId(item, params.id, source);
145
147
  const { offset, imageOffset } = readOffsets(item, params);
146
148
  const firstImage = imageOffset < item.images.length ? 1 : 0;
147
- const chars = access.pages.size(access.host, { imageCount: firstImage });
148
- const imageEnd = Math.min(
149
- item.images.length,
150
- imageOffset + firstImage + Math.floor((chars - MIN_PAGE_CHARS) / ESTIMATED_IMAGE_CHARS),
151
- );
152
- const images = item.images.slice(imageOffset, imageEnd);
153
- const end = Math.min(
154
- item.text.length,
155
- offset + chars - (images.length - firstImage) * ESTIMATED_IMAGE_CHARS,
156
- );
157
- const continuation: Continuation<{ readonly offset: number; readonly imageOffset: number }> =
158
- end < item.text.length || imageEnd < item.images.length
159
- ? { kind: "more", next: { offset: end, imageOffset: imageEnd } }
160
- : { kind: "complete" };
161
- const more =
162
- continuation.kind === "more"
163
- ? `\nMore remains; call history read with id "${shownId}" and offset ${continuation.next.offset}${item.images.length > 0 ? ` and imageOffset ${continuation.next.imageOffset}` : ""}.`
164
- : "";
165
- const header = `${item.entry.timestamp ?? ""}${sourceTag(source)} [window ${item.windowId}] [${shownId}] [chars ${offset}-${end} of ${item.text.length}] `;
166
- return access.pages.result(`${header}${item.text.slice(offset, end)}${more}`, images, {
167
- kind: "history-read",
168
- headerLength: header.length,
169
- offset,
170
- end,
171
- total: item.text.length,
172
- imageOffset,
173
- imageEnd,
174
- imageTotal: item.images.length,
149
+ return access.pages.deliver(access.host, { imageCount: firstImage }, (chars) => {
150
+ const imageEnd = Math.min(
151
+ item.images.length,
152
+ imageOffset + firstImage + Math.floor((chars - MIN_PAGE_CHARS) / ESTIMATED_IMAGE_CHARS),
153
+ );
154
+ const images = item.images.slice(imageOffset, imageEnd);
155
+ const end = Math.min(
156
+ item.text.length,
157
+ offset + chars - (images.length - firstImage) * ESTIMATED_IMAGE_CHARS,
158
+ );
159
+ const continuation: Continuation<{
160
+ readonly offset: number;
161
+ readonly imageOffset: number;
162
+ }> =
163
+ end < item.text.length || imageEnd < item.images.length
164
+ ? { kind: "more", next: { offset: end, imageOffset: imageEnd } }
165
+ : { kind: "complete" };
166
+ const more =
167
+ continuation.kind === "more"
168
+ ? `\nMore remains; call history read with id "${shownId}" and offset ${continuation.next.offset}${item.images.length > 0 ? ` and imageOffset ${continuation.next.imageOffset}` : ""}.`
169
+ : "";
170
+ const header = `${item.entry.timestamp ?? ""}${sourceTag(source)} [window ${item.windowId}] [${shownId}] [chars ${offset}-${end} of ${item.text.length}] `;
171
+ return textResult(`${header}${item.text.slice(offset, end)}${more}`, images, {
172
+ kind: "history-read",
173
+ headerLength: header.length,
174
+ offset,
175
+ end,
176
+ total: item.text.length,
177
+ imageOffset,
178
+ imageEnd,
179
+ imageTotal: item.images.length,
180
+ });
175
181
  });
176
182
  }
@@ -31,6 +31,7 @@ export type HistorySource = {
31
31
  readonly dir: string;
32
32
  readonly cwd: string;
33
33
  readonly currentFile?: string | undefined;
34
+ /** Pi's parent-before-child branch order, not message timestamp order. */
34
35
  readonly branch: () => readonly EntryLike[];
35
36
  readonly projection: () => readonly ProjectedEntry[];
36
37
  };
@@ -55,12 +55,14 @@ async function projectScopes(
55
55
  throw error;
56
56
  });
57
57
  const candidates = entries.filter((entry) => !entry.name.startsWith(".staging-"));
58
- const manifests = await mapBatch(candidates, async (entry) =>
59
- entry.isDirectory() ? readManifest(join(directory, entry.name, "notes")) : undefined,
60
- );
61
- for (const [index, entry] of candidates.entries()) {
58
+ const manifests = await mapBatch(candidates, async (entry) => ({
59
+ entry,
60
+ manifest: entry.isDirectory()
61
+ ? await readManifest(join(directory, entry.name, "notes"))
62
+ : undefined,
63
+ }));
64
+ for (const { entry, manifest } of manifests) {
62
65
  const path = join(directory, entry.name);
63
- const manifest = manifests[index];
64
66
  if (manifest === undefined || manifest.root !== session.binding.root) {
65
67
  notice(`Not indexed: unmanaged or incomplete notes data at ${path}.`);
66
68
  } else {
@@ -1,7 +1,12 @@
1
1
  import { join } from "node:path";
2
2
  import { isRecord, optionalString, type EntryLike, type ProjectedEntry } from "./contracts.ts";
3
3
  import { contextEdits } from "./history-entries.ts";
4
- import { collectTouches, type NoteTouch, type ScannedNoteEntry } from "./recovery-note-touches.ts";
4
+ import {
5
+ collectTouches,
6
+ noteTargetKey,
7
+ type NoteTouch,
8
+ type ScannedNoteEntry,
9
+ } from "./recovery-note-touches.ts";
5
10
  import {
6
11
  addressOf,
7
12
  bindingsOf,
@@ -20,7 +25,9 @@ export type NotesRecovery = {
20
25
  };
21
26
 
22
27
  export type NoteEvidence = {
28
+ /** Active branch in native journal order; later edits and receipts supersede earlier ones. */
23
29
  readonly branch: readonly EntryLike[];
30
+ /** Keep each source journal's effect order when combining durable provenance. */
24
31
  readonly allEntries: readonly EntryLike[];
25
32
  readonly projected: readonly ProjectedEntry[];
26
33
  readonly retained: ReadonlySet<string>;
@@ -74,15 +81,12 @@ function recordedTouches(
74
81
  ): NoteTouch[] {
75
82
  const receipts = effectReceipts(evidence.branch);
76
83
  const shown = new Map(visible.map((item) => [item.entry.id, item]));
77
- const seen = new Set<string>();
78
- return touchRecords(evidence.allEntries).flatMap((record) => {
84
+ const touches = touchRecords(evidence.allEntries).flatMap((record) => {
79
85
  const receipt = receipts.get(record.rootToolCallId);
80
86
  const item = shown.get(receipt?.id);
81
- const key = `${record.owner.id}\0${record.owner.timestamp}\0${record.toolCallId}`;
82
- if (item === undefined || seen.has(key)) {
87
+ if (item === undefined) {
83
88
  return [];
84
89
  }
85
- seen.add(key);
86
90
  return record.files.map((file): NoteTouch => {
87
91
  let kind: NoteTouch["kind"] = "observed-write";
88
92
  if (file.kind === "read") {
@@ -96,14 +100,39 @@ function recordedTouches(
96
100
  kind,
97
101
  entryId: item.entryId,
98
102
  receiptId: item.entry.id ?? item.entryId,
103
+ toolCallId: record.toolCallId,
99
104
  inRetained: false,
100
105
  owner: record.owner,
101
106
  };
102
107
  });
103
108
  });
109
+ const latest = new Map<string, NoteTouch>();
110
+ for (const touch of touches) {
111
+ const key = JSON.stringify([touch.owner?.id, touch.owner?.timestamp, touchKey(touch)]);
112
+ // Adoption and completion can record the same file in one call. Keep its final effect
113
+ // at its final position without discarding other files adopted by that call.
114
+ latest.delete(key);
115
+ latest.set(key, touch);
116
+ }
117
+ return [...latest.values()];
104
118
  }
105
119
  function touchKey(touch: NoteTouch): string {
106
- return JSON.stringify([touch.receiptId ?? touch.entryId, touch.absPath ?? touch.notePath]);
120
+ return JSON.stringify([
121
+ touch.receiptId ?? touch.entryId,
122
+ touch.toolCallId,
123
+ noteTargetKey(touch),
124
+ ]);
125
+ }
126
+ function reconcileTouch(recorded: NoteTouch, inferred: NoteTouch | undefined): NoteTouch {
127
+ if (
128
+ inferred !== undefined &&
129
+ ((recorded.kind === "read" && inferred.kind === "read") ||
130
+ (recorded.kind === "observed-write" &&
131
+ (inferred.kind === "full-write" || inferred.kind === "partial-write")))
132
+ ) {
133
+ return { ...inferred, owner: recorded.owner };
134
+ }
135
+ return recorded;
107
136
  }
108
137
  export function sessionNoteTouches(evidence: NoteEvidence): {
109
138
  readonly touches: readonly NoteTouch[];
@@ -117,14 +146,12 @@ export function sessionNoteTouches(evidence: NoteEvidence): {
117
146
  ]);
118
147
  const legacy = collectTouches(visible, directories);
119
148
  const recorded = recordedTouches(evidence, visible);
120
- const recordedByReceipt = new Map(recorded.map((touch) => [touchKey(touch), touch]));
121
- const covered = new Set<string>();
122
- const identified = legacy.touches.map((touch) => {
123
- const key = touchKey(touch);
124
- covered.add(key);
125
- return { ...touch, owner: recordedByReceipt.get(key)?.owner };
126
- });
127
- const touches = [...identified, ...recorded.filter((touch) => !covered.has(touchKey(touch)))];
149
+ const inferredByCall = new Map(legacy.touches.map((touch) => [touchKey(touch), touch]));
150
+ const covered = new Set(recorded.map(touchKey));
151
+ const touches = [
152
+ ...legacy.touches.filter((touch) => !covered.has(touchKey(touch))),
153
+ ...recorded.map((touch) => reconcileTouch(touch, inferredByCall.get(touchKey(touch)))),
154
+ ];
128
155
  const order = new Map(visible.map((entry, index) => [entry.entry.id ?? entry.entryId, index]));
129
156
  touches.sort(
130
157
  (a, b) =>
@@ -89,12 +89,15 @@ async function recordedFiles(
89
89
  captured: CapturedCall,
90
90
  ): Promise<NoteTouchRecord["files"]> {
91
91
  const files: NoteTouchRecord["files"][number][] = [];
92
- const addresses = await mapBatch(operations, (operation) =>
93
- noteAddress(toolPath(captured.tool, operation.path, captured.cwd), captured.session),
94
- );
95
- for (const [index, operation] of operations.entries()) {
92
+ const addressed = await mapBatch(operations, async (operation) => ({
93
+ operation,
94
+ address: await noteAddress(
95
+ toolPath(captured.tool, operation.path, captured.cwd),
96
+ captured.session,
97
+ ),
98
+ }));
99
+ for (const { operation, address } of addressed) {
96
100
  // Each result belongs to the scope captured before execution, even after /tree.
97
- const address = addresses[index];
98
101
  if (address === undefined) {
99
102
  continue;
100
103
  }
@@ -37,15 +37,18 @@ async function* folderEntries(directory: string, signal: AbortSignal | undefined
37
37
  const firstFolder = batch.findIndex(
38
38
  (entry) => entry.isDirectory() || entry.isSymbolicLink(),
39
39
  );
40
- const paths = batch
41
- .slice(0, firstFolder === -1 ? batch.length : firstFolder + 1)
42
- .map((entry) => join(directory, entry.name));
43
- const infos = await Promise.all(paths.map(statIfPresent));
44
- for (const [index, path] of paths.entries()) {
40
+ const listed = await Promise.all(
41
+ batch
42
+ .slice(0, firstFolder === -1 ? batch.length : firstFolder + 1)
43
+ .map(async (entry) => {
44
+ const path = join(directory, entry.name);
45
+ return { path, info: await statIfPresent(path), alias: entry.isSymbolicLink() };
46
+ }),
47
+ );
48
+ for (const { path, info, alias } of listed) {
45
49
  start += 1;
46
- const info = infos[index];
47
50
  if (info !== undefined) {
48
- yield { path, info, alias: batch[index]?.isSymbolicLink() === true };
51
+ yield { path, info, alias };
49
52
  }
50
53
  if (info?.isDirectory() === true) {
51
54
  break;
@@ -235,13 +235,13 @@ async function forkBinding(
235
235
  const entries = [...manager.getEntries(), ...source.entries];
236
236
  const files: SnapshotNote[] = [];
237
237
  const absent: string[] = [];
238
- const addresses = await mapBatch(candidates, (candidate) =>
239
- resolveReference(scope ?? candidate.source, candidate.path, entries),
240
- );
241
- for (const [index, candidate] of candidates.entries()) {
238
+ const addressed = await mapBatch(candidates, async (candidate) => ({
239
+ candidate,
240
+ address: await resolveReference(scope ?? candidate.source, candidate.path, entries),
241
+ }));
242
+ for (const { candidate, address } of addressed) {
242
243
  // Resolve against the immediate parent's files, not a historical ancestor's version.
243
244
  // A missing source note is not copied; a known source scope still resolves it later.
244
- const address = addresses[index];
245
245
  if (address !== undefined) {
246
246
  files.push({
247
247
  path: candidate.path,
@@ -218,6 +218,7 @@ export function parseBinding(value: unknown): NoteBinding | undefined {
218
218
  }
219
219
  return value;
220
220
  }
221
+ /** Preserve the caller's journal precedence; consumers select the last matching binding. */
221
222
  export function bindingsOf(entries: readonly EntryLike[]): NoteBinding[] {
222
223
  return entries.flatMap((entry) => {
223
224
  const binding =
@@ -239,18 +240,25 @@ export function touchRecords(entries: readonly EntryLike[]): NoteTouchRecord[] {
239
240
  }
240
241
  try {
241
242
  return entry.data.files.every(
242
- (file) =>
243
- validScope(file) &&
244
- noteRelative(file.path) === file.path &&
245
- (file.seed === undefined || validSeed(file.seed)),
243
+ (file) => validScope(file) && (file.seed === undefined || validSeed(file.seed)),
246
244
  )
247
- ? [entry.data]
245
+ ? [
246
+ {
247
+ ...entry.data,
248
+ // Earlier writers stored accepted aliases such as ./task.md verbatim.
249
+ files: entry.data.files.map((file) => ({
250
+ ...file,
251
+ path: noteRelative(file.path),
252
+ })),
253
+ },
254
+ ]
248
255
  : [];
249
256
  } catch {
250
257
  return [];
251
258
  }
252
259
  });
253
260
  }
261
+ /** Replay journal effects oldest first so later same-path adoption seeds replace earlier ones. */
254
262
  export function seedsOf(binding: NoteBinding, entries: readonly EntryLike[]): readonly NoteSeed[] {
255
263
  const seeds = new Map(
256
264
  binding.kind === "fork" ? binding.seeds.map((seed) => [seed.path, seed]) : [],
@@ -91,6 +91,7 @@ export type SnapshotNote = {
91
91
  readonly anchors: readonly string[];
92
92
  };
93
93
  const NOTE_IO_BATCH = 16;
94
+ /** Results retain input order. A failed batch settles all launched work before propagating failure. */
94
95
  export async function mapBatch<Input, Output>(
95
96
  items: readonly Input[],
96
97
  fn: (item: Input) => Promise<Output>,
package/src/note-store.ts CHANGED
@@ -103,7 +103,8 @@ export class SessionNotes {
103
103
  if (files.length === 0) {
104
104
  return;
105
105
  }
106
- for (const file of files) {
106
+ const normalized = files.map((file) => ({ ...file, path: noteRelative(file.path) }));
107
+ for (const file of normalized) {
107
108
  if (file.kind !== "read" && sameScope(file, this.binding)) {
108
109
  this.#owned.add(file.path);
109
110
  const path = canonicalPath(notePath(file, file.path));
@@ -116,7 +117,7 @@ export class SessionNotes {
116
117
  scope: { root: this.binding.root, scope: this.binding.scope },
117
118
  rootToolCallId: call.rootId,
118
119
  toolCallId: call.id,
119
- files,
120
+ files: normalized,
120
121
  } satisfies NoteTouchRecord);
121
122
  }
122
123
  async selectScope(selector: string): Promise<NoteScope> {
package/src/notes.ts CHANGED
@@ -130,21 +130,20 @@ async function readNote(
130
130
  target.kind === "own"
131
131
  ? noteReadHeader(path)
132
132
  : `Read-only live reference: notes read ${JSON.stringify({ scope: scopeDirectory(target.address), path: target.address.path })}\n`;
133
- const end = Math.min(
134
- text.length,
135
- offset + pages.size(access.host(), { headerChars: header.length }),
136
- );
137
- const more =
138
- end < text.length
139
- ? `\n[chars ${offset}-${end} of ${text.length}; continue with offset ${end}]`
140
- : "";
141
- session.record([{ ...target.address, kind: "read" }], access.call);
142
- return pages.result(`${header}${text.slice(offset, end)}${more}`, [], {
143
- kind: "note-read",
144
- headerLength: header.length,
145
- offset,
146
- end,
147
- total: text.length,
133
+ return pages.deliver(access.host(), { headerChars: header.length }, (chars) => {
134
+ const end = Math.min(text.length, offset + chars);
135
+ const more =
136
+ end < text.length
137
+ ? `\n[chars ${offset}-${end} of ${text.length}; continue with offset ${end}]`
138
+ : "";
139
+ session.record([{ ...target.address, kind: "read" }], access.call);
140
+ return textResult(`${header}${text.slice(offset, end)}${more}`, [], {
141
+ kind: "note-read",
142
+ headerLength: header.length,
143
+ offset,
144
+ end,
145
+ total: text.length,
146
+ });
148
147
  });
149
148
  }
150
149
  async function writeNote(
package/src/paging.ts CHANGED
@@ -1,12 +1,11 @@
1
- import type { PosthorseDisplay } from "../ui.ts";
2
1
  import { pageCapacity } from "./budget.ts";
2
+ import { textOf } from "./message-text.ts";
3
3
  import {
4
4
  ESTIMATED_IMAGE_CHARS,
5
5
  MAX_PAGE_CHARS,
6
6
  MIN_PAGE_CHARS,
7
7
  PAGE_MARGIN_TOKENS,
8
8
  textResult,
9
- type ImageLike,
10
9
  type PolicyContext,
11
10
  type TextResult,
12
11
  } from "./contracts.ts";
@@ -26,11 +25,11 @@ export type NotesPage = {
26
25
  readonly more?: boolean;
27
26
  };
28
27
  export type PageAccess = {
29
- readonly size: (ctx: PolicyContext, request?: PageRequest) => number;
30
- readonly result: (
31
- text: string,
32
- images: readonly ImageLike[],
33
- display: PosthorseDisplay,
28
+ /** Reconcile, build synchronously, and reserve before another page can be admitted. */
29
+ readonly deliver: (
30
+ ctx: PolicyContext,
31
+ request: PageRequest,
32
+ build: (chars: number) => TextResult,
34
33
  ) => TextResult;
35
34
  readonly error: (ctx: PolicyContext, message: string) => never;
36
35
  readonly notes: (ctx: PolicyContext, page: NotesPage) => TextResult;
@@ -74,7 +73,7 @@ export class PageReservations {
74
73
  * Body characters for the next page. Near the rollover line pages shrink to MIN_PAGE_CHARS
75
74
  * instead of refusing, so reading keeps making progress; Pi's rollover handles the overshoot.
76
75
  */
77
- size(ctx: PolicyContext, request: PageRequest = {}): number {
76
+ private size(ctx: PolicyContext, request: PageRequest): number {
78
77
  this.settle(ctx);
79
78
  const remaining = pageCapacity(ctx, this.toolTokens) - this.accounting.tokens;
80
79
  const budget = Math.min(
@@ -95,9 +94,14 @@ export class PageReservations {
95
94
  imageCount * (ESTIMATED_IMAGE_CHARS / 4),
96
95
  );
97
96
  }
98
- result(text: string, images: readonly ImageLike[], display: PosthorseDisplay): TextResult {
99
- this.reserve(text, images.length);
100
- return textResult(text, images, display);
97
+ deliver(
98
+ ctx: PolicyContext,
99
+ request: PageRequest,
100
+ build: (chars: number) => TextResult,
101
+ ): TextResult {
102
+ const result = build(this.size(ctx, request));
103
+ this.reserve(textOf(result), result.content.filter((part) => part.type === "image").length);
104
+ return result;
101
105
  }
102
106
  error(ctx: PolicyContext, message: string): never {
103
107
  this.settle(ctx);
@@ -107,32 +111,33 @@ export class PageReservations {
107
111
  notes(ctx: PolicyContext, page: NotesPage): TextResult {
108
112
  const { rows, offset, kind, empty, header = "", more } = page;
109
113
  const text = rows.length > 0 ? rows.join("\n") : empty;
110
- const chars = this.size(ctx, { headerChars: header.length });
111
- const footer = (end: number) =>
112
- `\n[chars ${offset}-${end}${more === true ? "; more matches follow" : ` of ${text.length}`}; continue with offset ${end}]`;
113
- if (offset > 0 && offset >= text.length) {
114
- this.error(ctx, "Offset is past the end; restart with offset 0.");
115
- }
116
- const range = notesRange(rows, {
117
- offset,
118
- end: Math.min(text.length, offset + chars),
119
- maxRows: kind === "notes-search" ? 20 : 100,
114
+ return this.deliver(ctx, { headerChars: header.length }, (chars) => {
115
+ const footer = (end: number) =>
116
+ `\n[chars ${offset}-${end}${more === true ? "; more matches follow" : ` of ${text.length}`}; continue with offset ${end}]`;
117
+ if (offset > 0 && offset >= text.length) {
118
+ this.error(ctx, "Offset is past the end; restart with offset 0.");
119
+ }
120
+ const range = notesRange(rows, {
121
+ offset,
122
+ end: Math.min(text.length, offset + chars),
123
+ maxRows: kind === "notes-search" ? 20 : 100,
124
+ });
125
+ const end =
126
+ range.end < text.length
127
+ ? Math.min(range.end, offset + chars - footer(text.length).length)
128
+ : range.end;
129
+ return textResult(
130
+ header + text.slice(offset, end) + (end < text.length ? footer(end) : ""),
131
+ [],
132
+ {
133
+ kind,
134
+ headerLength: header.length,
135
+ count: range.starts.filter((start) => start < end).length,
136
+ page: { offset, end, total: text.length },
137
+ ...(more === true ? { more } : {}),
138
+ },
139
+ );
120
140
  });
121
- const end =
122
- range.end < text.length
123
- ? Math.min(range.end, offset + chars - footer(text.length).length)
124
- : range.end;
125
- return this.result(
126
- header + text.slice(offset, end) + (end < text.length ? footer(end) : ""),
127
- [],
128
- {
129
- kind,
130
- headerLength: header.length,
131
- count: range.starts.filter((start) => start < end).length,
132
- page: { offset, end, total: text.length },
133
- ...(more === true ? { more } : {}),
134
- },
135
- );
136
141
  }
137
142
  }
138
143
  function notesRange(
@@ -202,7 +202,10 @@ function recoveryAncestry(
202
202
  skipped: skipped.map((boundary) => boundary.id?.slice(0, 120) ?? "unknown"),
203
203
  };
204
204
  }
205
- /** The inputs a record quotes in full (oldest first), the ones it only lists, and where its walk back ended. */
205
+ /**
206
+ * Entries use native branch order. First/latest owner anchors depend on that order, not timestamps.
207
+ * Returns the inputs quoted in full (oldest first), those only listed, and where ancestry ended.
208
+ */
206
209
  export function recoveryInputs(
207
210
  entries: readonly EntryLike[],
208
211
  projected: readonly ProjectedEntry[],
@@ -1,3 +1,4 @@
1
+ import { posix } from "node:path";
1
2
  import {
2
3
  NOTE_RECEIPT,
3
4
  isRecord,
@@ -22,9 +23,18 @@ export type NoteTarget = {
22
23
  readonly absPath?: string | undefined;
23
24
  readonly referenceScope?: string | undefined;
24
25
  };
26
+ /** Normalize journal path spelling without resolving archived evidence against today's filesystem. */
27
+ export function noteTargetKey(target: NoteTarget): string {
28
+ const location = target.referenceScope ?? target.absPath ?? "";
29
+ return JSON.stringify([
30
+ posix.normalize(location.replaceAll("\\", "/")),
31
+ posix.normalize(target.notePath.replaceAll("\\", "/")),
32
+ ]);
33
+ }
25
34
  export type NoteTouch = NoteTarget & {
26
35
  readonly entryId: string;
27
36
  readonly receiptId?: string | undefined;
37
+ readonly toolCallId?: string | undefined;
28
38
  readonly owner?: NoteOwner | undefined;
29
39
  } & (
30
40
  | { readonly kind: ContentTouchKind; readonly inRetained: boolean }
@@ -344,7 +354,8 @@ function touchesFromNested(message: MessageLike, context: TouchContext): NoteTou
344
354
  touch.kind === "read" || touch.kind === "clear" ? touch.kind : "observed-write",
345
355
  inRetained: false,
346
356
  receiptId: context.sourceId,
347
- } satisfies Pick<NoteTouch, "kind" | "inRetained" | "receiptId">),
357
+ toolCallId: optionalString(raw.id),
358
+ } satisfies Pick<NoteTouch, "kind" | "inRetained" | "receiptId" | "toolCallId">),
348
359
  );
349
360
  });
350
361
  }
@@ -368,7 +379,9 @@ function touchesFromAssistantCall(
368
379
  : fileToolTouches(tool, args, res, context);
369
380
  return {
370
381
  consumedCallId,
371
- touches: touches.map((touch) => Object.assign({}, touch, { receiptId: res.sourceId })),
382
+ touches: touches.map((touch) =>
383
+ Object.assign({}, touch, { receiptId: res.sourceId, toolCallId: callId }),
384
+ ),
372
385
  };
373
386
  }
374
387
 
@@ -385,7 +398,10 @@ function touchesFromToolResult(
385
398
  !handledResultIds.has(callId) && bareToolName(msg.toolName) === "notes"
386
399
  ? notesToolTouches({}, textOf(msg), context)
387
400
  : [];
388
- return [...direct, ...touchesFromNested(msg, context)];
401
+ return [
402
+ ...direct.map((touch) => Object.assign({}, touch, { toolCallId: callId })),
403
+ ...touchesFromNested(msg, context),
404
+ ];
389
405
  }
390
406
 
391
407
  export function collectTouches(
@@ -2,7 +2,7 @@ import { join } from "node:path";
2
2
  import type { EntryLike, ProjectedEntry } from "./contracts.ts";
3
3
  import { sessionNoteTouches, scopeRecoveryTouches, type NotesRecovery } from "./note-evidence.ts";
4
4
  import { scopeDirectory } from "./note-scopes.ts";
5
- import type { NoteTarget, NoteTouch } from "./recovery-note-touches.ts";
5
+ import { noteTargetKey, type NoteTarget, type NoteTouch } from "./recovery-note-touches.ts";
6
6
  import type { RetainedSpan } from "./retained-tail.ts";
7
7
 
8
8
  const MAX_WRITTEN_NOTES = 4;
@@ -162,7 +162,7 @@ function trackedNotes(
162
162
  rawTouch.absPath === undefined && defaultDir !== undefined
163
163
  ? { ...rawTouch, absPath: `${defaultDir}/${rawTouch.notePath}` }
164
164
  : rawTouch;
165
- const key = `${touch.referenceScope ?? touch.absPath ?? ""}\0${touch.notePath}`;
165
+ const key = noteTargetKey(touch);
166
166
  const next = applyTouch(tracked.get(key), touch, order);
167
167
  if (next === undefined) {
168
168
  tracked.delete(key);
@@ -63,6 +63,7 @@ export class ResetRequests {
63
63
  root.state = { ...root.state, kind: "settled" };
64
64
  }
65
65
  }
66
+ /** The first request within one foreground root owns its handoff. */
66
67
  request(id: string, handoff: string): void {
67
68
  const root = this.#active.get(id);
68
69
  if (root === undefined || !this.#active.has(root.id)) {
@@ -75,6 +76,7 @@ export class ResetRequests {
75
76
  /**
76
77
  * Settles the whole foreground batch. Any failed receipt cancels the reset, an aborted turn
77
78
  * keeps its context, and the first settled receipt that carries a handoff is honored.
79
+ * Results use host batch order, not completion order; settling consumes all requests.
78
80
  */
79
81
  settle(
80
82
  results: TurnEndEvent["toolResults"],