pi-mega-compact 0.21.8 → 0.21.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/dedup/degenerate.js +68 -0
  2. package/dist/extensions/dashboard-server/routes-dedup-attribution.js +8 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-compaction.js +42 -0
  4. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +8 -8
  5. package/dist/extensions/mega-config.js +12 -0
  6. package/dist/extensions/mega-events/context-handler/gateCheck.js +51 -1
  7. package/dist/extensions/mega-events/context-handler/headroom.js +128 -0
  8. package/dist/extensions/mega-events/context-handler/liveTrim.js +37 -51
  9. package/dist/extensions/mega-events/context-handler/pipelineRun.js +14 -1
  10. package/dist/extensions/mega-events/context-handler.js +26 -3
  11. package/dist/extensions/mega-pipeline/compact/run.js +14 -3
  12. package/dist/extensions/mega-runtime/dashboard-snapshot.js +1 -0
  13. package/dist/extensions/mega-runtime/runtime-instrumentation.js +1 -0
  14. package/dist/extensions/mega-runtime/runtime-snapshot.js +1 -0
  15. package/dist/src/config/dedup.js +3 -0
  16. package/dist/src/dedup/degenerate.js +68 -0
  17. package/dist/src/extractive-salvage.js +195 -0
  18. package/dist/src/extractive.js +63 -72
  19. package/dist/src/vector-cortex/dedup-attr/rollup.js +5 -0
  20. package/dist/src/vectorStore/add-degenerate.js +25 -0
  21. package/dist/src/vectorStore/add.js +28 -5
  22. package/dist/src/vectorStore/dedup-audit.js +8 -0
  23. package/dist/vector-cortex/dedup-attr/rollup.js +5 -0
  24. package/dist/vectorStore/dedup-audit.js +8 -0
  25. package/extensions/dashboard-server/api-contracts/endpoints/types.ts +2 -0
  26. package/extensions/dashboard-server/routes-dedup-attribution.ts +11 -1
  27. package/extensions/dashboard-server/routes-rag-settings-compaction.ts +91 -0
  28. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +13 -27
  29. package/extensions/mega-config-types.ts +25 -0
  30. package/extensions/mega-config.ts +12 -0
  31. package/extensions/mega-dashboard.ts +4 -1
  32. package/extensions/mega-events/context-handler/gateCheck.ts +67 -0
  33. package/extensions/mega-events/context-handler/headroom.ts +190 -0
  34. package/extensions/mega-events/context-handler/liveTrim.ts +37 -57
  35. package/extensions/mega-events/context-handler/pipelineRun.ts +14 -1
  36. package/extensions/mega-events/context-handler.ts +26 -3
  37. package/extensions/mega-pipeline/compact/run.ts +14 -4
  38. package/extensions/mega-runtime/dashboard-snapshot.ts +3 -0
  39. package/extensions/mega-runtime/runtime-instrumentation.ts +4 -0
  40. package/extensions/mega-runtime/runtime-snapshot.ts +2 -0
  41. package/package.json +1 -1
  42. package/src/config/dedup.ts +15 -0
  43. package/src/dedup/degenerate.ts +125 -0
  44. package/src/extractive-salvage.ts +212 -0
  45. package/src/extractive.ts +70 -75
  46. package/src/vector-cortex/dedup-attr/rollup.ts +4 -0
  47. package/src/vectorStore/add-degenerate.ts +64 -0
  48. package/src/vectorStore/add.ts +29 -5
  49. package/src/vectorStore/dedup-audit.ts +25 -2
@@ -303,6 +303,8 @@ export interface PerfDiag {
303
303
  readonly liveTrimFires: number;
304
304
  /** Number of live trim replays. */
305
305
  readonly liveTrimReplays: number;
306
+ /** v0.21.9: output-headroom gate trips (pre-overflow compaction fires). */
307
+ readonly headroomTrips: number;
306
308
  }
307
309
 
