pi-tuck 1.1.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +28 -59
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/bash-command.d.ts +8 -0
  6. package/dist/src/bash-command.js +116 -0
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +2 -103
  10. package/dist/src/compaction.js +20 -140
  11. package/dist/src/diagnostic-replay.js +3 -3
  12. package/dist/src/diagnostics.d.ts +3 -2
  13. package/dist/src/diagnostics.js +30 -9
  14. package/dist/src/history-tools.js +3 -3
  15. package/dist/src/kept-reads.d.ts +2 -2
  16. package/dist/src/kept-reads.js +35 -8
  17. package/dist/src/kept-searches.d.ts +11 -0
  18. package/dist/src/kept-searches.js +202 -0
  19. package/dist/src/ledger.d.ts +1 -1
  20. package/dist/src/ledger.js +5 -3
  21. package/dist/src/legacy-cleanup.d.ts +3 -0
  22. package/dist/src/legacy-cleanup.js +190 -0
  23. package/dist/src/notify.d.ts +3 -0
  24. package/dist/src/notify.js +13 -0
  25. package/dist/src/omissions.d.ts +1 -1
  26. package/dist/src/omissions.js +3 -3
  27. package/dist/src/path-key.d.ts +3 -0
  28. package/dist/src/path-key.js +8 -0
  29. package/dist/src/request-capacity.js +1 -1
  30. package/dist/src/run.d.ts +1 -3
  31. package/dist/src/run.js +3 -5
  32. package/dist/src/source-export.d.ts +1 -1
  33. package/dist/src/source-export.js +1 -1
  34. package/dist/src/status.d.ts +0 -6
  35. package/dist/src/status.js +1 -6
  36. package/dist/src/tuck/core/content.d.ts +0 -11
  37. package/dist/src/tuck/core/content.js +5 -55
  38. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  39. package/dist/src/tuck/core/keyword-query.js +1 -1
  40. package/dist/src/tuck/core/search-entries.d.ts +5 -28
  41. package/dist/src/tuck/core/search-entries.js +14 -156
  42. package/dist/src/tuck/core/transcript.js +2 -1
  43. package/dist/src/tuck.d.ts +7 -15
  44. package/dist/src/tuck.js +409 -409
  45. package/dist/src/windows-private-storage.d.ts +9 -0
  46. package/dist/src/windows-private-storage.js +90 -0
  47. package/index.ts +18 -82
  48. package/package.json +5 -8
  49. package/src/bash-command.ts +59 -0
  50. package/src/build-id.ts +1 -1
  51. package/src/compaction.ts +19 -107
  52. package/src/diagnostic-replay.ts +3 -3
  53. package/src/diagnostics.ts +24 -9
  54. package/src/history-tools.ts +3 -3
  55. package/src/kept-reads.ts +27 -10
  56. package/src/kept-searches.ts +163 -0
  57. package/src/ledger.ts +5 -3
  58. package/src/legacy-cleanup.ts +134 -0
  59. package/src/notify.ts +10 -0
  60. package/src/omissions.ts +3 -3
  61. package/src/path-key.ts +9 -0
  62. package/src/request-capacity.ts +1 -1
  63. package/src/run.ts +4 -6
  64. package/src/source-export.ts +1 -1
  65. package/src/status.ts +1 -10
  66. package/src/tuck/core/content.ts +4 -52
  67. package/src/tuck/core/keyword-query.ts +2 -2
  68. package/src/tuck/core/search-entries.ts +15 -202
  69. package/src/tuck/core/transcript.ts +2 -1
  70. package/src/tuck.ts +350 -357
  71. package/src/windows-private-storage.ts +94 -0
  72. package/dist/src/assets.d.ts +0 -58
  73. package/dist/src/assets.js +0 -80
  74. package/dist/src/eligibility-cache.d.ts +0 -19
  75. package/dist/src/eligibility-cache.js +0 -33
  76. package/dist/src/semantic-recall.d.ts +0 -422
  77. package/dist/src/semantic-recall.js +0 -1386
  78. package/dist/src/setup.d.ts +0 -3
  79. package/dist/src/setup.js +0 -191
  80. package/scripts/eg2-runtime.py +0 -307
  81. package/scripts/provision-eg2.py +0 -139
  82. package/scripts/semantic-worker.py +0 -234
  83. package/src/assets.ts +0 -92
  84. package/src/eligibility-cache.ts +0 -43
  85. package/src/semantic-recall.ts +0 -592
  86. package/src/setup.ts +0 -163
package/dist/src/tuck.js CHANGED
@@ -8,6 +8,7 @@ import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content.js";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
10
  import { keptReadCandidates } from "./kept-reads.js";
11
+ import { keptSearchCandidates } from "./kept-searches.js";
11
12
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
12
13
  import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
13
14
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
@@ -17,11 +18,12 @@ import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/
17
18
  import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
18
19
  import { compileDialogue } from "./tuck/core/summarize.js";
19
20
  import { prepareKeywordQuery } from "./tuck/core/keyword-query.js";
20
- import { searchEntriesDetailed } from "./tuck/core/search-entries.js";
21
- export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, searchEntriesDetailed };
22
- /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation. */
23
- export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, operatorManual = false, newPrompt = false, protectedPromptEntryId) {
24
- return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, operatorManual, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
21
+ import { rankRecallRows } from "./tuck/core/search-entries.js";
22
+ export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
23
+ /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
24
+ * `_operatorManual` retains the exported positional slot for existing callers. */
25
+ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId) {
26
+ return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
25
27
  }
26
28
  /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
