pi-tuck 1.0.32 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,46 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.1.0] - 2026-11-13
7
+
8
+ ### Added
9
+
10
+ - **A cut's summary now carries the files the session last read and has not changed since.** After a cut, agents often doubted what an
11
+ earlier read had shown and read the same file again, even though no edit had touched it. The summary now includes, after the Files
12
+ list, the newest whole read of each file that has no later write or edit, headed `read PATH (as recorded at #N; no write or edit
13
+ recorded since):`. It keeps at most 4 files, whole outputs only, within 20% of the summary's room and never more than 24,000
14
+ characters. When the summary is over its target these records are dropped first, oldest first. With no such reads the summary is
15
+ unchanged. Tool outputs are never touched.
16
+
17
+ ### Release gates
18
+
19
+ - **Shipped before its Tier 1, on a 5-task gate.** The Tier 1 runs after release against 1.0.33; if it fails, npm and installs go back
20
+ to 1.0.33.
21
+ - **5-task check against 1.0.31:** no breakage in 5 of 5; re-checks after a doubt 22 against 45; doubt moments 9 against 24; cuts 22
22
+ against 26; turns 305 against 384; all 5 solved on both. One heavy task went worse: 90 turns against 59, 9 cuts against 4, 3 doubts
23
+ against 1.
24
+ - **Replay against 1.0.33:** 13,946 requests. In every recording that differs, the first difference is the first summary carrying one of
25
+ these records; 11 of 29 never differ. 0 lost or dead tasks, clips 17 → 16, cuts 1,946 → 1,971 (larger summaries bring later cuts
26
+ sooner).
27
+ - **Strict stress, 313 cells:** 0 findings on Pi 1.2.0 and the newest Pi, including the large-session test. Tests and CI. The packed
28
+ tarball loaded in the real installed Pi 1.5.2.
29
+
30
+ ## [1.0.33] - 2026-11-13
31
+
32
+ ### Fixed
33
+
34
+ - **A file read's recall number pointed at the read call, not at what the read returned.** The summary lists each file the session read
35
+ with a tuck_recall number. That number brought back the call's arguments instead of the file's contents, so recalling a read cost a
36
+ turn and showed nothing useful. It now brings back the read's output.
37
+
38
+ ### Release gates
39
+
40
+ - **Shipped without a live gate under the defect rule.** Replay against 1.0.31, with the read numbers set aside: 13,946 requests, 13,855
41
+ identical, 51 differing only in what the summary had room for, 40 noise, 0 unexplained, 0 lost or dead tasks, clips 17 → 17. The
42
+ fix also ran, inside a larger candidate, through 4 live tasks with no breakage.
43
+ - **Strict stress, 313 cells:** 0 findings on Pi 1.2.0 and the newest Pi. Tests and CI. The packed tarball loaded in the real installed
44
+ Pi 1.5.2.
45
+
6
46
  ## [1.0.32] - 2026-11-13
7
47
 
8
48
  ### Changed