308
310
  /**
@@ -59,7 +59,17 @@ function parseAuditLine(line: string): DedupAuditEvent | null {
59
59
  const tier = obj.tier;
60
60
  const status = obj.status;
61
61
  if (tier !== "L0" && tier !== "L1" && tier !== "L2" && tier !== "new") return null;
62
- if (status !== "deduped" && status !== "passed" && status !== "stored") return null;
62
+ // "skipped" = a tier matched but the degenerate-match guard declined to
63
+ // collapse. Accepted so the line is not silently dropped from the tail; the
64
+ // rollup below counts only deduped/passed, so tier catch-share math is
65
+ // unchanged by its presence.
66
+ if (
67
+ status !== "deduped" &&
68
+ status !== "passed" &&
69
+ status !== "stored" &&
70
+ status !== "skipped"
71
+ )
72
+ return null;
63
73
  // sessionId is never read by the rollup; a parsed line may omit richer fields.
64
74
  return { type: "dedup_audit", ts: obj.ts, tier, status, sessionId: "" };
65
75
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * dashboard-server/routes-rag-settings-compaction.ts — Compaction SETTINGS.
3
+ *
4
+ * The compaction-group flag inventory, split out of routes-rag-settings-helpers.ts
5
+ * (delegate-shell split per the extensions/ 400-line soft limit) when the
6
+ * v0.21.9 output-headroom flags landed. regression_check.py globs every
7
+ * routes-rag-settings*.ts sibling, so no scanner update is needed on split.
8
+ *
9
+ * PREVENT-011: no `any` type.
10
+ */
11
+
12
+ import type { SettingSpec, SettingGroup } from "./routes-rag-settings-types.js";
13
+
14
+ const boolDirect = (
15
+ key: string,
16
+ label: string,
17
+ description: string,
18
+ def: boolean,
19
+ ): SettingSpec => ({
20
+ key,
21
+ label,
22
+ description,
23
+ type: "boolean",
24
+ default: def,
25
+ disabledConvention: false,
26
+ requiresLlm: false,
27
+ });
28
+
29
+ const num = (
30
+ key: string,
31
+ label: string,
32
+ description: string,
33
+ def: number,
34
+ min: number,
35
+ max: number,
36
+ unit?: string,
37
+ ): SettingSpec => ({
38
+ key,
39
+ label,
40
+ description,
41
+ type: "number",
42
+ default: def,
43
+ disabledConvention: false,
44
+ requiresLlm: false,
45
+ min,
46
+ max,
47
+ ...(unit ? { unit } : {}),
48
+ });
49
+
50
+ /** The compaction flags, as one SETTINGS category. */
51
+ export const COMPACTION_SETTINGS: SettingGroup = {
52
+ name: "Compaction",
53
+ settings: [
54
+ num(
55
+ "MEGACOMPACT_THRESHOLD_PCT",
56
+ "Compaction Threshold",
57
+ "Fraction of the actual model context window at which compaction fires — 0.80 fires at 80% used (leaves 20% free). Applies to any model size; a per-model Model Thresholds row overrides it",
58
+ 0.8,
59
+ 0.1,
60
+ 0.95,
61
+ ),
62
+ num(
63
+ "MEGACOMPACT_THRASH_REARM_PCT",
64
+ "Thrash Re-arm %",
65
+ "After an ineffective compaction (live window did not shrink), refuse to re-fire until the live window grows by this fraction of the effective threshold. Default 0.10 (10%)",
66
+ 0.1,
67
+ 0.01,
68
+ 0.5,
69
+ ),
70
+ boolDirect(
71
+ "MEGACOMPACT_OUTPUT_ERROR_COMPACT",
72
+ "Output-Error Compact",
73
+ "When a model response is truncated mid-output (stopReason: 'length'), trip a one-shot forced compaction to free input headroom. Closes the small-context deadlock where the model truncates below the input threshold.",
74
+ true,
75
+ ),
76
+ boolDirect(
77
+ "MEGACOMPACT_OVERFLOW_HEADROOM",
78
+ "Overflow Headroom Gate",
79
+ "Fire compaction BEFORE the request overflows the model window — when input tokens + the output reserve + safety margin would exceed the context window — instead of waiting for the percent fire point (which judges only INPUT and never trips on small-window models whose output budget is a large fraction of the window). Percent-based: the reserve scales with the model's own window, so the math holds at every window size (32k…5M). OFF disables this pre-fire check (the gate reverts to input-only judgment); the pair-safe tail-cap hardenings are unconditional safety fixes and remain active.",
80
+ true,
81
+ ),
82
+ num(
83
+ "MEGACOMPACT_OUTPUT_RESERVE_PCT",
84
+ "Output Reserve %",
85
+ "FALLBACK output reserve as a fraction of the context window, used only when the model's declared maxTokens is absent or implausible (0, or a models.json sentinel like 1e9/1e38, or >= the window). When maxTokens IS plausible the declared value wins — vLLM-style backends reserve the FULL declared maxTokens. Default 0.30 (30%), clamped 0.10–0.95.",
86
+ 0.3,
87
+ 0.1,
88
+ 0.95,
89
+ ),
90
+ ],
91
+ };
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import type { SettingSpec, SettingGroup } from "./routes-rag-settings-types.js";
11
11
  import { VECTOR_CORTEX_SETTINGS } from "./routes-rag-settings-vector-cortex.js";