27
29
  /** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
@@ -144,422 +146,422 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
144
146
  floorBoundary = Math.min(floorBoundary, latestPosition);
145
147
  // One fill owns the summary and the contiguous native suffix. Protocol/current-input
146
148
  // floors are representation constraints; every other source competes by rank.
147
- return rankedFill();
148
- function rankedFill() {
149
- const model = ctx.model;
150
- if (!model)
151
- return { unavailable: "pi-tuck needs a model to measure the cut" };
152
- const indices = tuck.buildGlobalIndexById(ctx.sessionManager.getEntries());
153
- const header = ctx.sessionManager.getHeader();
154
- if (!header)
155
- throw new Error("Missing native session header");
156
- const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
157
- const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
158
- const positions = new Map(entries.map((entry, at) => [entry.id, at]));
159
- const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
160
- if (!originals.ok)
161
- return { unavailable: "No eligible original prefix to compile" };
162
- const byId = new Map(entries.map(entry => [entry.id, entry]));
163
- const sourceIndices = originals.selectedIds.map(id => indices.get(id));
164
- const rows = originals.selectedIds.map((id, at) => ({ id, position: positions.get(id), index: sourceIndices[at], message: originals.messages[at] }));
165
- const users = rows.filter(row => row.message.role === "user");
166
- const userTexts = new Map(users.map(row => [row.index, textOf(row.message.content)]));
167
- let replied = false;
168
- const answered = [];
169
- for (let at = entries.length - 1; at >= 0; at--) {
170
- const entry = entries[at];
171
- if (entry.type !== "message")
172
- continue;
173
- if (entry.message.role === "assistant" && !isDiscardedResponse(entry.message) && entry.message.content.length) {
174
- replied = true;
175
- continue;
176
- }
177
- if (entry.message.role !== "user")
178
- continue;
179
- if (replied && textOf(entry.message.content).length)
180
- answered.push(entry);
181
- replied = false;
149
+ const model = ctx.model;
150
+ if (!model)
151
+ return { unavailable: "pi-tuck needs a model to measure the cut" };
152
+ const indices = tuck.buildGlobalIndexById(ctx.sessionManager.getEntries());
153
+ const header = ctx.sessionManager.getHeader();
154
+ if (!header)
155
+ throw new Error("Missing native session header");
156
+ const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
157
+ const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
158
+ const positions = new Map(entries.map((entry, at) => [entry.id, at]));
159
+ const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
160
+ if (!originals.ok)
161
+ return { unavailable: "No eligible original prefix to compile" };
162
+ const sourceIndices = originals.selectedIds.map(id => indices.get(id));
163
+ const rows = originals.selectedIds.map((id, at) => ({ id, position: positions.get(id), index: sourceIndices[at], message: originals.messages[at] }));
164
+ const users = rows.filter(row => row.message.role === "user");
165
+ const userTexts = new Map(users.map(row => [row.index, textOf(row.message.content)]));
166
+ let replied = false;
167
+ const answered = [];
168
+ for (let at = entries.length - 1; at >= 0; at--) {
169
+ const entry = entries[at];
170
+ if (entry.type !== "message")
171
+ continue;
172
+ if (entry.message.role === "assistant" && !isDiscardedResponse(entry.message) && entry.message.content.length) {
173
+ replied = true;
174
+ continue;
182
175
  }
183
- const anchors = [...new Map([...answered.slice(0, 8), ...(firstUserPosition >= 0 ? [entries[firstUserPosition]] : [])].map(entry => [entry.id, entry])).values()];
184
- const failedCalls = new Set(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.isError ? [entry.message.toolCallId] : []));
185
- const detailsAt = (boundary) => ({ compactor: "pi-tuck", version: 2, adapter: "standalone",
186
- keptUserTurns: users.reduce((n, row) => n + Number(row.position >= boundary), 0),
187
- ...(boundary === preferredBoundary && budgetCut ? { budgetCut } : {}) });
188
- const preview = (summary, boundary) => {
189
- const manager = SessionManager.inMemory(ctx.cwd, undefined, [header, ...branch]);
190
- manager.appendCompaction(summary, entries[boundary]?.id ?? "", input.tokensBefore, detailsAt(boundary), true);
191
- return manager.buildSessionProjection().messages;
192
- };
193
- // Price the native suffix once. The measure's additive offset and Pi's
194
- // summary envelope are calibrated once, rather than replaying a session
195
- // for each opening, ledger line or tail boundary considered by the fill.
196
- const rawPositions = new Map(branch.map((entry, at) => [entry.id, at]));
197
- const native = new Float64Array(branch.length + 1);
198
- for (const entry of projected.entries) {
199
- if (entry.sourceEntry.type === "compaction")
200
- continue;
201
- const at = rawPositions.get(entry.sourceEntry.id);
202
- if (at !== undefined)
203
- for (const message of entry.messages)
204
- native[at] += measure.messageTokens ? measure.messageTokens(message) : conversationTokens([message]);
205
- }
206
- for (let at = branch.length - 1; at >= 0; at--)
207
- native[at] += native[at + 1];
208
- const nativeAt = (boundary) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary].id)];
209
- const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
210
- // Move only the older end, to the newest whole protocol-safe entries
211
- // within the shared tail size. Required current/fresh native sources
212
- // stay whole even when their floor exceeds that preferred amount.
213
- while (preferredBoundary < floorBoundary && nativeAt(preferredBoundary) > tailTokens) {
176
+ if (entry.message.role !== "user")
177
+ continue;
178
+ if (replied && textOf(entry.message.content).length)
179
+ answered.push(entry);
180
+ replied = false;
181
+ }
182
+ const anchors = [...new Map([...answered.slice(0, 8), ...(firstUserPosition >= 0 ? [entries[firstUserPosition]] : [])].map(entry => [entry.id, entry])).values()];
183
+ const failedCalls = new Set(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.isError ? [entry.message.toolCallId] : []));
184
+ const detailsAt = (boundary) => ({ compactor: "pi-tuck", version: 2, adapter: "standalone",
185
+ keptUserTurns: users.reduce((n, row) => n + Number(row.position >= boundary), 0),
186
+ ...(boundary === preferredBoundary && budgetCut ? { budgetCut } : {}) });
187
+ const preview = (summary, boundary) => {
188
+ const manager = SessionManager.inMemory(ctx.cwd, undefined, [header, ...branch]);
189
+ manager.appendCompaction(summary, entries[boundary]?.id ?? "", input.tokensBefore, detailsAt(boundary), true);
190
+ return manager.buildSessionProjection().messages;
191
+ };
192
+ // Price the native suffix once. The measure's additive offset and Pi's
193
+ // summary envelope are calibrated once, rather than replaying a session
194
+ // for each opening, ledger line or tail boundary considered by the fill.
195
+ const rawPositions = new Map(branch.map((entry, at) => [entry.id, at]));
196
+ const native = new Float64Array(branch.length + 1);
197
+ for (const entry of projected.entries) {
198
+ if (entry.sourceEntry.type === "compaction")
199
+ continue;
200
+ const at = rawPositions.get(entry.sourceEntry.id);
201
+ if (at !== undefined)
202
+ for (const message of entry.messages)
203
+ native[at] += measure.messageTokens ? measure.messageTokens(message) : conversationTokens([message]);
204
+ }
205
+ for (let at = branch.length - 1; at >= 0; at--)
206
+ native[at] += native[at + 1];
207
+ const nativeAt = (boundary) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary].id)];
208
+ const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
209
+ // Move only the older end, to the newest whole protocol-safe entries
210
+ // within the shared tail size. Required current/fresh native sources
211
+ // stay whole even when their floor exceeds that preferred amount.
212
+ while (preferredBoundary < floorBoundary && nativeAt(preferredBoundary) > tailTokens) {
213
+ preferredBoundary++;
214
+ while (preferredBoundary < floorBoundary) {
215
+ const entry = entries[preferredBoundary];
216
+ if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary")
217
+ break;
214
218
  preferredBoundary++;
215
- while (preferredBoundary < floorBoundary) {
216
- const entry = entries[preferredBoundary];
217
- if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary")
218
- break;
219
- preferredBoundary++;
220
- }
221
219
  }
222
- const envelope = convertToLlm([{ role: "compactionSummary", summary: "", tokensBefore: 0, timestamp: 0 }]);
223
- const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
224
- const summaryTokens = (characters) => Math.ceil((characters + wrapperCharacters) / 4);
225
- const lineCost = (records) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
226
- const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
227
- const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
228
- const units = { user: [], assistant: [], toolResult: [] };
229
- for (const row of rows) {
230
- if (row.index === undefined)
231
- continue;
232
- const message = row.message;
233
- if (message.role === "user" && textOf(message.content).length)
234
- units.user.push({ position: row.position, index: row.index, count: 1 });
235
- else if (message.role === "toolResult")
236
- units.toolResult.push({ position: row.position, index: row.index, count: 1 });
237
- else if (message.role === "assistant" && !isDiscardedResponse(message)) {
238
- const count = message.content.filter(part => part.type === "text" && part.text.trim()).length;
239
- if (count)
240
- units.assistant.push({ position: row.position, index: row.index, count });
241
- }
220
+ }
221
+ const envelope = convertToLlm([{ role: "compactionSummary", summary: "", tokensBefore: 0, timestamp: 0 }]);
222
+ const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
223
+ const summaryTokens = (characters) => Math.ceil((characters + wrapperCharacters) / 4);
224
+ const lineCost = (records) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
225
+ const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
226
+ const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
227
+ const units = { user: [], assistant: [], toolResult: [] };
228
+ for (const row of rows) {
229
+ if (row.index === undefined)
230
+ continue;
231
+ const message = row.message;
232
+ if (message.role === "user" && textOf(message.content).length)
233
+ units.user.push({ position: row.position, index: row.index, count: 1 });
234
+ else if (message.role === "toolResult")
235
+ units.toolResult.push({ position: row.position, index: row.index, count: 1 });
236
+ else if (message.role === "assistant" && !isDiscardedResponse(message)) {
237
+ const count = message.content.filter(part => part.type === "text" && part.text.trim()).length;
238
+ if (count)
239
+ units.assistant.push({ position: row.position, index: row.index, count });
242
240
  }
243
- const prefixes = Object.fromEntries(Object.entries(units).map(([role, list]) => {
244
- const end = new Int32Array(entries.length + 1), count = new Int32Array(list.length + 1);
245
- let seen = 0;
246
- for (let at = 0; at <= entries.length; at++) {
247
- while (seen < list.length && list[seen].position < at)
248
- seen++;
249
- end[at] = seen;
250
- }
251
- list.forEach((unit, at) => count[at + 1] = count[at] + unit.count);
252
- return [role, { end, count }];
253
- }));
254
- const quoteCache = new Map();
255
- const quote = (entry, take) => {
256
- const key = `${entry.id}:${take}`;
257
- let cached = quoteCache.get(key);
258
- if (cached)
259
- return cached;
260
- const index = indices.get(entry.id);
261
- const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
262
- const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
263
- // Custom entries have a native identity but no global message index.
264
- const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
265
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
266
- ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
267
- : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
268
- cached = { records, cost: lineCost(records), whole: take >= text.length };
269
- quoteCache.set(key, cached);
241
+ }
242
+ const prefixes = Object.fromEntries(Object.entries(units).map(([role, list]) => {
243
+ const end = new Int32Array(entries.length + 1), count = new Int32Array(list.length + 1);
244
+ let seen = 0;
245
+ for (let at = 0; at <= entries.length; at++) {
246
+ while (seen < list.length && list[seen].position < at)
247
+ seen++;
248
+ end[at] = seen;
249
+ }
250
+ list.forEach((unit, at) => count[at + 1] = count[at] + unit.count);
251
+ return [role, { end, count }];
252
+ }));
253
+ const quoteCache = new Map();
254
+ const quote = (entry, take) => {
255
+ const key = `${entry.id}:${take}`;
256
+ let cached = quoteCache.get(key);
257
+ if (cached)
270
258
  return cached;
271
- };
272
- const highAt = (boundary, length) => {
273
- const kept = [], selected = new Set(), whole = new Set();
274
- let cost = 0;
275
- const add = (entry, take) => {
276
- const quoted = quote(entry, take), index = indices.get(entry.id);
277
- kept.push(...quoted.records);
278
- cost += quoted.cost;
279
- if (index !== undefined && quoted.records.length) {
280
- selected.add(index);
281
- if (quoted.whole)
282
- whole.add(index);
283
- }
284
- };
285
- if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly)
286
- add(latest, Infinity);
287
- if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id)
288
- add(current, Infinity);
289
- for (const entry of anchors)
290
- if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id) < boundary)
291
- add(entry, length);
292
- const omissions = [];
293
- for (const role of ["user", "assistant", "toolResult"]) {
294
- const list = units[role], prefix = prefixes[role];
295
- let first = 0, last = prefix.end[boundary] - 1;
296
- if (role === "user") {
297
- while (first <= last && selected.has(list[first].index))
298
- first++;
299
- while (last >= first && selected.has(list[last].index))
300
- last--;
301
- }
302
- if (last < first)
303
- continue;
304
- const a = list[first], b = list[last];
305
- let count = prefix.count[last + 1] - prefix.count[first];
306
- if (role === "user")
307
- for (const index of whole)
308
- if (index >= a.index && index <= b.index)
309
- count--;
310
- if (count)
311
- omissions.push(omissionRecord(role, count, [a.index, b.index], false));
259
+ const index = indices.get(entry.id);
260
+ const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
261
+ const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
262
+ // Custom entries have a native identity but no global message index.
263
+ const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
264
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
265
+ ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
266
+ : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
267
+ cached = { records, cost: lineCost(records), whole: take >= text.length };
268
+ quoteCache.set(key, cached);
269
+ return cached;
270
+ };
271
+ const highAt = (boundary, length) => {
272
+ const kept = [], selected = new Set(), whole = new Set();
273
+ let cost = 0;
274
+ const add = (entry, take) => {
275
+ const quoted = quote(entry, take), index = indices.get(entry.id);
276
+ kept.push(...quoted.records);
277
+ cost += quoted.cost;
278
+ if (index !== undefined && quoted.records.length) {
279
+ selected.add(index);
280
+ if (quoted.whole)
281
+ whole.add(index);
312
282
  }
313
- const rows = [...kept, ...omissions], totalCost = cost + lineCost(omissions);
314
- return { kept, whole, omissions, rows, cost: totalCost, length: frameLength(totalCost, rows.length) };
315
- };
316
- const calibrationHigh = highAt(floorBoundary, minimumOpeningLength);
317
- const floorSummary = render(calibrationHigh.rows), floorProjection = preview(floorSummary, floorBoundary);
318
- // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
319
- // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
320
- if (input.deepest) {
321
- assertNativeToolRounds(floorProjection);
322
- const after = measure(floorProjection);
323
- return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
324
- details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
325
- }
326
- const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
327
- const price = (characters, boundary) => offset + nativeAt(boundary) + summaryTokens(characters);
328
- const listCache = new Map();
329
- const listsAt = (boundary) => {
330
- const cached = listCache.get(boundary);
331
- if (cached)
332
- return cached;
333
- const compacted = entries.slice(0, boundary), resolves = (entry) => readable(entry) !== undefined;
334
- const files = ledgerItems(compacted, indices, resolves, failedCalls), actions = actionItems(compacted, indices, resolves, failedCalls);
335
- const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
336
- listCache.set(boundary, lists);
337
- return lists;
338
283
  };
339
- const preferredHigh = highAt(preferredBoundary, openingLength), preferredLists = listsAt(preferredBoundary);
340
- const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
341
- const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
342
- const base = price(baseCharacters, preferredBoundary);
343
- const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
344
- // The old tail rule supplies an ordering boundary only. Its recent
345
- // suffix follows the openings, and is charged to the same total grant.
346
- const boundaries = [floorBoundary];
347
- for (let at = floorBoundary - 1; at >= preferredBoundary; at--) {
348
- const entry = entries[at];
349
- if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary")
350
- boundaries.push(at);
351
- }
352
- boundaries.reverse();
353
- const tailFor = (length) => {
354
- // Longest suffix first: the first fit is the preferred rank. Most
355
- // cuts keep that entire suffix, so no other boundaries need pricing.
356
- for (const boundary of boundaries) {
357
- const high = highAt(boundary, length);
358
- if (price(high.length, boundary) <= target)
359
- return { boundary, high };
284
+ if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly)
285
+ add(latest, Infinity);
286
+ if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id)
287
+ add(current, Infinity);
288
+ for (const entry of anchors)
289
+ if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id) < boundary)
290
+ add(entry, length);
291
+ const omissions = [];
292
+ for (const role of ["user", "assistant", "toolResult"]) {
293
+ const list = units[role], prefix = prefixes[role];
294
+ let first = 0, last = prefix.end[boundary] - 1;
295
+ if (role === "user") {
296
+ while (first <= last && selected.has(list[first].index))
297
+ first++;
298
+ while (last >= first && selected.has(list[last].index))
299
+ last--;
360
300
  }
361
- return undefined;
362
- };
363
- let selected = tailFor(minimumOpeningLength);
364
- if (!selected)
365
- return { unavailable: "pi-tuck's mandatory context cannot fit or reduce the request budget",
366
- capacityRejected: price(calibrationHigh.length, floorBoundary) + reserveTokens >= model.contextWindow,
367
- floorMessages: floorProjection };
368
- let low = minimumOpeningLength, high = openingLength;
369
- while (low < high) {
370
- const middle = Math.ceil((low + high) / 2);
371
- if (tailFor(middle))
372
- low = middle;
373
- else
374
- high = middle - 1;
375
- }
376
- selected = tailFor(low);
377
- let { boundary, high: protectedView } = selected;
378
- const sourceRows = rows.filter(row => row.position < boundary);
379
- const lists = listsAt(boundary);
380
- const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
381
- const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
382
- let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
383
- const keptReads = [];
384
- for (const record of keptReadCandidates(entries.slice(0, boundary), indices, entry => readable(entry) !== undefined)) {
385
- const cost = lineCost([record]);
386
- if (cost > allowance)
301
+ if (last < first)
387
302
  continue;
388
- keptReads.push(record);
389
- allowance -= cost;
390
- if (keptReads.length === 4)
391
- break;
303
+ const a = list[first], b = list[last];
304
+ let count = prefix.count[last + 1] - prefix.count[first];
305
+ if (role === "user")
306
+ for (const index of whole)
307
+ if (index >= a.index && index <= b.index)
308
+ count--;
309
+ if (count)
310
+ omissions.push(omissionRecord(role, count, [a.index, b.index], false));
392
311
  }
393
- let ledger = [...lists.records, ...keptReads];
394
- // List caps are existing ranking policy; only the carried target is a
395
- // spending limit. Candidate list sizes have fixed, cached line prices.
396
- while (keptReads.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
397
- keptReads.pop();
398
- ledger = [...lists.records, ...keptReads];
312
+ const rows = [...kept, ...omissions], totalCost = cost + lineCost(omissions);
313
+ return { kept, whole, omissions, rows, cost: totalCost, length: frameLength(totalCost, rows.length) };
314
+ };
315
+ const calibrationHigh = highAt(floorBoundary, minimumOpeningLength);
316
+ const floorSummary = render(calibrationHigh.rows), floorProjection = preview(floorSummary, floorBoundary);
317
+ // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
318
+ // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
319
+ if (input.deepest) {
320
+ assertNativeToolRounds(floorProjection);
321
+ const after = measure(floorProjection);
322
+ return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
323
+ details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
324
+ }
325
+ const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
326
+ const price = (characters, boundary) => offset + nativeAt(boundary) + summaryTokens(characters);
327
+ const listCache = new Map();
328
+ const listsAt = (boundary) => {
329
+ const cached = listCache.get(boundary);
330
+ if (cached)
331
+ return cached;
332
+ const compacted = entries.slice(0, boundary), resolves = (entry) => readable(entry) !== undefined;
333
+ const files = ledgerItems(compacted, indices, resolves, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolves, failedCalls);
334
+ const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
335
+ listCache.set(boundary, lists);
336
+ return lists;
337
+ };
338
+ const preferredHigh = highAt(preferredBoundary, openingLength), preferredLists = listsAt(preferredBoundary);
339
+ const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
340
+ const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
341
+ const base = price(baseCharacters, preferredBoundary);
342
+ const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
343
+ // The old tail rule supplies an ordering boundary only. Its recent
344
+ // suffix follows the openings, and is charged to the same total grant.
345
+ const boundaries = [floorBoundary];
346
+ for (let at = floorBoundary - 1; at >= preferredBoundary; at--) {
347
+ const entry = entries[at];
348
+ if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary")
349
+ boundaries.push(at);
350
+ }
351
+ boundaries.reverse();
352
+ const tailFor = (length) => {
353
+ // Longest suffix first: the first fit is the preferred rank. Most
354
+ // cuts keep that entire suffix, so no other boundaries need pricing.
355
+ for (const boundary of boundaries) {
356
+ const high = highAt(boundary, length);
357
+ if (price(high.length, boundary) <= target)
358
+ return { boundary, high };
399
359
  }
400
- if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
401
- ledger = [];
402
- for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
403
- const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
404
- if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target)
405
- ledger = candidate;
406
- }
360
+ return undefined;
361
+ };
362
+ let selected = tailFor(minimumOpeningLength);
363
+ if (!selected)
364
+ return { unavailable: "pi-tuck's mandatory context cannot fit or reduce the request budget",
365
+ capacityRejected: price(calibrationHigh.length, floorBoundary) + reserveTokens >= model.contextWindow,
366
+ floorMessages: floorProjection };
367
+ let low = minimumOpeningLength, high = openingLength;
368
+ while (low < high) {
369
+ const middle = Math.ceil((low + high) / 2);
370
+ if (tailFor(middle))
371
+ low = middle;
372
+ else
373
+ high = middle - 1;
374
+ }
375
+ selected = tailFor(low);
376
+ let { boundary, high: protectedView } = selected;
377
+ const sourceRows = rows.filter(row => row.position < boundary);
378
+ const lists = listsAt(boundary);
379
+ const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
380
+ const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
381
+ let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
382
+ const keptResults = [], counts = new Map();
383
+ const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
384
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
385
+ .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
386
+ for (const record of candidates) {
387
+ if ((counts.get(record.title) ?? 0) === 4)
388
+ continue;
389
+ const cost = lineCost([record]);
390
+ if (cost > allowance)
391
+ continue;
392
+ keptResults.push(record);
393
+ allowance -= cost;
394
+ counts.set(record.title, (counts.get(record.title) ?? 0) + 1);
395
+ }
396
+ let ledger = [...lists.records, ...keptResults];
397
+ // List caps are existing ranking policy; only the carried target is a
398
+ // spending limit. Candidate list sizes have fixed, cached line prices.
399
+ while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
400
+ keptResults.pop();
401
+ ledger = [...lists.records, ...keptResults];
402
+ }
403
+ if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
404
+ ledger = [];
405
+ for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
406
+ const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
407
+ if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target)
408
+ ledger = candidate;
407
409
  }
408
- const mandatory = new Set([...protectedView.whole].filter(index => {
409
- const row = users.find(row => row.index === index);
410
- return row?.message.role === "user" && isTextOnly(row.message.content);
411
- }));
412
- const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
413
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
414
- const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
415
- sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(byId.get(row.id))),
416
- ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
417
- const imageLabels = new Map();
418
- for (const row of sourceRows)
419
- if (row.message.role === "user" && Array.isArray(row.message.content))
420
- imageLabels.set(row.index, new Set(row.message.content.flatMap(part => part.type === "image" ? [`[image: ${part.mimeType}]`] : [])));
421
- const compiledBoundary = boundary;
422
- // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
423
- const sourceKey = (record) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
424
- const assemble = (compiled, at = compiledBoundary) => {
425
- const split = compiled ? splitSummary(compiled) : undefined;
426
- if (compiled && !split)
427
- throw new Error("pi-tuck returned an invalid summary");
428
- const inputRecords = split ? parseRecords(split.body, split.version) : protectedView.omissions;
429
- const expanded = new Set(protectedView.kept.filter(record => record.kind === "excerpt" && inputRecords.some(row => row.kind === "excerpt" && row.role === record.role && sourceKey(row) === sourceKey(record) && row.text.startsWith(record.text) && row.text.length >= record.text.length)).map(sourceKey));
430
- const anchored = new Set(protectedView.kept.map(sourceKey));
431
- const moved = new Set(rows.filter(row => row.position >= at && row.position < compiledBoundary).map(row => current?.type === "custom_message" && row.id === current.id ? row.id : row.index));
432
- const records = [...inputRecords.filter(record => {
433
- const key = sourceKey(record);
434
- if (key !== undefined && moved.has(key))
435
- return false;
436
- if (record.kind === "excerpt" && record.role === "user" && imageLabels.get(record.sourceIndex)?.has(record.text))
437
- return true;
438
- return record.role !== "user" && record.role !== "custom" || key === undefined || !anchored.has(key) || expanded.has(key);
439
- }), ...protectedView.kept.filter(record => !expanded.has(sourceKey(record)) && !moved.has(sourceKey(record)))];
440
- // Mixed user turns keep their text opening, while their image
441
- // metadata remains in the ordinary lower-ranked dialogue lane.
442
- const wholeUser = new Set(records.filter(record => record.kind === "excerpt" && record.role === "user" && record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
443
- const wholeAssistant = new Map();
444
- for (const record of records)
445
- if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
446
- wholeAssistant.set(record.sourceIndex, (wholeAssistant.get(record.sourceIndex) ?? 0) + 1);
447
- for (let pos = records.length - 1; pos >= 0; pos--) {
448
- const record = records[pos];
449
- if (record.kind !== "omission" || !record.sourceRange)
450
- continue;
451
- if (record.role === "user") {
452
- const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end && !wholeUser.has(unit.index));
453
- if (!missing.length)
410
+ }
411
+ const mandatory = new Set([...protectedView.whole].filter(index => {
412
+ const row = users.find(row => row.index === index);
413
+ return row?.message.role === "user" && isTextOnly(row.message.content);
414
+ }));
415
+ const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
416
+ const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
417
+ const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
418
+ sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
419
+ ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
420
+ const imageLabels = new Map();
421
+ for (const row of sourceRows)
422
+ if (row.message.role === "user" && Array.isArray(row.message.content))
423
+ imageLabels.set(row.index, new Set(row.message.content.flatMap(part => part.type === "image" ? [`[image: ${part.mimeType}]`] : [])));
424
+ const compiledBoundary = boundary;
425
+ // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
426
+ const sourceKey = (record) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
427
+ const assemble = (compiled, at = compiledBoundary) => {
428
+ const split = compiled ? splitSummary(compiled) : undefined;
429
+ if (compiled && !split)
430
+ throw new Error("pi-tuck returned an invalid summary");
431
+ const inputRecords = split ? parseRecords(split.body, split.version) : protectedView.omissions;
432
+ const expanded = new Set(protectedView.kept.filter(record => record.kind === "excerpt" && inputRecords.some(row => row.kind === "excerpt" && row.role === record.role && sourceKey(row) === sourceKey(record) && row.text.startsWith(record.text) && row.text.length >= record.text.length)).map(sourceKey));
433
+ const anchored = new Set(protectedView.kept.map(sourceKey));
434
+ const moved = new Set(rows.filter(row => row.position >= at && row.position < compiledBoundary).map(row => current?.type === "custom_message" && row.id === current.id ? row.id : row.index));
435
+ const records = [...inputRecords.filter(record => {
436
+ const key = sourceKey(record);
437
+ if (key !== undefined && moved.has(key))
438
+ return false;
439
+ if (record.kind === "excerpt" && record.role === "user" && imageLabels.get(record.sourceIndex)?.has(record.text))
440
+ return true;
441
+ return record.role !== "user" && record.role !== "custom" || key === undefined || !anchored.has(key) || expanded.has(key);
442
+ }), ...protectedView.kept.filter(record => !expanded.has(sourceKey(record)) && !moved.has(sourceKey(record)))];
443
+ // Mixed user turns keep their text opening, while their image
444
+ // metadata remains in the ordinary lower-ranked dialogue lane.
445
+ const wholeUser = new Set(records.filter(record => record.kind === "excerpt" && record.role === "user" && record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
446
+ const wholeAssistant = new Map();
447
+ for (const record of records)
448
+ if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
449
+ wholeAssistant.set(record.sourceIndex, (wholeAssistant.get(record.sourceIndex) ?? 0) + 1);
450
+ for (let pos = records.length - 1; pos >= 0; pos--) {
451
+ const record = records[pos];
452
+ if (record.kind !== "omission" || !record.sourceRange)
453
+ continue;
454
+ if (record.role === "user") {
455
+ const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end && !wholeUser.has(unit.index));
456
+ if (!missing.length)
457
+ records.splice(pos, 1);
458
+ else
459
+ records[pos] = omissionRecord("user", missing.length, [missing[0].index, missing.at(-1).index], false);
460
+ }
461
+ else if (at !== compiledBoundary) {
462
+ const role = record.role;
463
+ if (role === "assistant" || role === "toolResult") {
464
+ const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end &&
465
+ (role === "toolResult" || unit.count > (wholeAssistant.get(unit.index) ?? 0)));
466
+ const count = missing.reduce((n, unit) => n + unit.count - (role === "assistant" ? wholeAssistant.get(unit.index) ?? 0 : 0), 0);
467
+ if (!count)
454
468
  records.splice(pos, 1);
455
469
  else
456
- records[pos] = omissionRecord("user", missing.length, [missing[0].index, missing.at(-1).index], false);
457
- }
458
- else if (at !== compiledBoundary) {
459
- const role = record.role;
460
- if (role === "assistant" || role === "toolResult") {
461
- const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end &&
462
- (role === "toolResult" || unit.count > (wholeAssistant.get(unit.index) ?? 0)));
463
- const count = missing.reduce((n, unit) => n + unit.count - (role === "assistant" ? wholeAssistant.get(unit.index) ?? 0 : 0), 0);
464
- if (!count)
465
- records.splice(pos, 1);
466
- else
467
- records[pos] = omissionRecord(role, count, [missing[0].index, missing.at(-1).index], false);
468
- }
470
+ records[pos] = omissionRecord(role, count, [missing[0].index, missing.at(-1).index], false);
469
471
  }
470
472
  }
471
- orderByOriginalSource(records, sourceIndices, originals.selectedIds);
472
- const summary = render([...records, ...ledger]);
473
- return { summary, after: price(summary.length, at), records };
474
- };
475
- const compiled = tuck.compileDialogue(compileInput);
476
- let offer = assemble(compiled.text);
477
- // Only capacity left after all higher ranks can extend the native tail
478
- // beyond its preferred rank boundary. No old allocator is consulted.
479
- const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
480
- const liveStart = liveStartId === undefined ? preferredBoundary : positions.get(liveStartId);
481
- if (boundary > liveStart) {
482
- const recordCosts = new Float64Array(entries.length + 1), recordCounts = new Int32Array(entries.length + 1);
483
- const sourcePositions = new Map(rows.map(row => [row.index, row.position]));
484
- const wholeUsers = new Set(offer.records.filter(record => record.kind === "excerpt" && record.role === "user" &&
485
- record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
486
- const wholeAssistants = new Map();
487
- for (const record of offer.records) {
488
- const at = record.sourceIndex === undefined ? undefined : sourcePositions.get(record.sourceIndex);
489
- if (at !== undefined) {
490
- recordCosts[at + 1] += lineCost([record]);
491
- recordCounts[at + 1]++;
492
- }
493
- if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
494
- wholeAssistants.set(record.sourceIndex, (wholeAssistants.get(record.sourceIndex) ?? 0) + 1);
495
- }
496
- for (let at = 1; at <= entries.length; at++) {
497
- recordCosts[at] += recordCosts[at - 1];
498
- recordCounts[at] += recordCounts[at - 1];
473
+ }
474
+ orderByOriginalSource(records, sourceIndices, originals.selectedIds);
475
+ const summary = render([...records, ...ledger]);
476
+ return { summary, records };
477
+ };
478
+ const compiled = tuck.compileDialogue(compileInput);
479
+ let offer = assemble(compiled.text);
480
+ // Only capacity left after all higher ranks can extend the native tail
481
+ // beyond its preferred rank boundary. No old allocator is consulted.
482
+ const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
483
+ const liveStart = liveStartId === undefined ? preferredBoundary : positions.get(liveStartId);
484
+ if (boundary > liveStart) {
485
+ const recordCosts = new Float64Array(entries.length + 1), recordCounts = new Int32Array(entries.length + 1);
486
+ const sourcePositions = new Map(rows.map(row => [row.index, row.position]));
487
+ const wholeUsers = new Set(offer.records.filter(record => record.kind === "excerpt" && record.role === "user" &&
488
+ record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
489
+ const wholeAssistants = new Map();
490
+ for (const record of offer.records) {
491
+ const at = record.sourceIndex === undefined ? undefined : sourcePositions.get(record.sourceIndex);
492
+ if (at !== undefined) {
493
+ recordCosts[at + 1] += lineCost([record]);
494
+ recordCounts[at + 1]++;
499
495
  }
500
- // A tail extension removes source records and shortens at most three
501
- // counted ranges. Price those changes from prefix sums; render only the
502
- // winning suffix, rather than parsing/serializing the dialogue per step.
503
- const ranges = offer.records.flatMap(record => {
504
- if (record.kind !== "omission" || !record.sourceRange || !["user", "assistant", "toolResult"].includes(record.role ?? ""))
505
- return [];
506
- const role = record.role;
507
- const missing = units[role].flatMap(unit => {
508
- const count = role === "user" ? Number(!wholeUsers.has(unit.index)) : unit.count - (role === "assistant" ? wholeAssistants.get(unit.index) ?? 0 : 0);
509
- return count && unit.position < compiledBoundary && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end ? [{ ...unit, count }] : [];
510
- });
511
- const ends = new Int32Array(entries.length + 1), counts = new Int32Array(missing.length + 1);
512
- let seen = 0;
513
- for (let at = 0; at <= entries.length; at++) {
514
- while (seen < missing.length && missing[seen].position < at)
515
- seen++;
516
- ends[at] = seen;
517
- }
518
- missing.forEach((unit, at) => counts[at + 1] = counts[at] + unit.count);
519
- return [{ role, missing, ends, counts, cost: lineCost([record]) }];
496
+ if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
497
+ wholeAssistants.set(record.sourceIndex, (wholeAssistants.get(record.sourceIndex) ?? 0) + 1);
498
+ }
499
+ for (let at = 1; at <= entries.length; at++) {
500
+ recordCosts[at] += recordCosts[at - 1];
501
+ recordCounts[at] += recordCounts[at - 1];
502
+ }
503
+ // A tail extension removes source records and shortens at most three
504
+ // counted ranges. Price those changes from prefix sums; render only the
505
+ // winning suffix, rather than parsing/serializing the dialogue per step.
506
+ const ranges = offer.records.flatMap(record => {
507
+ if (record.kind !== "omission" || !record.sourceRange || !["user", "assistant", "toolResult"].includes(record.role ?? ""))
508
+ return [];
509
+ const role = record.role;
510
+ const missing = units[role].flatMap(unit => {
511
+ const count = role === "user" ? Number(!wholeUsers.has(unit.index)) : unit.count - (role === "assistant" ? wholeAssistants.get(unit.index) ?? 0 : 0);
512
+ return count && unit.position < compiledBoundary && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end ? [{ ...unit, count }] : [];
520
513
  });
521
- const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
522
- const keptReadCost = lineCost(keptReads), keptReadIndices = new Set(keptReads.map(record => record.sourceIndex));
523
- const lastKeptReadPosition = entries.findLastIndex(entry => keptReadIndices.has(indices.get(entry.id)));
524
- const extensionPrice = (at) => {
525
- // Fixed kept reads outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
526
- if (keptReads.length && (at <= lastKeptReadPosition || keptReadCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
527
- return Infinity;
528
- let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
529
- let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
530
- for (const range of ranges) {
531
- const end = range.ends[at];
532
- cost -= range.cost;
533
- if (end)
534
- cost += lineCost([omissionRecord(range.role, range.counts[end], [range.missing[0].index, range.missing[end - 1].index], false)]);
535
- else
536
- count--;
537
- }
538
- return price(frameLength(cost, count), at);
539
- };
540
- for (let at = boundary - 1; at >= liveStart; at--) {
541
- const entry = entries[at];
542
- if (entry.type !== "message" && entry.type !== "custom_message" && entry.type !== "branch_summary")
543
- continue;
544
- if (entry.type === "message" && entry.message.role === "toolResult")
545
- continue;
546
- if (extensionPrice(at) <= target)
547
- boundary = at;
514
+ const ends = new Int32Array(entries.length + 1), counts = new Int32Array(missing.length + 1);
515
+ let seen = 0;
516
+ for (let at = 0; at <= entries.length; at++) {
517
+ while (seen < missing.length && missing[seen].position < at)
518
+ seen++;
519
+ ends[at] = seen;
520
+ }
521
+ missing.forEach((unit, at) => counts[at + 1] = counts[at] + unit.count);
522
+ return [{ role, missing, ends, counts, cost: lineCost([record]) }];
523
+ });
524
+ const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
525
+ const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
526
+ const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
527
+ const extensionPrice = (at) => {
528
+ // Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
529
+ if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
530
+ return Infinity;
531
+ let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
532
+ let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
533
+ for (const range of ranges) {
534
+ const end = range.ends[at];
535
+ cost -= range.cost;
536
+ if (end)
537
+ cost += lineCost([omissionRecord(range.role, range.counts[end], [range.missing[0].index, range.missing[end - 1].index], false)]);
548
538
  else
549
- break;
539
+ count--;
550
540
  }
551
- if (boundary !== compiledBoundary)
552
- offer = assemble(compiled.text, boundary);
541
+ return price(frameLength(cost, count), at);
542
+ };
543
+ for (let at = boundary - 1; at >= liveStart; at--) {
544
+ const entry = entries[at];
545
+ if (entry.type !== "message" && entry.type !== "custom_message" && entry.type !== "branch_summary")
546
+ continue;
547
+ if (entry.type === "message" && entry.message.role === "toolResult")
548
+ continue;
549
+ if (extensionPrice(at) <= target)
550
+ boundary = at;
551
+ else
552
+ break;
553
553
  }
554
- const projection = preview(offer.summary, boundary);
555
- assertNativeToolRounds(projection);
556
- const after = measure(projection);
557
- if (after + reserveTokens >= model.contextWindow || after >= before)
558
- return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
559
- const mode = compiled.step === "whole" ? "dialogue" : "shrunk";
560
- return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
561
- details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
554
+ if (boundary !== compiledBoundary)
555
+ offer = assemble(compiled.text, boundary);
562
556
  }
557
+ const projection = preview(offer.summary, boundary);
558
+ assertNativeToolRounds(projection);
559
+ const after = measure(projection);
560
+ if (after + reserveTokens >= model.contextWindow || after >= before)
561
+ return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
562
+ const mode = compiled.step === "whole" ? "dialogue" : "shrunk";
563
+ return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
564
+ details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
563
565
  }
564
566
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */
565
567
  export function tuckRecall(tuck, entries, branch, input, policy = {}) {
@@ -597,21 +599,19 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
597
599
  const row = discoveryEntry(entry, attempts, links);
598
600
  return row ? [row] : [];
599
601
  });