@@ -1 +1 @@
1
- export declare const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
1
+ export declare const BUILD_ID = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
@@ -1 +1 @@
1
- export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
1
+ export const BUILD_ID = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
3
+ export declare const DIAGNOSTIC_BUILD = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -0,0 +1,4 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
+ export declare function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
@@ -0,0 +1,40 @@
1
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
2
+ import { extractPath } from "./tuck/core/tool-args.js";
3
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
+ export function keptReadCandidates(entries, indices, resolvable) {
5
+ const reads = new Map(), mutations = new Map();
6
+ let order = 0;
7
+ for (const entry of entries) {
8
+ if (entry.type !== "message" || entry.message.role !== "assistant")
9
+ continue;
10
+ for (const block of entry.message.content) {
11
+ if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
12
+ !block.arguments || typeof block.arguments !== "object")
13
+ continue;
14
+ const path = extractPath(block.arguments);
15
+ if (!path || /[\r\n]/u.test(path))
16
+ continue;
17
+ order++;
18
+ if (block.name === "read")
19
+ reads.set(block.id, { path, order });
20
+ else
21
+ mutations.set(path, order);
22
+ }
23
+ }
24
+ const seen = new Set(), records = [];
25
+ for (let at = entries.length - 1; at >= 0; at--) {
26
+ const entry = entries[at];
27
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
28
+ continue;
29
+ const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
30
+ if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order)
31
+ continue;
32
+ const text = textOf(entry.message.content);
33
+ if (!text.length || sourceIndex === undefined || !resolvable(entry))
34
+ continue;
35
+ seen.add(read.path);
36
+ records.push({ kind: "section", title: "Kept-read", sourceIndex,
37
+ text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
38
+ }
39
+ return records;
40
+ }
@@ -5,12 +5,15 @@ export declare const MAX_LEDGER_LINES = 60;
5
5
  export declare const LEDGER_HEADING = "Files touched by read, write and edit before this summary, newest first, with the last operation:";
6
6
  /** Never ends inside a surrogate pair, so the head is an exact prefix of whole code points. */
7
7
  export declare const head: (text: string, max: number) => string;
8
- /** One distinct path and its last recorded operation. `sourceIndex` is the entry holding that call;
9
- * `resolvable` says tuck_recall {index} reads it, so only then is the index shown as a locator. */
8
+ /** One distinct path and its last recorded operation. `sourceIndex` is the entry holding that call (the line's own index, so a native
9
+ * omission of the call removes the line). `locatorIndex` is the entry an agent wants back: for a read, the one holding its result (what
10
+ * the file showed; a live check, 2026-11-12: an agent asked for "#13" and got the call); for a write or edit, the call (what was written).
11
+ * `resolvable` says tuck_recall {index} reads the locator, so only then is it shown. A read whose result is missing points at its call. */
10
12
  export interface LedgerItem {
11
13
  path: string;
12
14
  operation: "wrote/edited" | "read";
13
15
  sourceIndex?: number;
16
+ locatorIndex?: number;
14
17
  resolvable: boolean;
15
18
  }
