pi-tuck 1.3.1 → 1.3.3

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,32 @@
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.3.3] - 2026-11-20
7
+
8
+ ### Fixed
9
+
10
+ - **A learned server window no longer outlives a larger configured window.** When a server clips replies below the configured window,
11
+ pi-tuck learns the smaller window and keeps it in the session. It now also records the configured window it learned under, and
12
+ drops the learned value once the model's configured window differs, for example after a server and its models.json grew from
13
+ 68,000 to 131,072 tokens. Before, every reopened session stayed capped at the old window and compacted far too often. Learned
14
+ windows saved by earlier versions carry no configured window and are not reused; if the server still clips, the next clipped
15
+ reply learns it again.
16
+
17
+ ## [1.3.2] - 2026-11-15
18
+
19
+ ### Fixed
20
+
21
+ - **pi-tuck no longer refuses a request that Pi itself would send.** When a reply mid-run is too large for any cut to fit pi-tuck's own
22
+ limit (seen live: a reply with about 12,000 tokens of reasoning at a 32,768-token window), pi-tuck now sends its smallest cut whenever Pi's
23
+ own request math fits it in the window, with the reply cap Pi's clamp leaves. Nothing is removed from the request. It refuses only past
24
+ the window, and the refusal now names what does not fit instead of always blaming the starting prompt.
25
+
26
+ ### Changed
27
+
28
+ - **Tests no longer assert wall time in CI.** Timing bounds run in a local bench before each release; per-test timeouts are 120 s.
29
+ Local timing bench for this release (Apple silicon, `npm run timing`): every regression-bench cell within its bound; keyword recall on an
30
+ 85 MB session 671 ms before and 688 ms after growth, against a 3,000 ms budget.
31
+
6
32
  ## [1.3.1] - 2026-11-15
7
33
 
8
34
  ### Changed
package/README.md CHANGED
@@ -62,8 +62,8 @@ pi install npm:pi-tuck
62
62
  Then start a new Pi session. That is all. pi-tuck takes over Pi's compaction, both automatic and `/compact`. You change no setting.
63
63
 
64
64
  - Needs Pi 1.2.0 or later (tested on 1.2.0 and 1.4.0), on macOS, Linux or Windows (Windows since 1.2.0, tested on Windows 10 with Node 24 and Pi 1.5.2). On an older Pi, pi-tuck stays off, Pi's own compaction runs, and pi-tuck says so once.
65
- - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.2.0`.
66
- - To pin a version, add it: `pi install npm:pi-tuck@1.2.0`.
65
+ - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.3.1`.
66
+ - To pin a version, add it: `pi install npm:pi-tuck@1.3.1`.
67
67
 
68
68
  ## Uninstall
69
69
 
@@ -80,6 +80,7 @@ When context fills up, pi-tuck replaces the older turns with one summary. The su
80
80
  - **The dialogue and your prompts, ranked.** Since 1.0.18, one ranked list decides what a cut carries, across the summary and the kept tail together: the current prompt, whole; the openings of the first prompt and the newest answered prompts, sized to the room; the newest part of the conversation, kept as it is; the file and action lists below; and the rest of the conversation. Dropped turns and tool results are counted with index ranges that `tuck_recall` reads back. Clipped text says how to read it in full.
81
81
  - **The files.** Files the agent read, wrote or edited, newest first (up to 60), each with a pointer to read it back.