12
+ import { COMPACTION_SETTINGS } from "./routes-rag-settings-compaction.js";
12
13
 
13
14
  export type { SettingSpec } from "./routes-rag-settings-types.js";
14
15
 
@@ -227,6 +228,12 @@ export const SETTINGS: ReadonlyArray<SettingGroup> = [
227
228
  boolDirect("MEGACOMPACT_MARK_ONLY_L1", "Mark Only L1", "L1 runs but does not collapse", false),
228
229
  boolDirect("MEGACOMPACT_MARK_ONLY_L2", "Mark Only L2", "L2 runs but does not collapse", false),
229
230
  boolDirect("MEGACOMPACT_MINILM", "MiniLM Embedder", "Use MiniLM instead of trigram", false),
231
+ boolDirect(
232
+ "MEGACOMPACT_DEDUP_DEGENERATE_GUARD",
233
+ "Degenerate Match Guard",
234
+ "Decline an L1/L2 collapse when the MATCHED stored checkpoint is a content-free skeleton (a ~30-40 token structural summary) and the incoming region is richer. Without this, one degenerate checkpoint absorbs every later compaction forever and the store can never heal. OFF = byte-identical pre-guard cascade. Calibrated by the two Degenerate floors under Dedup Thresholds.",
235
+ true,
236
+ ),
230
237
  boolDirect(
231
238
  "MEGACOMPACT_DEDUP_AUDIT",
232
239
  "Dedup Audit Trail",
@@ -241,6 +248,8 @@ export const SETTINGS: ReadonlyArray<SettingGroup> = [
241
248
  num("MEGACOMPACT_L2_THRESHOLD", "L2 Cosine Threshold", "L2 semantic dedup firing point", 0.85, 0, 1),
242
249
  num("MEGACOMPACT_L1_JACCARD", "L1 Jaccard Threshold", "L1 MinHash near-dup threshold", 0.8, 0, 1),
243
250
  num("MEGACOMPACT_DEDUP_SIM", "Dedup Similarity", "Legacy content-similarity fallback", 0.9, 0, 1),
251
+ num("MEGACOMPACT_DEDUP_DEGEN_MIN_TOKENS", "Degenerate Min Tokens", "Absolute token floor below which a stored summary counts as a degenerate skeleton (Degenerate Match Guard)", 48, 0, 10000, "tokens"),
252
+ num("MEGACOMPACT_DEDUP_DEGEN_MIN_PCT", "Degenerate Min Percent", "Relative floor as a fraction of the summary's original region size; a summary under max(min-tokens, pct x original) is degenerate", 0.005, 0, 1),
244
253
  num("MEGACOMPACT_RECALL_MIN_COSINE", "Recall Min Cosine (same-repo)", "3WF-3 same-repo floor the 3-source validator applies to the top winner (cross-repo 0.90 stays separate)", 0.12, 0, 1),
245
254
  num("MEGACOMPACT_MMR_LAMBDA", "MMR Lambda", "Maximal Marginal Relevance diversity", 0.5, 0, 1),
246
255
  num("MEGACOMPACT_SEMDEDUP_COSINE", "SemDeDup Cosine", "Offline SemDeDup pair threshold", 0.95, 0, 1),
@@ -275,33 +284,10 @@ export const SETTINGS: ReadonlyArray<SettingGroup> = [
275
284
  num("MEGACOMPACT_EMBEDDING_CHARS_PER_TOKEN", "Embedding Chars per Token", "Estimated characters per token used for embedder chunking size", 4, 1, 32),
276
285
  ],
277
286
  },
278
- {
279
- name: "Compaction",
280
- settings: [
281
- num(
282
- "MEGACOMPACT_THRESHOLD_PCT",
283
- "Compaction Threshold",
284
- "Fraction of the actual model context window at which compaction fires — 0.80 fires at 80% used (leaves 20% free). Applies to any model size; a per-model Model Thresholds row overrides it",
285
- 0.8,
286
- 0.1,
287
- 0.95,
288
- ),
289
- num(
290
- "MEGACOMPACT_THRASH_REARM_PCT",
291
- "Thrash Re-arm %",
292
- "After an ineffective compaction (live window did not shrink), refuse to re-fire until the live window grows by this fraction of the effective threshold. Default 0.10 (10%)",
293
- 0.1,
294
- 0.01,
295
- 0.5,
296
- ),
297
- boolDirect(
298
- "MEGACOMPACT_OUTPUT_ERROR_COMPACT",
299
- "Output-Error Compact",
300
- "When a model response is truncated mid-output (stopReason: 'length'), trip a one-shot forced compaction to free input headroom. Closes the small-context deadlock where the model truncates below the input threshold.",
301
- true,
302
- ),
303
- ],
304
- },
287
+ // v0.21.9: compaction group extracted to keep this file under the
288
+ // extensions/ soft limit (delegate-shell split); carries the overflow-
289
+ // headroom + output-reserve flags alongside the pre-existing trio.
290
+ COMPACTION_SETTINGS,
305
291
  {
306
292
  name: "Three-Way Failback",
307
293
  settings: [
@@ -141,6 +141,31 @@ export interface MegaConfig {
141
141
  * gate never fires → "compact never" → every subsequent response truncates
142
142
  * too). Default ON; OFF (=0/`=false`) = byte-identical pre-H. */
143
143
  outputErrorCompact: boolean;
144
+ /** v0.21.9: output-headroom gate. Fire compaction BEFORE the request
145
+ * overflows the model window — when
146
+ * `currentTokens + outputReserve + safetyMargin >= contextWindow` —
147
+ * instead of waiting for the percent/token fire point (which judges only
148
+ * INPUT and never trips on small-window models whose output reserve is a
149
+ * large fraction of the window: a 32k window with a 20k maxTokens
150
+ * overflows at ~37% INPUT). Percent-based by construction: the reserve is
151
+ * a fraction of the model's own window, so the math is identical at every
152
+ * window size (32k, 64k, 200k, 1M, 5M). Default ON; OFF (=0/`=false`)
153
+ * disables ONLY the pre-fire gate check (the gate reverts to the
154
+ * input-only pre-v0.21.9 judgment). NOTE: the shared tail-cap hardenings
155
+ * this fix introduced — pair-safe front-drop (the pre-v0.21.9 cap could
156
+ * split a toolCall/toolResult pair, PREVENT-PI-002) and the budget floor
157
+ * (the old cap silently disabled itself when the reserve exceeded the
158
+ * window) — are UNCONDITIONAL guardrail fixes and apply regardless of
159
+ * this flag. Headroom-triggered fires are EXEMPT from the ThrashGuard
160
+ * (an overflowed session is unrecoverable). */
161
+ overflowHeadroom: boolean;
162
+ /** v0.21.9: fallback output reserve as a fraction of the context window
163
+ * when the model's declared maxTokens is absent or implausible (0, or the
164
+ * models.json sentinels 1e9/1e38, or >= the window). Clamped [0.1, 0.95];
165
+ * default 0.30 (30% of the window). When maxTokens is plausible the
166
+ * declared value wins — vLLM-style backends reserve the FULL declared
167
+ * maxTokens against the context window, so the reserve must match it. */
168
+ outputReservePct: number;
144
169
  /** Inline-dedupe recalled checkpoints against the live window (Fix C): drop
145
170
  * a hit whose summary is ≥ dedupSim similar to a live message — "dedupe on
146
171
  * inline/read" so we never re-inject context already resident. */
@@ -253,6 +253,18 @@ export function loadConfig(): MegaConfig {
253
253
  // Phase H: output-error catch — trip compaction on a truncated model output
254
254
  // (S28 stopReason==='length'). Default ON; OFF byte-identical pre-H.
255
255
  outputErrorCompact: envBool("MEGACOMPACT_OUTPUT_ERROR_COMPACT", true),
256
+ // v0.21.9 OUTPUT-HEADROOM GATE: fire compaction BEFORE the request
257
+ // overflows the model window (input + output reserve + margin >= window),
258
+ // not after. Percent-based: the reserve scales with the model's own window
259
+ // so the math holds at every window size (32k…5M). Default ON;
260
+ // OFF = byte-identical pre-v0.21.9 (2026-08-19 32k incident fix).
261
+ overflowHeadroom: envBool("MEGACOMPACT_OVERFLOW_HEADROOM", true),
262
+ // v0.21.9: fallback OUTPUT reserve as a FRACTION of the context window,
263
+ // used when the model's declared maxTokens is absent or implausible
264
+ // (0 / sentinel 1e9/1e38 / >= window). Clamped [0.1, 0.95]; default 0.30.
265
+ // When maxTokens IS plausible the declared value wins (vLLM reserves the
266
+ // full maxTokens) — this fraction is only the fallback.
267
+ outputReservePct: clamp(envFlag("MEGACOMPACT_OUTPUT_RESERVE_PCT", 0.3), 0.1, 0.95),
256
268
  windowDedupe: envBool("MEGACOMPACT_WINDOW_DEDUPE", true),
257
269
  recallTailInject: envBool("MEGACOMPACT_RECALL_TAIL_INJECT", true),
258
270
  // 3WF-1: TriggerGuard — guarantee a staged recall block on every context
@@ -142,11 +142,14 @@ export interface DashboardSnapshot {
142
142
  outputRate: number; // USD per output token (Model.cost)
143
143
  };
144
144
  /** v0.8.8 Perf dashboard: live diag counters (skip vs recompute vs replay)
145
- * for the Perf tab's "TUI lag proxy" cards. Optional for back-compat. */
145
+ * for the Perf tab's "TUI lag proxy" cards. Optional for back-compat.
146
+ * v0.21.9: headroomTrips added (output-headroom gate trips); readers that
147
+ * don't know it stay backward-compatible. */
146
148
  diag?: {
147
149
  ctxFastGate: number;
148
150
  liveTrimFires: number;
149
151
  liveTrimReplays: number;
152
+ headroomTrips?: number;
150
153
  };
151
154
  /** S38.8: error-retry state for dashboard "retries" tile.
152
155
  * R7 (retry redesign): sessionRetryCount / sessionMax / poisonedCount are
@@ -18,6 +18,7 @@ import { autoCompactCheck } from "../../../src/compact.js";
18
18
  import type { MegaRuntime } from "../../mega-runtime.js";
19
19
  import type { MegaConfig } from "../../mega-config.js";
20
20
  import { isThrashBlockedFor } from "./thrashGuard.js";
21
+ import { resolveOutputReserve } from "./headroom.js";
21
22
 
22
23
  /** Tail-injection closure shape produced by buildTailResult (tailResult.ts). */
23
24
  export type TailResultFn = (
@@ -30,6 +31,14 @@ export type GateOutcome =
30
31
  | {
31
32
  kind: "proceed";
32
33
  perModelThreshold: { safetyMarginPct: number; firePointPct: number };
34
+ /**
35
+ * v0.21.9: true when the proceed was forced by the output-headroom
36
+ * check (the request would overflow the model window before reaching
37
+ * the percent/token fire point). Consumed by thrashGuardBlocks so an
38
+ * overflow-bound fire is never refused by the thrash guard — an
39
+ * overflowed session is unrecoverable (2026-08-19 32k incident).
40
+ */
41
+ headroomExceeded?: boolean;
33
42
  };
34
43
 
35
44
  /**
@@ -55,9 +64,16 @@ export function thrashGuardBlocks(
55
64
  runtime: MegaRuntime,
56
65
  config: MegaConfig,
57
66
  currentTokens: number | null | undefined,
67
+ headroomExceeded?: boolean,
58
68
  ): boolean {
59
69
  if (!config.threeWayFailback) return false;
60
70
  if (currentTokens == null) return false;
71
+ // v0.21.9: an overflow-bound fire (headroomExceeded) is EXEMPT from the
72
+ // thrash guard. The guard exists to stop wasted re-compaction when the
73
+ // window refuses to shrink; but an overflowed request is not "wasted work"
74
+ // — it is the model about to 400. Blocking that fire reproduces the
75
+ // 2026-08-19 32k deadlock (compact never → request > window → error loop).
76
+ if (headroomExceeded) return false;
61
77
  return isThrashBlockedFor(runtime, currentTokens, runtime.currentStateDir);
62
78
  }
63
79
 
@@ -113,6 +129,57 @@ export function evaluateGate(
113
129
  return { kind: "proceed", perModelThreshold };
114
130
  }
115
131
 
132
+ // v0.21.9 OUTPUT-HEADROOM GATE (the root-cause fix for the 32k truncation
133
+ // loop). The percent/token fire points above judge only INPUT utilization
134
+ // (tier% of the window), but a request's budget is
135
+ // input tokens + the model's output budget + safety margin.
136
+ // On a small-window model with a large maxTokens (the user's 32k/20k
137
+ // GLM-4.7), the request overflows at ~32% INPUT (21.4k + 20k > 32.768k) —
138
+ // long before any percent gate fires → provider 400 "request exceeds the
139
+ // available context size" every turn → the poisoned-error loop. Phase H only
140
+ // reacts to stopReason 'length' (mid-output truncation); a pre-output 400
141
+ // never arms it, so "compact never". This check fires the compaction
142
+ // BEFORE the overflow instead of after.
143
+ //
144
+ // PERCENT-BASED (LTS invariant — must work at every window size: 32k, 64k,
145
+ // 200k, 1M, 5M): the reserve is a FRACTION of the model's own window via
146
+ // resolveOutputReserve (plausible declared maxTokens wins, else
147
+ // clamp(MEGACOMPACT_OUTPUT_RESERVE_PCT, 10–95%) × window). Same math, any
148
+ // size. window <= 0 (unknown) ⇒ deferred (never guess a window), matching
149
+ // the effectiveThresholdImpl Phase-C invariant. Gated on
150
+ // config.overflowHeadroom (default ON; OFF = byte-identical pre-v0.21.9).
151
+ // Thrash-guard exemption: headroomExceeded rides along on the proceed so the
152
+ // handler's thrash consult never refuses an overflow-bound fire (see
153
+ // thrashGuardBlocks above) — an overflowed session is unrecoverable, so a
154
+ // wasted re-fire is always the better outcome (2026-08-19 incident).
155
+ if (
156
+ config.overflowHeadroom &&
157
+ runtime.lastCtxWindow > 0 &&
158
+ Number.isFinite(currentTokens) &&
159
+ currentTokens > 0
160
+ ) {
161
+ const { reserveTokens, fallbackUsed } = resolveOutputReserve(
162
+ runtime.lastCtxWindow,
163
+ runtime.currentModel?.maxTokens ?? 0,
164
+ config.outputReservePct,
165
+ );
166
+ const headroomMargin = Math.ceil(
167
+ runtime.lastCtxWindow * (perModelThreshold.safetyMarginPct / 100),
168
+ );
169
+ if (currentTokens + reserveTokens + headroomMargin >= runtime.lastCtxWindow) {
170
+ runtime.diagCtxHeadroomTrip++;
171
+ runtime.logger.info("gate-headroom-trip", {
172
+ sessionId: runtime.rt.sessionId,
173
+ currentTokens,
174
+ ctxWindow: runtime.lastCtxWindow,
175
+ reserveTokens,
176
+ fallbackUsed,
177
+ marginPct: perModelThreshold.safetyMarginPct,
178
+ });
179
+ return { kind: "proceed", perModelThreshold, headroomExceeded: true };
180
+ }
181
+ }
182
+
116
183
  // S29 FAST GATE: `custom` (absolute MEGACOMPACT_THRESHOLD_TOKENS,
117
184
  // tierPct null) is an explicit opt-out of percent scaling — it keeps the
118
185
  // token gate. When pct is unavailable (window unknown / a model that
@@ -0,0 +1,190 @@
1
+ /**
2
+ * context-handler/headroom.ts — output-headroom reserve math + pair-safe tail cap.
3
+ *
4
+ * v0.21.9. Single source of truth for the output reserve used by BOTH the
5
+ * gate's pre-fire overflow check (gateCheck.ts) and the live-trim tail cap
6
+ * (liveTrim.ts + the D.2/D.3 replay paths). The pre-v0.21.9 code computed the
7
+ * reserve inline in liveTrim only and never in the gate — the two halves could
8
+ * drift, and the gate had no output awareness at all.
9
+ *
10
+ * PERCENT-BASED BY DESIGN (per the LTS invariant): every quantity is expressed
11
+ * as a fraction of the MODEL'S OWN context window, so the math is identical at
12
+ * any window size — 32k, 64k, 200k, 1M, 5M. The reserve is the model's
13
+ * declared max output tokens when plausible, else a clamped fraction of the
14
+ * window (MEGACOMPACT_OUTPUT_RESERVE_PCT, default 30%, clamped 10–95%).
15
+ *
16
+ * Pure functions, no runtime dependency — trivially unit-testable headlessly.
17
+ */
18
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
19
+ import { estimateBlockTokens, estimateMessageTokens } from "../../../src/tokens.js";
20
+ import { messageContentText } from "./messageText.js";
21
+
22
+ /**
23
+ * The model's declared maxTokens is only trusted as the output budget when it
24
+ * is plausible. models.json carries sentinel junk for some entries (1e9,
25
+ * 1e38, "unlimited"), and some providers report 0/absent. A declared budget
26
+ * above this FRACTION of the window is implausible — fall back to the
27
+ * configured fraction so a 200k/1e9 model doesn't compute a negative budget
28
+ * and silently disable the cap (the pre-v0.21.9 bug). Percent-based: holds at
29
+ * every window size.
30
+ *
31
+ * WHY 0.95 AND NOT LOWER: vLLM-style backends reject a request when
32
+ * `input + max_tokens > context window` — they reserve the model's FULL
33
+ * declared maxTokens, not a fraction of it. The user's own GLM-4.7 entry is
34
+ * 32000/20000 (62.5%); a 0.6 cutoff rejected that REAL config as
35
+ * "implausible" and fell back to a 30% reserve (9600) while the backend
36
+ * reserved the full 20000 — the gate would keep firing late and the
37
+ * post-compact tail would still overflow (2026-08-19 incident, attempt #6).
38
+ * A declared budget is plausible up to just below the WHOLE window; anything
39
+ * at/above the window (or the 1e9/1e38 sentinels) is junk.
40
+ */
41
+ export const MAX_OUTPUT_PLAUSIBLE_FRACTION = 0.95;
42
+
43
+ /** Bounds for the fallback reserve fraction (MEGACOMPACT_OUTPUT_RESERVE_PCT). */
44
+ export const OUTPUT_RESERVE_PCT_MIN = 0.1;
45
+ export const OUTPUT_RESERVE_PCT_MAX = 0.95;
46
+
47
+ /**
48
+ * Resolve the output reserve (tokens) for a model window.
49
+ *
50
+ * - window <= 0 (unknown) → { reserveTokens: 0, fallbackUsed: false }; every
51
+ * consumer is guarded on window > 0 and defers (never guesses a window).
52
+ * - maxTokens plausible (0 < maxTokens <= 95% of the window) → maxTokens —
53
+ * vLLM-style backends reserve the FULL declared maxTokens, so the reserve
54
+ * must equal it, not a fraction of it.
55
+ * - otherwise → clamp(outputReservePct, 0.1, 0.95) × window.
56
+ *
57
+ * `outputReservePct` is config.outputReservePct (already env-clamped at load,
58
+ * re-clamped here for defense against direct callers).
59
+ */
60
+ export function resolveOutputReserve(
61
+ ctxWindow: number,
62
+ maxTokens: number,
63
+ outputReservePct: number,
64
+ ): { reserveTokens: number; fallbackUsed: boolean } {
65
+ if (!Number.isFinite(ctxWindow) || ctxWindow <= 0) {
66
+ return { reserveTokens: 0, fallbackUsed: false };
67
+ }
68
+ const plausible =
69
+ Number.isFinite(maxTokens) &&
70
+ maxTokens > 0 &&
71
+ maxTokens <= ctxWindow * MAX_OUTPUT_PLAUSIBLE_FRACTION;
72
+ if (plausible) return { reserveTokens: Math.round(maxTokens), fallbackUsed: false };
73
+ const pct = Math.min(
74
+ OUTPUT_RESERVE_PCT_MAX,
75
+ Math.max(OUTPUT_RESERVE_PCT_MIN, Number.isFinite(outputReservePct) ? outputReservePct : 0.3),
76
+ );
77
+ return { reserveTokens: Math.ceil(ctxWindow * pct), fallbackUsed: true };
78
+ }
79
+
80
+ /**
81
+ * Pair-safe front-drop for the live-trim tail cap. Drops OLDEST messages from
82
+ * the front of `recentRaw` until the remaining tail fits
83
+ * `ctxWindow − outputReserve − safetyMargin − summaryTokens`, then advances
84
+ * the start index past any leading toolResult messages so the preserved tail
85
+ * never begins on an orphaned toolResult (PREVENT-PI-002: a toolCall/toolResult
86
+ * pair must not be split). Never returns an empty tail — the final message is
87
+ * always kept so the agent can respond.
88
+ *
89
+ * v0.21.9 hardenings over the pre-v0.21.9 inline cap in liveTrim.ts:
90
+ * 1. BUDGET FLOOR — when the reserve exceeds the window (implausible maxTokens
91
+ * made budget <= 0) the old block silently skipped the cap entirely and an
92
+ * oversized tail sailed past the window. Now the reserve is clamped (via
93
+ * resolveOutputReserve) to a fraction of the window, so a floor budget
94
+ * always exists. If even ONE message exceeds the floor budget we keep only
95
+ * the final message — the agent's last turn is the one thing the model
96
+ * must always see.
97
+ * 2. TOOL-PAIR SAFETY — the old front-drop could land between a toolCall and
98
+ * its toolResult, splitting the pair.
99
+ *
100
+ * Pure: returns { recent, dropped } without touching the input array.
101
+ */
102
+ export function applyTailCap(opts: {
103
+ recentRaw: readonly AgentMessage[];
104
+ summaryTokens: number;
105
+ ctxWindow: number;
106
+ maxOutputTokens: number;
107
+ outputReservePct: number;
108
+ safetyMarginPct: number;
109
+ /**
110
+ * Optional token-count override for the tail messages. When present, the
111
+ * token sum is counted from this array (index-aligned with `recentRaw`);
112
+ * otherwise each message's tokens are estimated from its text content.
113
+ */
114
+ messageTokens?: readonly number[];
115
+ }): { recent: AgentMessage[]; dropped: number } {
116
+ const { recentRaw, summaryTokens, ctxWindow, outputReservePct } = opts;
117
+ if (ctxWindow <= 0 || recentRaw.length <= 1) {
118
+ return { recent: [...recentRaw], dropped: 0 };
119
+ }
120
+ const msgTokens =
121
+ opts.messageTokens && opts.messageTokens.length === recentRaw.length
122
+ ? opts.messageTokens
123
+ : null;
124
+ const { reserveTokens } = resolveOutputReserve(
125
+ ctxWindow,
126
+ opts.maxOutputTokens,
127
+ outputReservePct,
128
+ );
129
+ const safetyMargin = Math.ceil(
130
+ ctxWindow * (Math.max(0, opts.safetyMarginPct) / 100),
131
+ );
132
+ // Budget floor: never negative. An implausible reserve (clamped above to
133
+ // <= 95% of the window) plus margin + summary can still exceed the window
134
+ // on tiny summaries-free edges; the floor keeps the cap alive with a small
135
+ // positive budget instead of disabling it (pre-v0.21.9 behavior).
136
+ const budget = Math.max(
137
+ 1,
138
+ ctxWindow - reserveTokens - safetyMargin - Math.max(0, summaryTokens),
139
+ );
140
+ let start = 0;
141
+ let tailTokens = 0;
142
+ for (let i = recentRaw.length - 1; i >= 0; i--) {
143
+ tailTokens +=
144
+ msgTokens != null
145
+ ? Math.max(0, msgTokens[i])
146
+ : estimateMessageTokens({ text: messageContentText(recentRaw[i]) });
147
+ if (tailTokens > budget) {
148
+ // Keep from i+1 onward; never drop below the FINAL message.
149
+ start = Math.min(i + 1, recentRaw.length - 1);
150
+ break;
151
+ }
152
+ }
153
+ // PREVENT-PI-002: never begin the preserved tail on an orphaned toolResult —
154
+ // its toolCall was dropped by the front-cut above. Advance past consecutive
155
+ // toolResults; the pair stays intact or drops whole.
156
+ while (
157
+ start < recentRaw.length - 1 &&
158
+ (recentRaw[start] as { role?: string }).role === "toolResult"
159
+ ) {
160
+ start++;
161
+ }
162
+ return { recent: recentRaw.slice(start), dropped: start };
163
+ }
164
+
165
+ /**
166
+ * v0.21.9: re-cap a REPLAYED trim tail (D.2 in context-handler.ts, D.3 in
167
+ * pipelineRun.ts). The replay paths return the cached trim view verbatim —
168
+ * which bypasses the fire-time tail cap. A model switch mid-epoch can shrink
169
+ * the window, leaving a replayed tail that fit the OLD window overflowing the
170
+ * NEW one. Re-runs applyTailCap against the CURRENT window with the margin
171
+ * stored at fire time (trimCache.safetyMarginPct), so the replayed view never
172
+ * exceeds what the gate would allow. Pure — no runtime dependency.
173
+ */
174
+ export function recapReplayedTail(opts: {
175
+ recentRaw: readonly AgentMessage[];
176
+ summaryAgentMsg: AgentMessage;
177
+ ctxWindow: number;
178
+ maxOutputTokens: number;
179
+ outputReservePct: number;
180
+ safetyMarginPct: number;
181
+ }): { recent: AgentMessage[]; dropped: number } {
182
+ return applyTailCap({
183
+ recentRaw: opts.recentRaw,
184
+ summaryTokens: estimateBlockTokens(messageContentText(opts.summaryAgentMsg)),
185
+ ctxWindow: opts.ctxWindow,
186
+ maxOutputTokens: opts.maxOutputTokens,
187
+ outputReservePct: opts.outputReservePct,
188
+ safetyMarginPct: opts.safetyMarginPct,
189
+ });
190
+ }