16
19
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
@@ -15,6 +15,10 @@ export const head = (text, max) => {
15
15
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
16
16
  * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
17
17
  export function ledgerItems(entries, indices, resolvable, failedCalls) {
18
+ const results = new Map();
19
+ for (const entry of entries)
20
+ if (entry.type === "message" && entry.message.role === "toolResult")
21
+ results.set(entry.message.toolCallId, entry);
18
22
  const last = new Map();
19
23
  for (const entry of entries) {
20
24
  if (entry.type !== "message" || entry.message.role !== "assistant")
@@ -29,14 +33,14 @@ export function ledgerItems(entries, indices, resolvable, failedCalls) {
29
33
  if (!operation || !path || /[\r\n]/u.test(path) || operation === "wrote/edited" && failedCalls.has(block.id))
30
34
  continue;
31
35
  last.delete(path);
32
- last.set(path, { path, operation, entry });
36
+ last.set(path, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
33
37
  }
34
38
  }
35
39
  // Only listed lines show a locator, so resolvability (which renders the entry) is checked for those alone.
36
- return [...last.values()].reverse().map(({ path, operation, entry }, rank) => {
37
- const sourceIndex = indices.get(entry.id);
38
- return { path, operation, ...(sourceIndex !== undefined ? { sourceIndex } : {}),
39
- resolvable: rank < MAX_LEDGER_LINES && sourceIndex !== undefined && resolvable(entry) };
40
+ return [...last.values()].reverse().map(({ path, operation, entry, target }, rank) => {
41
+ const sourceIndex = indices.get(entry.id), locatorIndex = indices.get(target.id);
42
+ return { path, operation, ...(sourceIndex !== undefined ? { sourceIndex } : {}), ...(locatorIndex !== undefined ? { locatorIndex } : {}),
43
+ resolvable: rank < MAX_LEDGER_LINES && sourceIndex !== undefined && locatorIndex !== undefined && resolvable(target) };
40
44
  });
41
45
  }
42
46
  /** The ledger: a heading, one record per listed path (at most `keep` and the line cap, newest first), then a count of the older ones.
@@ -45,7 +49,7 @@ export function ledgerRecords(items, keep = items.length) {
45
49
  const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_LEDGER_LINES)));
46
50
  const line = (text, sourceIndex) => ({ kind: "section", title: LEDGER_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
47
51
  return [line(LEDGER_HEADING),
48
- ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.sourceIndex}})` : ""), item.sourceIndex)),
52
+ ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : ""), item.sourceIndex)),
49
53
  ...(items.length ? [] : [line("(none)")]),
50
54
  ...(listed.length < items.length ? [line(`+${items.length - listed.length} older files: use tuck_recall`)] : [])];
51
55
  }
@@ -57,7 +57,7 @@ const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall",
57
57
  * or, with no role, of the tool history
58
58
  * | role " omitted " count " #" index "-#" index ":" ... counted inclusive index range
59
59
  * | role " omitted " count [ " " locator-time { " " locator-time } ] ":" ... omission of unselected text blocks
60
- * | [ locator " " ] title ":" ... section (file ledger, action trail)
60
+ * | [ locator " " ] title ":" ... section (Files, Actions, Kept-read)
61
61
  * locator = "#" index the source's session-wide index, as tuck_recall {"index"} takes it
62
62
  * locator-time = locator [ "@" time-value ] every locator of a record has a time, or none does
63
63
  * role = "user" | "assistant" | "custom" | "toolResult" (omissions only)
package/dist/src/tuck.js CHANGED
@@ -7,6 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.j
7
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
+ import { keptReadCandidates } from "./kept-reads.js";
10
11
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
11
12
  import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
12
13
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
@@ -376,9 +377,26 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
376
377
  let { boundary, high: protectedView } = selected;
377
378
  const sourceRows = rows.filter(row => row.position < boundary);
378
379
  const lists = listsAt(boundary);
379
- let ledger = lists.records;
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)
387
+ continue;
388
+ keptReads.push(record);
389
+ allowance -= cost;
390
+ if (keptReads.length === 4)
391
+ break;
392
+ }
393
+ let ledger = [...lists.records, ...keptReads];
380
394
  // List caps are existing ranking policy; only the carried target is a
381
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];
399
+ }
382
400
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
383
401
  ledger = [];
384
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++) {
@@ -392,7 +410,6 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
392
410
  return row?.message.role === "user" && isTextOnly(row.message.content);
393
411
  }));
394
412
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
395
- const maxSummaryCharacters = Math.floor((target - offset - nativeAt(boundary)) * 4) - wrapperCharacters;
396
413
  const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
397
414
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
398
415
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(byId.get(row.id))),
@@ -502,7 +519,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
502
519
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
503
520
  });
504
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)));
505
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;
506
528
  let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
507
529
  let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
508
530
  for (const range of ranges) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.0.32",
3
+ "version": "1.1.0",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history. Search by meaning on Apple silicon.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
1
+ export const BUILD_ID = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
@@ -0,0 +1,36 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { isTextOnly, textOf } from "./tuck/core/content";
3
+ import { extractPath } from "./tuck/core/tool-args";
4
+ import type { TranscriptRecord } from "./tuck/core/transcript";
5
+
6
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
7
+ export function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>,
8
+ resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
9
+ const reads = new Map<string, { path: string; order: number }>(), mutations = new Map<string, number>();
10
+ let order = 0;
11
+ for (const entry of entries) {
12
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
13
+ for (const block of entry.message.content) {
14
+ if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
15
+ !block.arguments || typeof block.arguments !== "object") continue;
16
+ const path = extractPath(block.arguments as Record<string, unknown>);
17
+ if (!path || /[\r\n]/u.test(path)) continue;
18
+ order++;
19
+ if (block.name === "read") reads.set(block.id, { path, order });
20
+ else mutations.set(path, order);
21
+ }
22
+ }
23
+ const seen = new Set<string>(), records: TranscriptRecord[] = [];
24
+ for (let at = entries.length - 1; at >= 0; at--) {
25
+ const entry = entries[at]!;
26
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
27
+ const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
28
+ if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order) continue;
29
+ const text = textOf(entry.message.content);
30
+ if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
31
+ seen.add(read.path);
32
+ records.push({ kind: "section", title: "Kept-read", sourceIndex,
33
+ text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
34
+ }
35
+ return records;
36
+ }
package/src/ledger.ts CHANGED
@@ -16,15 +16,19 @@ export const head = (text: string, max: number): string => {
16
16
  return text.slice(0, /[\uD800-\uDBFF]/u.test(text[max - 1]!) ? max - 1 : max);
17
17
  };
18
18
 
19
- /** One distinct path and its last recorded operation. `sourceIndex` is the entry holding that call;
20
- * `resolvable` says tuck_recall {index} reads it, so only then is the index shown as a locator. */
21
- export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; resolvable: boolean }
19
+ /** One distinct path and its last recorded operation. `sourceIndex` is the entry holding that call (the line's own index, so a native
20
+ * omission of the call removes the line). `locatorIndex` is the entry an agent wants back: for a read, the one holding its result (what
21
+ * the file showed; a live check, 2026-11-12: an agent asked for "#13" and got the call); for a write or edit, the call (what was written).
22
+ * `resolvable` says tuck_recall {index} reads the locator, so only then is it shown. A read whose result is missing points at its call. */
23
+ export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; locatorIndex?: number; resolvable: boolean }
22
24
 
23
25
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
24
26
  * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
25
27
  export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
26
28
  failedCalls: ReadonlySet<string>): LedgerItem[] {
27
- const last = new Map<string, { path: string; operation: LedgerItem["operation"]; entry: SessionEntry }>();
29
+ const results = new Map<string, SessionEntry>();
30
+ for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
31
+ const last = new Map<string, { path: string; operation: LedgerItem["operation"]; entry: SessionEntry; target: SessionEntry }>();
28
32
  for (const entry of entries) {
29
33
  if (entry.type !== "message" || entry.message.role !== "assistant") continue;
30
34
  if (isDiscardedResponse(entry.message)) continue;
@@ -34,14 +38,14 @@ export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyM
34
38
  const path = operation && extractPath(block.arguments as Record<string, unknown>);
35
39
  if (!operation || !path || /[\r\n]/u.test(path) || operation === "wrote/edited" && failedCalls.has(block.id)) continue;
36
40
  last.delete(path);
37
- last.set(path, { path, operation, entry });
41
+ last.set(path, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
38
42
  }
39
43
  }
40
44
  // Only listed lines show a locator, so resolvability (which renders the entry) is checked for those alone.
41
- return [...last.values()].reverse().map(({ path, operation, entry }, rank) => {
42
- const sourceIndex = indices.get(entry.id);
43
- return { path, operation, ...(sourceIndex !== undefined ? { sourceIndex } : {}),
44
- resolvable: rank < MAX_LEDGER_LINES && sourceIndex !== undefined && resolvable(entry) };
45
+ return [...last.values()].reverse().map(({ path, operation, entry, target }, rank) => {
46
+ const sourceIndex = indices.get(entry.id), locatorIndex = indices.get(target.id);
47
+ return { path, operation, ...(sourceIndex !== undefined ? { sourceIndex } : {}), ...(locatorIndex !== undefined ? { locatorIndex } : {}),
48
+ resolvable: rank < MAX_LEDGER_LINES && sourceIndex !== undefined && locatorIndex !== undefined && resolvable(target) };
45
49
  });
46
50
  }
47
51
 
@@ -51,7 +55,7 @@ export function ledgerRecords(items: readonly LedgerItem[], keep = items.length)
51
55
  const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_LEDGER_LINES)));