82
82
  - **Kept reads** (1.1.0 and later). After the Files list, the summary carries 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 recorded since):`. It keeps at most 4 files, whole outputs only, within 20% of the summary's room and never more than 24,000 characters. Since 1.2.0, a read is also dropped from the summary when a later shell command that is not read-only names the file, or when a git command such as `checkout`, `stash`, `restore` or `reset` ran, and paths are compared after normalising their spelling. When the summary is over its target, these records are dropped first, oldest first. With no such reads the summary is unchanged, and tool outputs are never touched. The header says only that no write or edit was recorded since the read; it does not say the file on disk is unchanged. After a cut, agents often doubted what an earlier read had shown and read the same file again, and this is meant to spare that. It has no effectiveness claim; see Benchmarks.
83
+ - **Kept searches** (1.3.0 and later; 1.3.0 never reached npm, so 1.3.1 is the first release with them). A cut's summary also keeps the latest output of a `grep` or `rg` search, per command and at most 4, beside the kept reads, while nothing the search lists has changed since: a later write or edit of a listed file, or a shell command that is not read-only and names one, drops it. Searches with shell syntax pi-tuck cannot classify are never kept. Kept searches share kept reads' space in the summary, so the summary's size target is unchanged. It has no effectiveness claim; see Benchmarks.
83
84
  - **The action trail.** The agent's other tool calls, such as shell commands, newest first (up to 30). The output is left out. A pointer leads to it.
84
85
 
85
86
  Tool output stays in the session file, not in the summary. Each summary ends with a short instruction to the agent: re-read a file before you edit it, look things up, and treat anything not shown as unknown.
@@ -154,6 +155,7 @@ Each row says what was measured, under which conditions, and where the data is.
154
155
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.10 candidate | Passed as registered: 0 dead tasks and 0 stuck sessions on 30 tasks, on a slow local server (27 of 30 tasks hit the 30-minute wall cap, and 2 had a first request the server never answered). 6 resolved. A counter written later, which counts a task with no token as dead, would count those 2. **The registered counter counts refusals and cannot see a task that began without its prompt**: in 8 of the 30 tasks (4, 8, 9, 10, 13, 14, 17, 21) a cut at the prompt kept no turn, none of the 8 resolved, and 6 ended with an empty patch. So the pass shows no refusal, not that every task began with its prompt. The 1.0.11 candidate on the same test had 7 of 30 such tasks, 1 resolved. Fixed in 1.0.12 | Candidate `a67ec30` of 1.0.10, `mac-studio/main`, window 32,768, output cap 16,384, Pi's default `reserveTokens` 16,384 and `keepRecentTokens` 20,000, one session of chain t06. One mid-run refusal (a round with 9,020 tokens of reasoning against the 16,384-token room). One session per arm, one model. In 12 of the 15 tasks across both arms the model's own first messages show it lacked the prompt; the other 3 are not clear from the records | [`benchmark/RESULTS-DEFAULTS-1010.md`](benchmark/RESULTS-DEFAULTS-1010.md) |
155
156
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.8 | 28 of 30 tasks lost (tasks 3 to 30, each refused at its prompt); 1 resolved. Fails the pre-registered bar of 0 lost tasks | pi-tuck 1.0.8 (`86935e9`), `mac-studio/main`, window 32,768, output cap 16,384, `reserveTokens` 16,384 and `keepRecentTokens` 20,000 (larger than the room), one session of chain t06. One session, one model, one build: it shows that the failure occurs at these settings, not how often. Not comparable with other rows | [`benchmark/RESULTS-DEFAULTS.md`](benchmark/RESULTS-DEFAULTS.md) |
156
157
  | Tasks resolved, 32k window | Pi's built-in compaction 94 of 150; pi-tuck 120 of 150 (+17.3 points, 95% lower bound +10.7); observation masking 117 of 150 (pi-tuck +2.0, lower bound −2.7: no difference shown). Turns per task: 9.4 (built-in), 24.0 (pi-tuck), 11.9 (masking). Tokens per session: 6.10 M, 6.39 M, 7.02 M. Spend per arm for the five sessions: $0.87, $0.55, $0.94 | pi-tuck 1.0.5 (commit `aa30824`, the 1.0.5 code; 1.0.6 and 1.0.7 are not measured). DeepSeek V4.1 Flash pinned to one upstream, window 32,768, reserve 16,384, 5 chains of 30 SWE-bench Verified tasks, paired by task, one-sided bootstrap over tasks. **Limits:** only pi-tuck is held to the 16,384-token room (the built-in sent a request over it in 97 of 150 tasks, masking in 73, so the window is nominal for them). The difference by chain is +10.0, −3.3, +50.0, +16.7 and +13.3 points; leaving out chain t03 it is +9.2. The bootstrap resamples tasks, not chains. The pi-tuck arm ran at a different time from the others. One model, one window. pi-tuck refused to cut mid-run in 5 tasks, where one fresh tool result was larger than the room; they count as unresolved. In the same setup pi-tuck 1.0.3 resolved 72 of 150, with 52 dead tasks (tasks refused at their prompt after an earlier failure). In the pi-tuck arm of this row there was 1 dead task (t03 task 24: refused at its prompt with "Nothing to compact"; the next task ran normally), so this build missed the pre-registered acceptance bar of zero dead tasks by one task (the other part of the bar, no loss against 1.0.3 by more than 3 points, was met) | [`benchmark/RESULTS-32K-ACCEPT.md`](benchmark/RESULTS-32K-ACCEPT.md) |
158
+ | Kept searches (1.3.0, shipped in 1.3.1): live gate against 1.2.0's line | In a 10-task paired live gate, the agent repeated a search after a cut 0.23 times per cut against 0.45, and resolved 5 tasks the other build missed against 2, with no refusals, lost tasks or error stops | NVIDIA Nemotron, room 16,384, 10 paired tasks, one model, one room, one run per arm. The counts are what the ten tasks showed, and no effectiveness claim is made. 1.3.1 is 1.3.0's code: 1.3.0 never reached npm because a timing check in the test suite stopped its publish on the release runner | [`CHANGELOG.md`](CHANGELOG.md) 1.3.0 and 1.3.1 |
157
159
  | pi-tuck 1.2.0: live gate against 1.1.2, and replay against 1.1.3 | Live gate, 10 paired tasks at room 16,384: solved wins minus losses +1 (bar: at least −1), turn-cap stops 3 against 4, doubt moments 6 against 9, 0 lost tasks; kept-read records quoting a partial or stale read 0 against 141. Replay against 1.1.3 (byte-identical to 1.1.2): 29 recordings, cuts 1,975 to 1,869 and clips 16 to 8 with the smaller tool list and the stricter kept reads, 0 lost or dead tasks, 0 faults | Ten tasks on NIM Nemotron, one model, one room, one run per arm: no effectiveness claim is made. The gate found one false refusal after a steering message, fixed in 1.1.3 and pinned by tests built from that run. Strict stress: 322 cells, 0 findings. Tests and CI on macOS and Ubuntu; the full suite also passed on Windows | [`CHANGELOG.md`](CHANGELOG.md) 1.2.0 |
158
160
  | Kept reads (1.1.0): 5-task check against 1.0.31, and replay against 1.0.33 | No breakage in 5 of 5 tasks, and all 5 solved on both builds. Re-checks after a doubt 22 against 45; doubt moments 9 against 24; cuts 22 against 26; turns 305 against 384. One heavy task went worse: 90 turns against 59, 9 cuts against 4, 3 doubts against 1. Replay against 1.0.33: 13,946 requests, 0 lost or dead tasks, clips 17 to 16, cuts 1,946 to 1,971; in every recording that differs, the first difference is the first summary carrying a kept read, and 11 of 29 never differ | Five tasks, before the Tier 1. This is not an effectiveness result and no effectiveness claim is made for kept reads. The Tier 1 against 1.0.33 is still running; if it fails, npm and installs go back to 1.0.33. Strict stress: 0 findings in 313 cells on Pi 1.2.0 and the newest Pi | [`CHANGELOG.md`](CHANGELOG.md) 1.1.0 |
159
161
  | pi-tuck 1.0.18 against the recorded 1.0.16 arm, 81,920 window | Registered bar (Tier 1) met: both arms resolved the same 56 of 60 tasks (+0.0 points, one-sided 95% lower bound +0.0, against a bar of above −10); 0 lost tasks: dead tasks, mid-run refusals and dropped prompts are 0 in both arms, and the audit listed one candidate task (t06 task 21), which, with the two other candidate tasks that had a cut at a prompt (t06 task 8, t07 task 24), was read by hand and works on its own task. Readouts: turns per task 22.27 against 29.35, cuts 57 against 61, total tokens 40.3 M against 62.1 M. Against the recorded 1.0.13 arm of the adaptive gate, a different pair of runs a day apart, 1.0.18 is at 22.27 turns per task against 20.22 and 40.3 M tokens against 37.4 M | Pre-registered gate. pi-tuck 1.0.18 (`2d1f830`, tag `v1.0.18`), run from the unpacked npm tarball; its `src/` is byte-identical to `1ea1e1e`, the commit replay and the stress test measured, ran alone on chains t06 and t07 (60 tasks) against the recorded 1.0.16 arm; the arms did not run side by side, the base earlier the same day, so seconds are not compared. One model, one window, one run per arm. The resolved result is a bound, not a gain. The turn, cut and token readouts are reported, not claimed | [`benchmark/RESULTS-V1018.md`](benchmark/RESULTS-V1018.md) |
@@ -1 +1 @@
1
- export declare const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export declare const BUILD_ID = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
@@ -1 +1 @@
1
- export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export const BUILD_ID = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
@@ -115,6 +115,8 @@ class Calibration {
115
115
  factor = 1;
116
116
  ratios = [];
117
117
  learnedContextWindow;
118
+ /** The configured window the learned window was learned under; the learned window applies only while the model still has it. */
119
+ learnedCatalogue;
118
120
  windowObservation;
119
121
  pending;
120
122
  lastCeiling = null;
@@ -132,6 +134,7 @@ class Calibration {
132
134
  if (reason === 'session') {
133
135
  this.factor = 1;
134
136
  this.learnedContextWindow = undefined;
137
+ this.learnedCatalogue = undefined;
135
138
  this.estimatedTokens = 0;
136
139
  // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
137
140
  this.seededIdentity = '';
@@ -143,7 +146,8 @@ class Calibration {
143
146
  const branch = ctx.sessionManager.getBranch();
144
147
  this.ratios = seedWindow(branch, this.identity);
145
148
  this.factor = Math.max(1, ...this.ratios);
146
- this.learnedContextWindow = seedContextWindow(branch, this.identity);
149
+ this.learnedCatalogue = ctx.model?.contextWindow;
150
+ this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
147
151
  }
148
152
  learn(value, ctx, append) {
149
153
  this.ratios.push(value);
@@ -192,7 +196,7 @@ export async function installCompaction(pi, options = {}) {
192
196
  }
193
197
  });
194
198
  const captureDraft = (draft, ctx, reserve, reason, tokensBefore, retainCurrentInput, operatorManual, previousSummary, budget) => recorder.measureInline(() => {
195
- const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, learnedContextWindow: calibration.learnedContextWindow, activeInputCeilingTokens: calibration.lastCeiling });
199
+ const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, learnedContextWindow: calibration.learnedContextWindow, ...(calibration.learnedContextWindow !== undefined && calibration.learnedCatalogue !== undefined ? { catalogueContextWindow: calibration.learnedCatalogue } : {}), activeInputCeilingTokens: calibration.lastCeiling });
196
200
  proposalId = receiptId(attached);
197
201
  if (recorder.enabled) {
198
202
  try {
@@ -266,7 +270,9 @@ export async function installCompaction(pi, options = {}) {
266
270
  pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
267
271
  const contextWindow = (ctx) => {
268
272
  identityFor(ctx);
269
- return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
273
+ const model = ctx.model?.contextWindow ?? 0;
274
+ const learned = calibration.learnedCatalogue === ctx.model?.contextWindow ? calibration.learnedContextWindow : undefined;
275
+ return Math.min(model, learned ?? Infinity);
270
276
  };
271
277
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
272
278
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
@@ -339,9 +345,13 @@ export async function installCompaction(pi, options = {}) {
339
345
  if (message.stopReason === "length" && requested !== undefined &&
340
346
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
341
347
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
348
+ // A learned window from another configured window no longer bounds this one.
349
+ if (calibration.learnedCatalogue !== ctx.model.contextWindow)
350
+ calibration.learnedContextWindow = undefined;
351
+ calibration.learnedCatalogue = ctx.model.contextWindow;
342
352
  calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
343
353
  serverClipped.add(message);
344
- calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
354
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow, catalogue: ctx.model.contextWindow };
345
355
  }
346
356
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
347
357
  // Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
@@ -356,7 +366,7 @@ export async function installCompaction(pi, options = {}) {
356
366
  return;
357
367
  const observation = calibration.windowObservation;
358
368
  calibration.windowObservation = undefined;
359
- pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
369
+ pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window, catalogueContextWindow: observation.catalogue,
360
370
  serverClippedReplyId: event.messageEntryId });
361
371
  });
362
372
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
@@ -440,8 +450,9 @@ export async function installCompaction(pi, options = {}) {
440
450
  const requestClamp = (messages, ctx) => {
441
451
  const context = normalizeContext({ messages: convertToLlm(messages) });
442
452
  const cap = piClamp?.({ ...ctx.model, contextWindow: contextWindow(ctx) }, context, ctx.model.maxTokens);
443
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor,
444
- estimate: piMath ? piMath.estimateContextTokens(context).tokens : 0 };
453
+ const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
454
+ return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
455
+ fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
445
456
  };
446
457
  const projectedRequest = (messages, ctx, host, incoming, prompt, tools, cut) => {
447
458
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -485,13 +496,14 @@ export async function installCompaction(pi, options = {}) {
485
496
  const isNoWork = (message) => ["Already compacted", "Nothing to compact (session too small)"].includes(message?.replace(/^Compaction failed: /, "") ?? "");
486
497
  // A missing model is configuration, not capacity.
487
498
  const missingModel = () => new Error("No context model for the request budget");
488
- const receipt = (kind, reason, ctx) => {
499
+ const receipt = (kind, reason, ctx, check) => {
489
500
  let room = null, hardLine = null;
490
501
  try {
491
502
  ({ room, hardLine } = limits(ctx));
492
503
  }
493
504
  catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
494
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
505
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
506
+ ...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
495
507
  };
496
508
  const fail = (error, ctx) => {
497
509
  recorder.stop("native-attempt-failed");
@@ -689,9 +701,9 @@ export async function installCompaction(pi, options = {}) {
689
701
  };
690
702
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
691
703
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
692
- const deepestDecision = (ctx, newPrompt, retain) => {
704
+ const deepestDecision = (ctx, newPrompt, retain, clipFresh = true) => {
693
705
  const saved = ctx.sessionManager.buildSessionProjection().messages;
694
- if (!newPrompt) {
706
+ if (!newPrompt && clipFresh) {
695
707
  const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
696
708
  const response = saved[at];
697
709
  const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
@@ -723,6 +735,22 @@ export async function installCompaction(pi, options = {}) {
723
735
  return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
724
736
  compaction: draft.compaction, reserve: 0, messages } };
725
737
  };
738
+ // Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
739
+ // Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
740
+ // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
741
+ // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
742
+ const nativeFloorDecision = (ctx, newPrompt, retain, project) => {
743
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending)
744
+ return;
745
+ const candidate = deepestDecision(ctx, newPrompt, retain, false);
746
+ if (candidate.kind !== "cut")
747
+ return;
748
+ const messages = project(candidate);
749
+ if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
750
+ return;
751
+ if (requestClamp(messages, ctx).fitsWindow)
752
+ return candidate;
753
+ };
726
754
  // The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
727
755
  // custom message starts). The cut is pi-tuck's own, planned as at a tool boundary. It is not Pi's: Pi's cut finder keeps the last
728
756
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
@@ -732,6 +760,7 @@ export async function installCompaction(pi, options = {}) {
732
760
  if (standDown(ctx))
733
761
  return;
734
762
  run.cut.clear();
763
+ run.nativeFloorPending = false;
735
764
  const branchLength = ctx.sessionManager.getBranch().length;
736
765
  if (!active())
737
766
  return;
@@ -788,6 +817,13 @@ export async function installCompaction(pi, options = {}) {
788
817
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
789
818
  if (decision.kind === "none")
790
819
  return;
820
+ if (decision.kind === "fault" && decision.capacity) {
821
+ const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId), candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
822
+ if (floor) {
823
+ decision = floor;
824
+ run.nativeFloorPending = true;
825
+ }
826
+ }
791
827
  if (decision.kind === "fault")
792
828
  throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
793
829
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary, { response, host, mandatory, target: decision.target, margin: room - band });
@@ -896,12 +932,10 @@ export async function installCompaction(pi, options = {}) {
896
932
  // request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
897
933
  let previews = [];
898
934
  let floorKept;
899
- let wholePromptFloor;
900
935
  const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
901
936
  const decide = (targetRoom = room, targetBand = band, required = false) => {
902
937
  previews = [];
903
938
  floorKept = undefined;
904
- wholePromptFloor = undefined;
905
939
  const before = measure(saved);
906
940
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
907
941
  gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
@@ -914,8 +948,6 @@ export async function installCompaction(pi, options = {}) {
914
948
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
915
949
  const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
916
950
  if (!draft.compaction) {
917
- if (protectedId && draft.floorMessages)
918
- wholePromptFloor = measure(draft.floorMessages) + mandatory;
919
951
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
920
952
  if (draft.floorMessages && event.toolResults) {
921
953
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
@@ -981,9 +1013,15 @@ export async function installCompaction(pi, options = {}) {
981
1013
  }, () => deepestDecision(ctx, false, true));
982
1014
  }
983
1015
  if (decision.kind === "fault" && reason === "tool-loop") {
984
- if (wholePromptFloor !== undefined && !fits(wholePromptFloor, hardLine, ctx))
1016
+ if (decision.capacity)
1017
+ decision = nativeFloorDecision(ctx, false, true, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
1018
+ }
1019
+ if (decision.kind === "fault" && reason === "tool-loop") {
1020
+ if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx))
985
1021
  throw promptRefusal();
986
- throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
1022
+ if (decision.capacity)
1023
+ throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
1024
+ throw new Refusal(decision.message);
987
1025
  }
988
1026
  if (decision.kind !== "cut")
989
1027
  return;
@@ -1156,16 +1194,24 @@ export async function installCompaction(pi, options = {}) {
1156
1194
  };
1157
1195
  if (!accepts(decision))
1158
1196
  decision = deepestDecision(ctx, false, true);
1197
+ let native = false;
1159
1198
  if (decision.kind !== "cut" || !accepts(decision)) {
1160
1199
  clips().clear();
1161
1200
  for (const [id, clip] of previousClips)
1162
1201
  clips().set(id, clip);
1163
- return messages;
1202
+ const floor = nativeFloorDecision(ctx, false, true, project);
1203
+ if (!floor)
1204
+ return { messages };
1205
+ decision = floor;
1206
+ native = true;
1164
1207
  }
1208
+ if (decision.kind !== "cut")
1209
+ return { messages };
1165
1210
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary, { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1166
1211
  run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1212
+ run.nativeFloorPending = native;
1167
1213
  syncHistoryTools(ctx);
1168
- return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true);
1214
+ return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true), native };
1169
1215
  };
1170
1216
  pi.on("context", (event, ctx) => {
1171
1217
  try {
@@ -1263,8 +1309,13 @@ export async function installCompaction(pi, options = {}) {
1263
1309
  let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1264
1310
  let tokens = system + conversationTokens(messages);
1265
1311
  const { room, hardLine } = limits(ctx);
1266
- if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1267
- messages = guardCut(messages, tokens, system, ctx);
1312
+ let native = false;
1313
+ const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1314
+ piClamp && !requestClamp(messages, ctx).leavesFloor;
1315
+ if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1316
+ const cut = guardCut(messages, tokens, system, ctx);
1317
+ messages = cut.messages;
1318
+ native = Boolean(cut.native);
1268
1319
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1269
1320
  tokens = system + conversationTokens(messages);
1270
1321
  assertNativeToolRounds(messages);
@@ -1273,13 +1324,18 @@ export async function installCompaction(pi, options = {}) {
1273
1324
  calibration.estimatedTokens = corrected(tokens, ctx);
1274
1325
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1275
1326
  throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
1276
- if (!fits(tokens, hardLine, ctx))
1327
+ // A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
1328
+ native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
1329
+ native &&= requestClamp(messages, ctx).fitsWindow;
1330
+ if (!native && !fits(tokens, hardLine, ctx))
1277
1331
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1278
- // Pi's request estimator and its compaction estimator need not agree. The hard line is
1279
- // necessary; above the room, also require the real request clamp to preserve the floor.
1280
- if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1332
+ // Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
1333
+ // only the refusal-path compiler floor may instead use native window admission.
1334
+ if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1281
1335
  throw new CapacityError(clampMessage);
1282
- if (calibration.estimatedTokens > room)
1336
+ if (native)
1337
+ receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
1338
+ else if (calibration.estimatedTokens > room)
1283
1339
  receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1284
1340
  if (recorder.enabled && !recorder.waitingForCut)
1285
1341
  recorder.measureInline(() => {
@@ -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 = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
3
+ export declare const DIAGNOSTIC_BUILD = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -20,6 +20,7 @@ export interface Receipt {
20
20
  calibrationWindow?: number[];
21
21
  calibrationIdentity?: string;
22
22
  learnedContextWindow?: number;
23
+ catalogueContextWindow?: number;
23
24
  activeInputCeilingTokens?: number | null;
24
25
  };
25
26
  before: {
@@ -23,13 +23,18 @@ export declare const thinkingOnlyLength: (message: AgentMessage) => boolean;
23
23
  /** Thinking-only exhaustion uses the observed largest reply, not the full reserve. Every other failed length/overflow keeps its override. */
24
24
  export declare const needsFullReplyReserve: (message: AgentMessage) => boolean;
25
25
  /** Saved immediately at the reply's turn boundary, even when recovery cannot make a compaction. */
26
+ /** `catalogueContextWindow` is the model's configured window when the server clipped below it. A learned window holds only while the
27
+ * configured window is unchanged: a server or catalogue that grew must not stay capped by an old clip (Nautilus, 2026-11-20). */
26
28
  export interface WindowReceipt {
27
29
  calibrationIdentity: string;
28
30
  learnedContextWindow: number;
31
+ catalogueContextWindow: number;
29
32
  serverClippedReplyId: string;
30
33
  }
31
34
  export declare const WINDOW_RECEIPT = "pi-tuck-window";
32
- export declare function seedContextWindow(branch: readonly SessionEntry[], identity: string): number | undefined;
35
+ /** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
36
+ * carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
37
+ export declare function seedContextWindow(branch: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined;
33
38
  /** One branch reader for the reserve override and reply floor, including history before cuts. A server-clipping receipt follows its reply. */
34
39
  export declare function replyFit(branch: readonly SessionEntry[]): {
35
40
  failed: boolean;
@@ -72,13 +72,17 @@ function windowSettings(entry) {
72
72
  return entry.details?.diagnosticReceipt?.settings;
73
73
  return undefined;
74
74
  }
75
- export function seedContextWindow(branch, identity) {
75
+ /** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
76
+ * carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
77
+ export function seedContextWindow(branch, identity, catalogue) {
76
78
  for (let i = branch.length; i--;) {
77
79
  const settings = windowSettings(branch[i]);
78
80
  if (settings?.calibrationIdentity !== identity)
79
81
  continue;
80
82
  const window = settings.learnedContextWindow;
81
- return Number.isSafeInteger(window) && window > 0 ? window : undefined;
83
+ if (!(Number.isSafeInteger(window) && window > 0))
84
+ return undefined;
85
+ return catalogue !== undefined && settings.catalogueContextWindow === catalogue ? window : undefined;
82
86
  }
83
87
  return undefined;
84
88
  }
package/dist/src/run.d.ts CHANGED
@@ -52,6 +52,8 @@ export declare class Run {
52
52
  clips: Map<string, Clip>;
53
53
  pendingBoundaryReceipts: string[];
54
54
  thinkingRetryPending: boolean;
55
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
56
+ nativeFloorPending: boolean;
55
57
  refusalReceipted: boolean;
56
58
  clear(): void;
57
59
  }
package/dist/src/run.js CHANGED
@@ -129,6 +129,8 @@ export class Run {
129
129
  clips = new Map();
130
130
  pendingBoundaryReceipts = [];
131
131
  thinkingRetryPending = false;
132
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
133
+ nativeFloorPending = false;
132
134
  refusalReceipted = false;
133
135
  clear() {
134
136
  this.prompt = undefined;
@@ -136,6 +138,7 @@ export class Run {
136
138
  this.clips.clear();
137
139
  this.pendingBoundaryReceipts = [];
138
140
  this.thinkingRetryPending = false;
141
+ this.nativeFloorPending = false;
139
142
  this.refusalReceipted = false;
140
143
  this.expiredPlan = false;
141
144
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.3.1",
3
+ "version": "1.3.3",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -52,7 +52,8 @@
52
52
  "check": "tsc -p tsconfig.tests.json",
53
53
  "test": "vitest run --config vitest.config.ts",
54
54
  "build": "node scripts/build.mjs",
55
- "prepack": "npm run build"
55
+ "prepack": "npm run build",
56
+ "timing": "PI_TUCK_TIMING=1 STRESS=1 vitest run --config vitest.config.ts --maxWorkers=1 test/regression-bench.test.ts test/stress/large-session.test.ts"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "@earendil-works/pi-ai": ">=1.2.0",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export const BUILD_ID = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
package/src/compaction.ts CHANGED
@@ -109,7 +109,9 @@ class Calibration {
109
109
  factor = 1;
110
110
  ratios: number[] = [];
111
111
  learnedContextWindow: number | undefined;
112
- windowObservation: { message: AgentMessage; identity: string; window: number } | undefined;
112
+ /** The configured window the learned window was learned under; the learned window applies only while the model still has it. */
113
+ learnedCatalogue: number | undefined;
114
+ windowObservation: { message: AgentMessage; identity: string; window: number; catalogue: number } | undefined;
113
115
  pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
114
116
  lastCeiling: number | null = null;
115
117
  estimatedTokens = 0;
@@ -123,7 +125,7 @@ class Calibration {
123
125
  this.pending = undefined;
124
126
  if (reason !== 'identity') this.windowObservation = undefined;
125
127
  if (reason === 'session') {
126
- this.factor = 1; this.learnedContextWindow = undefined; this.estimatedTokens = 0;
128
+ this.factor = 1; this.learnedContextWindow = undefined; this.learnedCatalogue = undefined; this.estimatedTokens = 0;
127
129
  // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
128
130
  this.seededIdentity = '';
129
131
  return;
@@ -133,7 +135,8 @@ class Calibration {
133
135
  const branch = ctx.sessionManager.getBranch();
134
136
  this.ratios = seedWindow(branch, this.identity);
135
137
  this.factor = Math.max(1, ...this.ratios);
136
- this.learnedContextWindow = seedContextWindow(branch, this.identity);
138
+ this.learnedCatalogue = ctx.model?.contextWindow;
139
+ this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
137
140
  }
138
141
  learn(value: number, ctx: ExtensionContext, append: (kind: string, data: unknown) => void) {
139
142
  this.ratios.push(value); if (this.ratios.length > CALIBRATION_WINDOW) this.ratios.shift(); this.factor = Math.max(1, ...this.ratios);
@@ -203,7 +206,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
203
206
  if (found) { recorder.capture("observed-entry", "current-native-branch-memory-not-durable", { entryId: found.id, diagnosticReceiptId: proposalId, details: found.type === "compaction" ? found.details : undefined }); recorder.cut(); proposalId = undefined; }
204
207
  });
205
208
  const captureDraft = (draft: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>, ctx: ExtensionContext, reserve: number, reason: string, tokensBefore: number, retainCurrentInput: boolean, operatorManual: boolean, previousSummary?: string, budget?: { response: number; host: number; mandatory: number; target: Target; margin: number }) => recorder.measureInline(() => {
206
- const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, learnedContextWindow: calibration.learnedContextWindow, activeInputCeilingTokens: calibration.lastCeiling });
209
+ const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, learnedContextWindow: calibration.learnedContextWindow, ...(calibration.learnedContextWindow !== undefined && calibration.learnedCatalogue !== undefined ? { catalogueContextWindow: calibration.learnedCatalogue } : {}), activeInputCeilingTokens: calibration.lastCeiling });
207
210
  proposalId = receiptId(attached);
208
211
  if (recorder.enabled) { try {
209
212
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
@@ -258,7 +261,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
258
261
  pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
259
262
  const contextWindow = (ctx: ExtensionContext) => {
260
263
  identityFor(ctx);
261
- return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
264
+ const model = ctx.model?.contextWindow ?? 0;
265
+ const learned = calibration.learnedCatalogue === ctx.model?.contextWindow ? calibration.learnedContextWindow : undefined;
266
+ return Math.min(model, learned ?? Infinity);
262
267
  };
263
268
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
264
269
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
@@ -319,9 +324,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
319
324
  if (message.stopReason === "length" && requested !== undefined &&
320
325
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
321
326
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
327
+ // A learned window from another configured window no longer bounds this one.
328
+ if (calibration.learnedCatalogue !== ctx.model.contextWindow) calibration.learnedContextWindow = undefined;
329
+ calibration.learnedCatalogue = ctx.model.contextWindow;
322
330
  calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
323
331
  serverClipped.add(message);
324
- calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
332
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow, catalogue: ctx.model.contextWindow };
325
333
  }
326
334
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
327
335
  // Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
@@ -332,7 +340,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
332
340
  if (standDown(ctx)) return;
333
341
  if (calibration.windowObservation?.message !== event.message) return;
334
342
  const observation = calibration.windowObservation; calibration.windowObservation = undefined;
335
- pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
343
+ pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window, catalogueContextWindow: observation.catalogue,
336
344
  serverClippedReplyId: event.messageEntryId } satisfies WindowReceipt);
337
345
  });
338
346
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
@@ -411,8 +419,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
411
419
  const requestClamp = (messages: Messages, ctx: ExtensionContext) => {
412
420
  const context = normalizeContext({ messages: convertToLlm(messages) });
413
421
  const cap = piClamp?.({ ...ctx.model!, contextWindow: contextWindow(ctx) }, context, ctx.model!.maxTokens);
414
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor,
415
- estimate: piMath ? piMath.estimateContextTokens(context).tokens : 0 };
422
+ const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
423
+ return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
424
+ fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
416
425
  };
417
426
  const projectedRequest = (messages: Messages, ctx: ExtensionContext, host: Messages, incoming: Messages, prompt: string, tools: readonly string[], cut: boolean) => {
418
427
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -450,10 +459,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
450
459
  // A missing model is configuration, not capacity.
451
460
  const missingModel = () => new Error("No context model for the request budget");
452
461
  type CutPlan = { compaction: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>; reserve: number; messages: Messages };
453
- const receipt = (kind: "refusal" | "above-room", reason: string, ctx: ExtensionContext) => {
462
+ const receipt = (kind: "refusal" | "above-room" | "native-floor", reason: string, ctx: ExtensionContext, check?: ReturnType<typeof requestClamp>) => {
454
463
  let room: number | null = null, hardLine: number | null = null;
455
464
  try { ({ room, hardLine } = limits(ctx)); } catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
456
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
465
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
466
+ ...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
457
467
  };
458
468
  const fail = (error: unknown, ctx: ExtensionContext) => {
459
469
  recorder.stop("native-attempt-failed");
@@ -618,9 +628,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
618
628
  };
619
629
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
620
630
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
621
- const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean): Decision<CutPlan> => {
631
+ const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean, clipFresh = true): Decision<CutPlan> => {
622
632
  const saved = ctx.sessionManager.buildSessionProjection().messages;
623
- if (!newPrompt) {
633
+ if (!newPrompt && clipFresh) {
624
634
  const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
625
635
  const response = saved[at];
626
636
  const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
@@ -646,6 +656,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
646
656
  return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
647
657
  compaction: draft.compaction, reserve: 0, messages } };
648
658
  };
659
+ // Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
660
+ // Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
661
+ // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
662
+ // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
663
+ const nativeFloorDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean,
664
+ project: (candidate: Decision<CutPlan>) => Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
665
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending) return;
666
+ const candidate = deepestDecision(ctx, newPrompt, retain, false);
667
+ if (candidate.kind !== "cut") return;
668
+ const messages = project(candidate);
669
+ if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role)) return;
670
+ if (requestClamp(messages, ctx).fitsWindow) return candidate;
671
+ };
649
672
  // The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
650
673
  // custom message starts). The cut is pi-tuck's own, planned as at a tool boundary. It is not Pi's: Pi's cut finder keeps the last
651
674
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
@@ -654,6 +677,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
654
677
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages, protectedId?: string) => {
655
678
  if (standDown(ctx)) return;
656
679
  run!.cut.clear();
680
+ run!.nativeFloorPending = false;
657
681
  const branchLength = ctx.sessionManager.getBranch().length;
658
682
  if (!active()) return;
659
683
  access();
@@ -707,6 +731,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
707
731
  if (decision.kind === "defer") return;
708
732
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
709
733
  if (decision.kind === "none") return;
734
+ if (decision.kind === "fault" && decision.capacity) {
735
+ const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId),
736
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
737
+ if (floor) { decision = floor; run!.nativeFloorPending = true; }
738
+ }
710
739
  if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
711
740
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
712
741
  { response, host, mandatory, target: decision.target, margin: room - band });
@@ -799,12 +828,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
799
828
  // request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
800
829
  let previews: Messages[] = [];
801
830
  let floorKept: number | undefined;
802
- let wholePromptFloor: number | undefined;
803
831
  const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
804
832
  const decide = (targetRoom = room, targetBand = band, required = false) => {
805
833
  previews = [];
806
834
  floorKept = undefined;
807
- wholePromptFloor = undefined;
808
835
  const before = measure(saved);
809
836
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
810
837
  gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
@@ -816,7 +843,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
816
843
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
817
844
  const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
818
845
  if (!draft.compaction) {
819
- if (protectedId && draft.floorMessages) wholePromptFloor = measure(draft.floorMessages) + mandatory;
820
846
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
821
847
  if (draft.floorMessages && event.toolResults) {
822
848
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
@@ -875,8 +901,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
875
901
  }, () => deepestDecision(ctx, false, true));
876
902
  }
877
903
  if (decision.kind === "fault" && reason === "tool-loop") {
878
- if (wholePromptFloor !== undefined && !fits(wholePromptFloor, hardLine, ctx)) throw promptRefusal();
879
- throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
904
+ if (decision.capacity) decision = nativeFloorDecision(ctx, false, true,
905
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput,
906
+ event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
907
+ }
908
+ if (decision.kind === "fault" && reason === "tool-loop") {
909
+ if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx)) throw promptRefusal();
910
+ if (decision.capacity) throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
911
+ throw new Refusal(decision.message);
880
912
  }
881
913
  if (decision.kind !== "cut") return;
882
914
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, reason, before, true, false, previousSummary,
@@ -999,7 +1031,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
999
1031
  };
1000
1032
  // A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
1001
1033
  // atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
1002
- const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): Messages => {
1034
+ const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1003
1035
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1004
1036
  const before = conversationTokens(source), mandatory = tokens - before;
1005
1037
  const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
@@ -1036,16 +1068,22 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1036
1068
  return fits(reduced, hardLine, ctx) && (Boolean(options.requestReserve) || corrected(reduced, ctx) <= room || requestClamp(request, ctx).leavesFloor);
1037
1069
  };
1038
1070
  if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
1071
+ let native = false;
1039
1072
  if (decision.kind !== "cut" || !accepts(decision)) {
1040
1073
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
1041
- return messages;
1074
+ const floor = nativeFloorDecision(ctx, false, true, project);
1075
+ if (!floor) return { messages };
1076
+ decision = floor;
1077
+ native = true;
1042
1078
  }
1079
+ if (decision.kind !== "cut") return { messages };
1043
1080
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
1044
1081
  { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1045
1082
  run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1083
+ run!.nativeFloorPending = native;
1046
1084
  syncHistoryTools(ctx);
1047
- return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1048
- toolShapes(pi.getActiveTools()), true);
1085
+ return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1086
+ toolShapes(pi.getActiveTools()), true), native };
1049
1087
  };
1050
1088
  pi.on("context", (event, ctx) => {
1051
1089
  try {
@@ -1108,8 +1146,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1108
1146
  let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1109
1147
  let tokens = system + conversationTokens(messages);
1110
1148
  const { room, hardLine } = limits(ctx);
1111
- if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1112
- messages = guardCut(messages, tokens, system, ctx);
1149
+ let native = false;
1150
+ const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1151
+ piClamp && !requestClamp(messages, ctx).leavesFloor;
1152
+ if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1153
+ const cut = guardCut(messages, tokens, system, ctx);
1154
+ messages = cut.messages;
1155
+ native = Boolean(cut.native);
1113
1156
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1114
1157
  tokens = system + conversationTokens(messages);
1115
1158
  assertNativeToolRounds(messages);
@@ -1118,13 +1161,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1118
1161
  calibration.estimatedTokens = corrected(tokens, ctx);
1119
1162
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1120
1163
  throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
1121
- if (!fits(tokens, hardLine, ctx))
1164
+ // A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
1165
+ native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
1166
+ native &&= requestClamp(messages, ctx).fitsWindow;
1167
+ if (!native && !fits(tokens, hardLine, ctx))
1122
1168
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1123
- // Pi's request estimator and its compaction estimator need not agree. The hard line is
1124
- // necessary; above the room, also require the real request clamp to preserve the floor.
1125
- if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1169
+ // Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
1170
+ // only the refusal-path compiler floor may instead use native window admission.
1171
+ if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1126
1172
  throw new CapacityError(clampMessage);
1127
- if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1173
+ if (native) receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
1174
+ else if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1128
1175
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1129
1176
  recorder.request();
1130
1177
  // No system prompt or hidden assistant blocks; no provider payload/headers.
@@ -8,7 +8,7 @@ import { createRecall, type RecallPolicy } from './recall.js';
8
8
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
9
9
  import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
10
10
  export const DIAGNOSTIC_BUILD = BUILD_ID;
11
- export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; learnedContextWindow?: number; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
11
+ export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; learnedContextWindow?: number; catalogueContextWindow?: number; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
12
12
  export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
13
13
  const details = draft.details && typeof draft.details === 'object' ? draft.details as Record<string, unknown> : {};
14
14
  const receipt: Receipt = { id: randomUUID(), build: DIAGNOSTIC_BUILD, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
@@ -63,19 +63,24 @@ export const needsFullReplyReserve = (message: AgentMessage): boolean => message
63
63
  (message.stopReason === 'length' && !thinkingOnlyLength(message) || message.stopReason === 'error' && isContextOverflow(message));
64
64
 
65
65
  /** Saved immediately at the reply's turn boundary, even when recovery cannot make a compaction. */
66
- export interface WindowReceipt { calibrationIdentity: string; learnedContextWindow: number; serverClippedReplyId: string }
66
+ /** `catalogueContextWindow` is the model's configured window when the server clipped below it. A learned window holds only while the
67
+ * configured window is unchanged: a server or catalogue that grew must not stay capped by an old clip (Nautilus, 2026-11-20). */
68
+ export interface WindowReceipt { calibrationIdentity: string; learnedContextWindow: number; catalogueContextWindow: number; serverClippedReplyId: string }
67
69
  export const WINDOW_RECEIPT = 'pi-tuck-window';
68
70
  function windowSettings(entry: SessionEntry): Partial<WindowReceipt> | undefined {
69
71
  if (entry.type === 'custom' && entry.customType === WINDOW_RECEIPT) return entry.data as Partial<WindowReceipt> | undefined;
70
72
  if (entry.type === 'compaction') return (entry.details as { diagnosticReceipt?: { settings?: Partial<WindowReceipt> } } | undefined)?.diagnosticReceipt?.settings;
71
73
  return undefined;
72
74
  }
73
- export function seedContextWindow(branch: readonly SessionEntry[], identity: string): number | undefined {
75
+ /** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
76
+ * carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
77
+ export function seedContextWindow(branch: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined {
74
78
  for (let i = branch.length; i--;) {
75
79
  const settings = windowSettings(branch[i]!);
76
80
  if (settings?.calibrationIdentity !== identity) continue;
77
81
  const window = settings.learnedContextWindow;
78
- return Number.isSafeInteger(window) && window! > 0 ? window : undefined;
82
+ if (!(Number.isSafeInteger(window) && window! > 0)) return undefined;
83
+ return catalogue !== undefined && settings.catalogueContextWindow === catalogue ? window : undefined;
79
84
  }
80
85
  return undefined;
81
86
  }
package/src/run.ts CHANGED
@@ -117,9 +117,11 @@ export class Run {
117
117
  clips = new Map<string, Clip>();
118
118
  pendingBoundaryReceipts: string[] = [];
119
119
  thinkingRetryPending = false;
120
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
121
+ nativeFloorPending = false;
120
122
  refusalReceipted = false;
121
123
  clear() {
122
124
  this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
123
- this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
+ this.thinkingRetryPending = false; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
124
126
  }
125
127
  }