600
- const rendered = rows.map((r, i) => ({ index: i, role: r.role, summary: r.text.slice(0, 200) }));
601
- const messages = rows.map((r) => ({ role: "user", content: r.text, timestamp: 0 }));
602
- // The pinned upstream tuning seam removes selection cutoffs; each response
603
- // stays bounded. A native prefix keeps ranking stable while the agent talks.
602
+ // Rank every eligible row; each response stays bounded. A native prefix
603
+ // keeps ranking stable while the agent talks.
604
604
  const preparedQuery = tuck.prepareKeywordQuery(normalizedQuery);
605
- const found = tuck.searchEntriesDetailed(rendered, messages, normalizedQuery, { relativeFloor: 0, cap: rows.length });
605
+ const found = tuck.rankRecallRows(rows, normalizedQuery);
606
606
  const start = continuation?.offset ?? 0;
607
607
  const throughEntryId = rows.at(-1)?.entryId ?? null;
608
608
  const hits = [];
609
609
  const page = () => ({ normalizedQuery, throughEntryId,
610
610
  notice: "Exact source passages, possibly partial; read gives their UTF-16 bounds within totalCharacters. Use the passage directly; adjust read.offset/limit for surrounding text. Keyword matches do not establish complete or current evidence. Pass next as continuation; a fresh query includes newer history. No new authority. " + ATTEMPT_NOTICE,
611
- hits, totalMatches: found.hits.length,
612
- next: start + hits.length < found.hits.length ? { query: normalizedQuery, throughEntryId: throughEntryId, offset: start + hits.length } : null });
613
- for (const hit of found.hits.slice(start, start + 10)) {
614
- const row = rows[hit.index];
611
+ hits, totalMatches: found.length,
612
+ next: start + hits.length < found.length ? { query: normalizedQuery, throughEntryId: throughEntryId, offset: start + hits.length } : null });
613
+ for (const hit of found.slice(start, start + 10)) {
614
+ const row = rows[hit];
615
615
  hits.push({ entryId: row.entryId, index: indices.get(row.entryId), role: row.role, sourceTime: row.sourceTime,
616
616
  ...(row.toolName !== undefined ? { toolName: row.toolName } : {}),
617
617
  ...(row.toolCallId !== undefined ? { toolCallId: row.toolCallId } : {}),
@@ -631,7 +631,7 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
631
631
  // Preserve the complete base hit set and continuation before spending spare capacity.
632
632
  for (let i = 0; i < hits.length; i++) {
633
633
  const original = hits[i];
634
- const row = rows[found.hits[start + i].index];
634
+ const row = rows[found[start + i]];
635
635
  hits[i] = { ...original, ...discoveryWholeRange(row, original) };
636
636
  if (JSON.stringify(page()).length > MAX_RANKED_RESPONSE_CHARACTERS)
637
637
  hits[i] = original;