52
56
  const line = (text: string, sourceIndex?: number): TranscriptRecord => ({ kind: "section", title: LEDGER_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
53
57
  return [line(LEDGER_HEADING),
54
- ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.sourceIndex}})` : ""), item.sourceIndex)),
58
+ ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : ""), item.sourceIndex)),
55
59
  ...(items.length ? [] : [line("(none)")]),
56
60
  ...(listed.length < items.length ? [line(`+${items.length - listed.length} older files: use tuck_recall`)] : [])];
57
61
  }
@@ -83,7 +83,7 @@ const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall",
83
83
  * or, with no role, of the tool history
84
84
  * | role " omitted " count " #" index "-#" index ":" ... counted inclusive index range
85
85
  * | role " omitted " count [ " " locator-time { " " locator-time } ] ":" ... omission of unselected text blocks
86
- * | [ locator " " ] title ":" ... section (file ledger, action trail)
86
+ * | [ locator " " ] title ":" ... section (Files, Actions, Kept-read)
87
87
  * locator = "#" index the source's session-wide index, as tuck_recall {"index"} takes it
88
88
  * locator-time = locator [ "@" time-value ] every locator of a record has a time, or none does
89
89
  * role = "user" | "assistant" | "custom" | "toolResult" (omissions only)
package/src/tuck.ts CHANGED
@@ -7,6 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
+ import { keptReadCandidates } from "./kept-reads.js";
10
11
  import type { Message } from "@earendil-works/pi-ai";
11
12
  import { convertToLlm, SessionManager, type ExtensionContext,
12
13
  type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
@@ -362,9 +363,23 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
362
363
  let { boundary, high: protectedView } = selected;
363
364
  const sourceRows = rows.filter(row => row.position < boundary);
364
365
  const lists = listsAt(boundary);
365
- let ledger: TranscriptRecord[] = lists.records;
366
+ const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
367
+ const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
368
+ let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
369
+ const keptReads: TranscriptRecord[] = [];
370
+ for (const record of keptReadCandidates(entries.slice(0, boundary), indices, entry => readable(entry) !== undefined)) {
371
+ const cost = lineCost([record]);
372
+ if (cost > allowance) continue;
373
+ keptReads.push(record); allowance -= cost;
374
+ if (keptReads.length === 4) break;
375
+ }
376
+ let ledger: TranscriptRecord[] = [...lists.records, ...keptReads];
366
377
  // List caps are existing ranking policy; only the carried target is a
367
378
  // spending limit. Candidate list sizes have fixed, cached line prices.
379
+ while (keptReads.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
380
+ keptReads.pop();
381
+ ledger = [...lists.records, ...keptReads];
382
+ }
368
383
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
369
384
  ledger = [];
370
385
  for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
@@ -377,7 +392,6 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
377
392
  return row?.message.role === "user" && isTextOnly(row.message.content);
378
393
  }));
379
394
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
380
- const maxSummaryCharacters = Math.floor((target - offset - nativeAt(boundary)) * 4) - wrapperCharacters;
381
395
  const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
382
396
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
383
397
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(byId.get(row.id)!)),
@@ -472,7 +486,11 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
472
486
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
473
487
  });
474
488
  const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
489
+ const keptReadCost = lineCost(keptReads), keptReadIndices = new Set(keptReads.map(record => record.sourceIndex));
490
+ const lastKeptReadPosition = entries.findLastIndex(entry => keptReadIndices.has(indices.get(entry.id)));
475
491
  const extensionPrice = (at: number) => {
492
+ // Fixed kept reads outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
493
+ if (keptReads.length && (at <= lastKeptReadPosition || keptReadCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000))) return Infinity;
476
494
  let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
477
495
  let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
478
496
  for (const range of ranges) {