pi-tuck 1.7.0 → 1.9.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,38 @@
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.9.0]
7
+
8
+ ### Changed
9
+
10
+ - At large windows pi-tuck now trims more often, to keep each request small: in a simulation of 25 sessions at a 272k window it made
11
+ about five times the trims of 1.8.0 (20.7 per session against 3.8) and cut simulated request cost by about 41% against native Pi. Each
12
+ trim drops older context, so a long session sees more summaries than before. At small windows (32k) behavior is essentially unchanged.
13
+ - Lean trigger: once a session has trimmed and made at least five requests since, the trim point can move earlier, to K + sqrt(2(K + R)·δ / 0.1),
14
+ where K is what the latest trim left, δ the mean growth per request and R the mean tokens of unchanged re-reads soon after each trim. It
15
+ balances the cost of a trim against the cost of carrying a larger context each request. It never moves the trim point later than
16
+ 1.8.0's, it is off with an explicit `cutAt`, a host reserve or a protected prefix, and admission is unchanged.
17
+ - Prefix-stable summary: a trim's summary begins with the previous summary's dialogue records, byte for byte, and adds the messages
18
+ trimmed since after them; the omission counts, lists and kept results follow the dialogue. Consecutive summaries then share their
19
+ longest possible prefix, which a provider's prompt cache can serve. When the new messages do not fit whole and the carried part leaves
20
+ them less than half of the summary's room, the carried part keeps only its prompts (and drops its oldest ones past half the room), so a
21
+ summary still makes room for recent work. Sessions without an earlier pi-tuck summary are summarized as before.
22
+ - `/tuck` names the line that sets the trim point when it is not the default: the lean line or the thrash line (native Pi's).
23
+
24
+ ## [1.8.0]
25
+
26
+ ### Changed
27
+
28
+ - Working files: at a trim, the files the agent has read more than once are carried whole, verbatim, after the summary's closing words,
29
+ most reads first, then the most recent. A file is carried only when its last read covered the whole file and the file on disk still holds
30
+ exactly that text, so a change by any means (an edit, a shell command, a generator) keeps it out. They are paid for from the summary
31
+ (at most two thirds of it beyond the protected prompts), never from the kept recent messages. The "re-read a file before editing it"
32
+ rule no longer applies to carried files; it stays for every other file.
33
+ - Thrash-adaptive trigger: when a session's trims keep dropping files the agent then reads again unchanged within three replies (half a
34
+ re-read or more per trim), the trim point moves to native Pi's line, the larger of the band and `keepRecentTokens`, capped so the next
35
+ reply keeps its room (at least 3,584 tokens, or 1.7.0's raised room after a length stop). Trims still cut to the band. Sessions without
36
+ such re-reads, an explicit `cutAt`, or a host reserve keep 1.7.0's trim point. Admission is unchanged.
37
+
6
38
  ## [1.7.0]
7
39
 
8
40
  ### Changed
package/README.md CHANGED
@@ -12,12 +12,16 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.6.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.6.0` or `pi install git:github.com/galyavin/pi-tuck@v1.6.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.9.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.9.0` or `pi install git:github.com/galyavin/pi-tuck@v1.9.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
19
19
  A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
20
20
 
21
+ Files the agent has read more than once are carried whole after the summary, most-read first, as far as a share of the summary allows. A file is carried only when its last read covered the whole file and the file on disk still holds exactly that text; the agent can edit from a carried copy without re-reading it. When a session's cuts keep dropping files the agent then reads again unchanged, pi-tuck moves its trim point later, to native Pi's (the larger of the room and `keepRecentTokens`), while keeping room for the next reply. Cuts still trim to the usual size.
22
+
23
+ Once a session has trimmed and grown for a few requests, pi-tuck can move its trim point earlier, to the line that balances the cost of a trim (the summary and the re-reads that follow) against the cost of carrying a larger context on every request. At large windows this means more, smaller trims and smaller requests; it never trims later than the default line. Each summary begins with the previous summary's dialogue, unchanged, and adds what was trimmed since, so consecutive summaries share a prefix a provider's prompt cache can serve. `/tuck` names the line in use: the default, the lean line, or native Pi's line.
24
+
21
25
  When pi-tuck is active, `tuck_recall` becomes available after a cut on the current branch. Use a keyword query to locate a passage.
22
26
 
23
27
  ```json
@@ -125,11 +125,15 @@ export type Gate = {
125
125
  kind: "plan";
126
126
  opportunistic: boolean;
127
127
  };
128
+ /** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. `lean`, when below that line, moves
129
+ * it down: a cut becomes due there too, as an opportunistic cut inside the band. */
128
130
  export declare function gateCut(input: {
129
131
  total: number;
130
132
  mandatory: number;
131
133
  room: number;
132
134
  band: number;
135
+ trigger?: number;
136
+ lean?: number;
133
137
  fits: CutInput["fits"];
134
138
  }): Gate;
135
139
  /** Whether and how to cut at one boundary: the only decision procedure both triggers use. */
@@ -105,9 +105,11 @@ export function chooseCut(input) {
105
105
  return { kind: "fault", capacity: !fits(chosen.after + mandatory, room), message: unreduced };
106
106
  return { kind: "cut", target, plan: chosen };
107
107
  }
108
+ /** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. `lean`, when below that line, moves
109
+ * it down: a cut becomes due there too, as an opportunistic cut inside the band. */
108
110
  export function gateCut(input) {
109
111
  const { total, mandatory, room, band, fits } = input;
110
- if (fits(total, band))
112
+ if (fits(total, Math.min(Math.max(band, input.trigger ?? band), input.lean ?? Infinity)))
111
113
  return { kind: "none" };
112
114
  const inBand = fits(total, room);
113
115
  if (!fits(mandatory, room))
@@ -1 +1 @@
1
- export declare const BUILD_ID = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
1
+ export declare const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
@@ -1 +1 @@
1
- export const BUILD_ID = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
1
+ export const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
@@ -12,13 +12,15 @@ import { isDeepStrictEqual } from "node:util";
12
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
13
13
  import { projectedMessages } from "./omissions.js";
14
14
  import { applyClips, clipBudgets, clipFor } from "./clip.js";
15
- import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
15
+ import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
16
16
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
17
17
  import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
18
18
  import { Type } from "typebox";
19
19
  import { Check } from "typebox/value";
20
20
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
21
21
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
22
+ import { thrashing } from "./thrash.js";
23
+ import { leanLine } from "./lean.js";
22
24
  import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
23
25
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
24
26
  import { notify } from "./notify.js";
@@ -213,7 +215,7 @@ export async function installCompaction(pi, options = {}) {
213
215
  pi.on("session_compact", (_event, ctx) => observe(ctx));
214
216
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
215
217
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
216
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
218
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx), trigger: activeTrigger(ctx) }), "info");
217
219
  } });
218
220
  // Pi's native start/settled events bracket the run and its post-turn cuts.
219
221
  let run;
@@ -403,18 +405,57 @@ export async function installCompaction(pi, options = {}) {
403
405
  const preservePrefix = (ctx) => ctx.model !== undefined &&
404
406
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
405
407
  const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
408
+ // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
409
+ // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
410
+ // Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
411
+ // room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
412
+ // sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
413
+ const triggerLine = (ctx, room) => {
414
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
415
+ return undefined;
416
+ const branch = ctx.sessionManager.getBranch();
417
+ if (!thrashing(branch))
418
+ return undefined;
419
+ const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
420
+ const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
421
+ const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
422
+ return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
423
+ };
424
+ // Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
425
+ // economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
426
+ // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
427
+ const leanLimit = (ctx) => {
428
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
429
+ return undefined;
430
+ return leanLine(ctx.sessionManager.getBranch());
431
+ };
432
+ // A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
433
+ const usefulOnlyAt = (total, band, lean, ctx) => options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
406
434
  /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
407
435
  const cutPoint = (ctx) => {
408
436
  if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
409
437
  return undefined;
410
438
  try {
411
- const band = decisionBand(ctx, limits(ctx).room);
439
+ const { room } = limits(ctx), band = Math.min(Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0), leanLimit(ctx) ?? Infinity);
412
440
  return band > 0 ? band : undefined;
413
441
  }
414
442
  catch {
415
443
  return undefined;
416
444
  }
417
445
  };
446
+ /** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
447
+ const activeTrigger = (ctx) => {
448
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
449
+ return undefined;
450
+ try {
451
+ const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
452
+ const line = Math.max(band, thrash ?? 0);
453
+ return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
454
+ }
455
+ catch {
456
+ return undefined;
457
+ }
458
+ };
418
459
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
419
460
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
420
461
  const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
@@ -647,15 +688,16 @@ export async function installCompaction(pi, options = {}) {
647
688
  // trigger would: nothing below the band, an opportunistic cut inside it, a due cut at or above the room. A refusal is a plain
648
689
  // cancel (Pi reports it as aborted), never a failure.
649
690
  let thresholdOpportunistic = false;
691
+ const lean = leanLimit(ctx);
650
692
  if (event.reason === "threshold") {
651
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
693
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
652
694
  if (gate.kind !== "plan")
653
695
  return { cancel: true };
654
696
  thresholdOpportunistic = gate.opportunistic;
655
697
  }
656
698
  // Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
657
699
  const decide = (targetRoom = room, targetBand = band) => chooseCut({
658
- before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
700
+ before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
659
701
  opportunistic: thresholdOpportunistic,
660
702
  unreduced: "Compaction did not reduce context within the estimated request budget",
661
703
  plan: (target) => {
@@ -821,12 +863,13 @@ export async function installCompaction(pi, options = {}) {
821
863
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
822
864
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
823
865
  // help: leave it to the complete-context guard, which fails closed.
824
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
866
+ const lean = leanLimit(ctx);
867
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
825
868
  if (gate.kind === "none")
826
869
  return;
827
870
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
828
871
  const decide = (targetRoom, targetBand, opportunistic) => chooseCut({
829
- before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined, opportunistic,
872
+ before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
830
873
  unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
831
874
  plan: (target) => {
832
875
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
@@ -974,13 +1017,13 @@ export async function installCompaction(pi, options = {}) {
974
1017
  const decide = (targetRoom = room, targetBand = band, required = false) => {
975
1018
  previews = [];
976
1019
  floorKept = undefined;
977
- const before = measure(saved);
1020
+ const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
978
1021
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
979
- gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
1022
+ gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
980
1023
  if (gate.kind !== "plan")
981
1024
  return gate;
982
1025
  return chooseCut({
983
- opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
1026
+ opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
984
1027
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
985
1028
  plan: (target) => {
986
1029
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
@@ -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 = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
3
+ export declare const DIAGNOSTIC_BUILD = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -1,4 +1,4 @@
1
1
  import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
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 | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
4
+ export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
@@ -3,7 +3,7 @@ import { pathKey } from "./path-key.js";
3
3
  import { isTextOnly, textOf } from "./tuck/core/content.js";
4
4
  import { extractPath } from "./tuck/core/tool-args.js";
5
5
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
6
- export function keptReadCandidates(entries, indices, resolvable) {
6
+ export function keptReadCandidates(entries, indices, resolvable, exclude = new Set()) {
7
7
  const cwd = entries.find((entry) => entry.type === "session")?.cwd;
8
8
  const reads = new Map(), mutations = new Map();
9
9
  let allMutated = -1;
@@ -54,7 +54,7 @@ export function keptReadCandidates(entries, indices, resolvable) {
54
54
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
55
55
  continue;
56
56
  const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
57
- if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
57
+ if (!read || seen.has(read.key) || exclude.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
58
58
  continue;
59
59
  const text = textOf(entry.message.content);
60
60
  if (!text.length || sourceIndex === undefined || !resolvable(entry))
@@ -0,0 +1,23 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ /** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
3
+ export declare const LEAN_HOLDING = 0.1;
4
+ /** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
5
+ export declare const LEAN_MIN_SAMPLES = 4;
6
+ export interface LeanInputs {
7
+ kept: number;
8
+ growth: number;
9
+ rereads: number;
10
+ samples: number;
11
+ cuts: number;
12
+ }
13
+ /** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
14
+ * the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
15
+ * consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
16
+ export declare function leanInputs(branch: readonly SessionEntry[]): LeanInputs;
17
+ /**
18
+ * The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
19
+ * (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
20
+ * n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
21
+ * Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
22
+ */
23
+ export declare function leanLine(branch: readonly SessionEntry[]): number | undefined;
@@ -0,0 +1,55 @@
1
+ import { isDiscardedResponse } from "./protocol.js";
2
+ import { rereadsAfterCuts } from "./thrash.js";
3
+ /** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
4
+ export const LEAN_HOLDING = 0.1;
5
+ /** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
6
+ export const LEAN_MIN_SAMPLES = 4;
7
+ const promptTokens = (entry) => {
8
+ if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message))
9
+ return undefined;
10
+ const message = entry.message;
11
+ if (message.stopReason === "error" || message.stopReason === "aborted")
12
+ return undefined;
13
+ const u = message.usage;
14
+ const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
15
+ return Number.isFinite(total) && total > 0 ? total : undefined;
16
+ };
17
+ /** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
18
+ * the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
19
+ * consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
20
+ export function leanInputs(branch) {
21
+ let kept = 0, previous, afterCut = false, sum = 0, samples = 0;
22
+ for (const entry of branch) {
23
+ if (entry.type === "compaction") {
24
+ previous = undefined;
25
+ afterCut = true;
26
+ continue;
27
+ }
28
+ const prompt = promptTokens(entry);
29
+ if (prompt === undefined)
30
+ continue;
31
+ if (afterCut) {
32
+ kept = prompt;
33
+ afterCut = false;
34
+ }
35
+ if (previous !== undefined) {
36
+ sum += prompt - previous;
37
+ samples++;
38
+ }
39
+ previous = prompt;
40
+ }
41
+ const { cuts, tokens } = rereadsAfterCuts(branch);
42
+ return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
43
+ }
44
+ /**
45
+ * The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
46
+ * (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
47
+ * n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
48
+ * Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
49
+ */
50
+ export function leanLine(branch) {
51
+ const { kept, growth, rereads, samples, cuts } = leanInputs(branch);
52
+ if (!cuts || kept <= 0 || samples < LEAN_MIN_SAMPLES || !(growth > 0))
53
+ return undefined;
54
+ return Math.ceil(kept + Math.sqrt(2 * (kept + rereads) * growth / LEAN_HOLDING));
55
+ }
@@ -23,4 +23,6 @@ export declare function statusText(input: {
23
23
  cacheSensitive?: boolean;
24
24
  /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
25
25
  cutPoint?: number;
26
+ /** The line that sets the trim point now, when it is not the default band: the lean line or the thrash line. */
27
+ trigger?: "lean" | "thrash";
26
28
  }): string;
@@ -38,7 +38,9 @@ export function statusText(input) {
38
38
  ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
39
39
  ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
40
40
  input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
41
- ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
41
+ ? input.trigger === "lean" ? `Trim point: this session's lean line, set by its growth per request and the size of its last trim${now}.`
42
+ : input.trigger === "thrash" ? `Trim point: native Pi's line, because this session's trims keep dropping files it then re-reads${now}.`
43
+ : `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
42
44
  "Search: by keyword.",
43
45
  ...checkLines,
44
46
  ].join("\n");
@@ -0,0 +1,25 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ /** A re-read counts when it is issued within this many replies after a cut. */
3
+ export declare const THRASH_WINDOW_REPLIES = 3;
4
+ /** Re-reads per cut at which a session is thrashing. */
5
+ export declare const THRASH_BAR = 0.5;
6
+ /**
7
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
8
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
9
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
10
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
11
+ */
12
+ export interface Rereads {
13
+ cuts: number;
14
+ rereads: number;
15
+ tokens: number;
16
+ }
17
+ /** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
18
+ export declare function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads;
19
+ /**
20
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
21
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
22
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
23
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
24
+ */
25
+ export declare function thrashing(branch: readonly SessionEntry[]): boolean;
@@ -0,0 +1,59 @@
1
+ import { isDiscardedResponse } from "./protocol.js";
2
+ import { pathKey } from "./path-key.js";
3
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
4
+ import { extractPath } from "./tuck/core/tool-args.js";
5
+ /** A re-read counts when it is issued within this many replies after a cut. */
6
+ export const THRASH_WINDOW_REPLIES = 3;
7
+ /** Re-reads per cut at which a session is thrashing. */
8
+ export const THRASH_BAR = 0.5;
9
+ /** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
10
+ export function rereadsAfterCuts(branch) {
11
+ let cuts = 0, replies = 0, rereads = 0, chars = 0;
12
+ const pending = new Map(), last = new Map();
13
+ for (const entry of branch) {
14
+ if (entry.type === "compaction") {
15
+ cuts++;
16
+ replies = 0;
17
+ continue;
18
+ }
19
+ if (entry.type !== "message")
20
+ continue;
21
+ const message = entry.message;
22
+ if (message.role === "assistant") {
23
+ if (isDiscardedResponse(message))
24
+ continue;
25
+ replies++;
26
+ for (const block of message.content) {
27
+ if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
28
+ continue;
29
+ const args = block.arguments, path = extractPath(args);
30
+ if (!path)
31
+ continue;
32
+ pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
33
+ }
34
+ }
35
+ else if (message.role === "toolResult") {
36
+ const read = pending.get(message.toolCallId);
37
+ if (!read || message.isError || !isTextOnly(message.content))
38
+ continue;
39
+ pending.delete(message.toolCallId);
40
+ const text = textOf(message.content), earlier = last.get(read.key);
41
+ if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) {
42
+ rereads++;
43
+ chars += text.length;
44
+ }
45
+ last.set(read.key, { cut: read.cut, text });
46
+ }
47
+ }
48
+ return { cuts, rereads, tokens: Math.ceil(chars / 4) };
49
+ }
50
+ /**
51
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
52
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
53
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
54
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
55
+ */
56
+ export function thrashing(branch) {
57
+ const { cuts, rereads } = rereadsAfterCuts(branch);
58
+ return cuts > 0 && rereads / cuts >= THRASH_BAR;
59
+ }
@@ -2,3 +2,17 @@
2
2
  export declare const CLOSING_INSTRUCTION: string;
3
3
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
4
4
  export declare const DIALOGUE_SUFFIX: string;
5
+ /** The closing words when working files follow: the re-read rule stays for every other file. */
6
+ export declare const WORKING_FILES_INSTRUCTION: string;
7
+ /** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
8
+ * exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
9
+ export declare const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
10
+ export declare const workingFileBlock: (file: {
11
+ path: string;
12
+ text: string;
13
+ }) => string;
14
+ /** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
15
+ export declare const closingSuffix: (files: readonly {
16
+ path: string;
17
+ text: string;
18
+ }[]) => string;
@@ -4,3 +4,13 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
4
4
  "Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
5
5
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
6
6
  export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
7
+ const REREAD = "Re-read a file before editing it or importing from it.";
8
+ /** The closing words when working files follow: the re-read rule stays for every other file. */
9
+ export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD, "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
10
+ /** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
11
+ * exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
12
+ export const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
13
+ export const workingFileBlock = (file) => `\n<file path=${JSON.stringify(file.path)}>\n${file.text}\n</file>`;
14
+ /** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
15
+ export const closingSuffix = (files) => files.length
16
+ ? CLOSING_SEPARATOR + WORKING_FILES_INSTRUCTION + WORKING_FILES_HEADER + files.map(workingFileBlock).join("") : DIALOGUE_SUFFIX;
@@ -32,6 +32,8 @@ export interface RecallContinuation {
32
32
  }
33
33
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
34
34
  export declare const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
+ /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
+ export declare const WORKING_SET_SHARE: number;
35
37
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
36
38
  export interface Tuck {
37
39
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
@@ -64,6 +66,8 @@ export interface Tuck {
64
66
  }[], query: string): number[];
65
67
  }
66
68
  import { compileDialogue } from "./tuck/core/summarize.js";
69
+ /** The share of the brief below which the carried part of a prefix-stable summary keeps only its user and custom records. */
70
+ export declare const STABLE_CONSOLIDATE_AT = 0.5;
67
71
  export declare const tuck: Tuck;
68
72
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
69
73
  * `_operatorManual` retains the exported positional slot for existing callers. */