diff --git a/src/acp-status.ts b/src/acp-status.ts index 7c6af1c614..0e539a7325 100644 --- a/src/acp-status.ts +++ b/src/acp-status.ts @@ -37,6 +37,10 @@ function fmtBytes(n: number): string { return `${(n / (1024 * 1024)).toFixed(1)}MiB`; } +// #2366: usage fraction at which the PRESSURE NOTE becomes worth showing — +// below it the window still has headroom and "stop folding" is noise. +const PRESSURE_NOTE_USAGE_FRACTION = 0.6; + export function handleAcpStatus(args: Record, ctx: AcpStatusCtx): ProxyToolResult { const scope = typeof args.scope === "string" ? (args.scope as "compressed" | "uncompressed") : undefined; const view = typeof args.view === "string" ? (args.view as "ranges" | "messages") : undefined; @@ -56,6 +60,37 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx }); if (scope) return toolOk(base); const extra: string[] = []; + // #2366: everything in the report above is LOCAL ESTIMATES (defaultCountTokens); + // on CJK-heavy routes upstream billing runs 2–4× higher, so an agent judging + // pressure from those figures misreads a filling window as healthy and folds + // late, when little compressible mass is left. Surface the usage-grade reading + // next to the estimate view — statusInputBaseline's provenance contract, the + // same number the nudge decision runs on — and flag the ratio when it diverges + // hard. Never-reporting upstreams have no anchor → no line. + const billed = statusInputBaseline(ctx.session); + if (billed > 0) { + let estTotal = 0; + for (const m of ctx.messages) estTotal += defaultCountTokens(m.text ?? ""); + // Billed input covers system+tools too (and images); the est view must + // carry the same overhead — every prepare site keeps + // metadata.systemPromptTokens current — or every system-heavy session + // reads as divergence with no tokenizer gap behind it. + const sysOverhead = ctx.session.metadata?.systemPromptTokens; + if (typeof sysOverhead === "number" && sysOverhead > 0) estTotal += sysOverhead; + const srcLabel = ctx.session.stats.lastInputTokensSource === "overflow-arm" ? "overflow arm (bounded)" : "upstream usage"; + let billedLine = `BILLED INPUT (${srcLabel}): ${billed} tok`; + const measuredAt = ctx.session.metadata?.contextTokensAt; + if (typeof measuredAt === "number") { + const ageMin = Math.round((Date.now() - measuredAt) / 60_000); + if (ageMin >= 2) billedLine += `, measured ${ageMin}m ago`; + } + if (estTotal > 0) billedLine += ` · est-view total ${estTotal} tok · ratio ${(billed / estTotal).toFixed(1)}×`; + extra.push(""); + extra.push(billedLine); + if (estTotal > 0 && billed / estTotal >= 1.5) { + extra.push("NOTE: the token figures in the report above are local estimates and run well below what upstream actually bills (tokenizer-dependent; CJK-heavy content is the usual cause). Judge context pressure from BILLED INPUT; use the breakdown only to locate what to compress."); + } + } try { const turn = ctx.core.processTurn({ messages: ctx.messages, @@ -69,6 +104,13 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx if (nudge) { extra.push(""); extra.push(nudge.shouldInject ? `Nudge: ACTIVE — ${nudge.reason}` : `Nudge: idle — ${nudge.reason}`); + // #2366: high billed pressure + exhausted compressible mass is the + // deadlock invisible from the estimate view alone — tell the agent + // further folding is futile (each fold rewrites the prefix and + // forfeits the cache hit for almost-nothing reclaimed). + if (!nudge.shouldInject && nudge.contextUsage >= PRESSURE_NOTE_USAGE_FRACTION && nudge.breakdown.maxPending < nudge.breakdown.nudgeGrowthTokens) { + extra.push(`PRESSURE NOTE: billed input sits at ${Math.round(nudge.contextUsage * 100)}% of the ${ctx.config.modelContextLimit}-token limit while max compressible mass is only ~${nudge.breakdown.maxPending} tokens — little left to fold. Repeated small folds rewrite the prefix (forfeiting cache hits) while reclaiming almost nothing; continue the task instead of folding again unless pressure climbs further.`); + } // #847: only advertise ranges the submit gate accepts — the gate // counts raw chars (minCompressRange), not tokens, so a range can // be "viable" yet deterministically uncompressible. diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index 83a1fb2a32..0620faa821 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -953,10 +953,10 @@ export function recordCacheSample( * no cache tokens (recordCacheSample quarantines that sample). */ // #1933 F1: estimator calibration constants. The local chars/4 estimate is a // proxy whose ratio to real billing varies per upstream (observed 1.3–2.5× on -// one relay vs ~1.0× on another in the same session), so k̂ is learned per +// one relay vs ~1.0× on another in the same session; CJK-heavy content on +// llama-family tokenizers runs 2.4–4.0× ABOVE it, #2366), so k̂ is learned per // route and only applied on that route. Samples below MIN are noise (tiny -// requests), clamps bound a single pathological sample from wrecking the EMA -// and pin the correction to the deflate direction only (max 1, see below). +// requests), clamps bound a single pathological sample from wrecking the mean. const CALIBRATION_MIN_ESTIMATE = 2000; // Plausibility band for admitting a sample: outside it, the report and the // payload it bills demonstrably don't correspond (placeholder billing, relay @@ -964,16 +964,22 @@ const CALIBRATION_MIN_ESTIMATE = 2000; export const CALIBRATION_SAMPLE_MIN = 0.2; export const CALIBRATION_SAMPLE_MAX = 5; // Final clamp on the published factor: bounds how far calibration can move -// any decision away from the raw estimate. One-way by design: the clamp max -// is 1, so a learned factor can only DEFLATE the estimate (fire later than -// the raw proxy would), never inflate it. Routes whose billing runs ABOVE -// the local estimate (samples >1) publish k̂=1 — legacy raw behavior — and -// stay covered by the overflow arm / learn-on-failure ladder instead. This -// eliminates the class "calibration itself causes an earlier trigger": the -// observed #1933 damage was over-triggering (37% window tax, fold churn), -// while the opposite error already has a backstop. Discussion: PR #1940. +// any decision away from the raw estimate, in BOTH directions since #2366. +// It was one-way (max 1, "deflate only") by PR #1940's design: inflated +// estimates were deemed safe because they just fire early, with the overflow +// arm as backstop. That premise failed empirically on CJK routes — the +// estimator runs 2.4–4.0× BELOW real billing there (#2366 evidence: 53K +// estimated vs 152,903 billed), so under-estimating routes published k̂=1 +// forever: the >1 samples were collected into the ring and discarded at +// publish, and every decision (preflight trigger, output budget, the +// agent-visible status) stayed in the wrong caliber until the window filled +// past recoverable compression. The max now bounds symmetric inflation at 4×: +// it covers the measured CJK band and stays BELOW CALIBRATION_SAMPLE_MAX (5), +// so non-corresponding reports are still rejected before the clamp sees them. +// Wild values remain bounded by the evidence gates: ≥2 recent samples agreeing +// within ×2, keyed by route AND model, MIN_ESTIMATE floor. export const CALIBRATION_CLAMP_MIN = 0.25; -export const CALIBRATION_CLAMP_MAX = 1; +export const CALIBRATION_CLAMP_MAX = 4; // Evidence requirements: ≥2 recent same-route samples agreeing within ×2. // One lucky/degenerate pair must not flip every estimate on the route. export const CALIBRATION_SAMPLE_WINDOW = 3; diff --git a/src/persist.ts b/src/persist.ts index 42b7207883..a42b101e62 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -787,11 +787,11 @@ function isBlockView(v: unknown): v is BlockView { } // #2129: restore-time validation for the #1933 F1 calibrated factor. The learner -// publishes factors clamped to [CLAMP_MIN, CLAMP_MAX], but applyEstimateCalibration -// applies whatever it is given UNCLAMPED — a corrupt/hand-edited file with k̂>1 -// would INFLATE every estimate (violating the one-way deflate contract) and -// k̂<0.25 over-deflates past the published band. Reject out-of-band values instead -// of trusting them: absent falls back to the raw estimate (today's behavior). +// publishes factors clamped to [CLAMP_MIN, CLAMP_MAX] (two-way since #2366), but +// applyEstimateCalibration applies whatever it is given UNCLAMPED — a corrupt or +// hand-edited file outside the published band would move every calibrated reading +// off-scale (k̂>4 over-inflates, k̂<0.25 over-deflates). Reject out-of-band values +// instead of trusting them: absent falls back to the raw estimate (legacy behavior). function restoreCalibratedEstimate(v: unknown): number | undefined { return typeof v === "number" && Number.isFinite(v) && v >= CALIBRATION_CLAMP_MIN && v <= CALIBRATION_CLAMP_MAX ? v : undefined; } diff --git a/src/server.ts b/src/server.ts index fb4ebeea36..41b6982ed5 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4417,11 +4417,11 @@ async function preflightCompressIfNeeded( } // #1933 F1: scale the local text estimate by the per-route calibration // factor k̂ learned from this session's own usage reports (local estimate ÷ - // what upstream actually billed, EMA, clamped 0.25–1 — one-way, deflate - // only; see settleUsageReport). Unknown/mismatched origin → raw estimate, - // i.e. today's behavior. #2117 B: the model dimension gates too — a factor - // learned on another model acts as absent here rather than deciding with a - // cross-model billing scale (currentCalibrationFactor). + // what upstream actually billed; clamped 0.25–4, two-way since #2366 — see + // settleUsageReport). Unknown/mismatched origin → raw estimate, i.e. the + // uncalibrated legacy behavior. #2117 B: the model dimension gates too — a + // factor learned on another model acts as absent here rather than deciding + // with a cross-model billing scale (currentCalibrationFactor). const kFactor = currentCalibrationFactor(session.stats, session.metadata?.lastModel); const kOrigin = session.stats.calibratedEstimateOrigin; const calibratedText = applyEstimateCalibration(textEstimate + overheadEstimate, kFactor, kOrigin, currentOrigin); @@ -4451,8 +4451,9 @@ async function preflightCompressIfNeeded( // upstream's billing scale diverges from the estimator's caliber // (incident #2313: a local OpenAI-compatible shim billed ~200 B/token — // the trigger read 7.3M-10.3M against a real 305K input, ~24-34x over), - // calibration cannot correct it (k̂ is one-way, clamped 0.25-1, and - // consistent samples below CALIBRATION_SAMPLE_MIN are discarded), so + // calibration cannot correct it (k̂ is two-way since #2366 but clamped + // 0.25-4, and a 24-34x shim sits far outside the clamp; consistent + // samples below CALIBRATION_SAMPLE_MIN are discarded), so // estimate-driven folding demands unreachable targets, cannot finish // inside client stream patience (~300s idle abort), and never lets a // forward through — 0 successful forwards in 12h while every failed diff --git a/src/session.ts b/src/session.ts index f081c2f5c8..f32495f4f5 100644 --- a/src/session.ts +++ b/src/session.ts @@ -197,10 +197,11 @@ export type Session = { lastInputTokensOrigin?: string; /** #1933 F1: calibrated scale factor k̂ = mean of up to 3 recent * consistent same-route samples of (upstream-billed input ÷ local - * text estimate), clamped to [0.25, 1] — one-way by design: the - * correction can only deflate the estimate (never fire earlier - * than the raw proxy); routes billing above the local estimate - * publish k̂=1 (legacy behavior, overflow arm covers them). A + * text estimate), clamped to [0.25, 4] — two-way since #2366: the + * correction can inflate OR deflate the estimate toward the route's + * real billing scale (the one-way max-1 design failed empirically on + * CJK-heavy routes where billing runs 2.4–4.0× above the local + * estimate, so under-estimating routes learned nothing). A * sample is only admitted * when it falls in the plausibility band [0.2, 5] — outside it the * report and the payload clearly don't correspond (placeholder diff --git a/tests/issue1933-preflight-calibration.test.ts b/tests/issue1933-preflight-calibration.test.ts index 6285bd52e9..79a904b8ae 100644 --- a/tests/issue1933-preflight-calibration.test.ts +++ b/tests/issue1933-preflight-calibration.test.ts @@ -104,9 +104,10 @@ test("settleUsageReport: cross-route starts a fresh ring and clears the old fact pair(s, 10000, "http://b", 21000); // 2.0/2.1 are consistent under-estimate evidence (billing ABOVE the local - // estimate), but calibration is one-way: the mean clamps to 1 = raw - // estimate, legacy behavior — it may never fire earlier than the proxy. - assert.equal(st.calibratedEstimate, 1, "under-estimate route clamps to k̂=1 (no inflation)"); + // estimate). #2366 made calibration two-way (clamp [0.25, 4]): the mean + // publishes as-is — under-estimating routes (CJK-heavy content) must learn + // their real billing scale instead of being clamped back to the raw proxy. + assert.ok(Math.abs((st.calibratedEstimate ?? 0) - 2.05) < 1e-9, `under-estimate route learns k̂≈2.05, got ${st.calibratedEstimate}`); assert.equal(st.calibratedEstimateOrigin, "http://b"); }); @@ -140,21 +141,21 @@ test("settleUsageReport: implausible pairs never enter the ring", () => { assert.equal(st.calibrationRing?.values.length, 3, "ring capped at CALIBRATION_SAMPLE_WINDOW"); }); -test("settleUsageReport: published factors clamp to [0.25, 1] — one-way, deflate only", () => { +test("settleUsageReport: published factors clamp to [0.25, 4] — bounded both ways (#2366)", () => { const hi = makeSession(); pair(hi, 10000, "http://e", 45000); pair(hi, 10000, "http://e", 50000); - assert.equal(hi.stats.calibratedEstimate, 1, "mean 4.75 clamps down to 1: an under-estimating route keeps legacy behavior, calibration never inflates a reading"); + assert.equal(hi.stats.calibratedEstimate, 4, "mean 4.75 clamps down to 4: inflation is real on under-estimating (CJK) routes but bounded — and below the sample band max 5, so non-corresponding reports are still rejected first"); const lo = makeSession(); pair(lo, 10000, "http://f", 2200); pair(lo, 10000, "http://f", 2400); assert.equal(lo.stats.calibratedEstimate, 0.25, "mean 0.23 clamps up to 0.25"); - // The corrected reading can only drop BELOW the raw estimate, never rise: - // applying the clamped hi factor is a no-op (raw × 1), applying the lo - // one deflates — both bounded by the clamp range. - assert.equal(applyEstimateCalibration(10000, hi.stats.calibratedEstimate, "http://e", "http://e"), 10000); + // The corrected reading can now move either way, always inside the clamp + // band: applying the hi factor inflates to the bound (raw × 4), applying + // the lo one deflates (raw × 0.25). + assert.equal(applyEstimateCalibration(10000, hi.stats.calibratedEstimate, "http://e", "http://e"), 40000); assert.equal(applyEstimateCalibration(10000, lo.stats.calibratedEstimate, "http://f", "http://f"), 2500); }); diff --git a/tests/issue2129-restart-measurement-state.test.ts b/tests/issue2129-restart-measurement-state.test.ts index 24505ba98f..b065aa1117 100644 --- a/tests/issue2129-restart-measurement-state.test.ts +++ b/tests/issue2129-restart-measurement-state.test.ts @@ -138,9 +138,10 @@ test("corrupt persisted measurement values are rejected at restore (#2129)", asy } }; - // Out-of-band values: a k̂ above the clamp band would INFLATE estimates - // (applyEstimateCalibration applies unclamped — one-way deflate contract), - // negative anchors/estimates are nonsense, empty origins match no route. + // Out-of-band values: a k̂ above the two-way clamp band [0.25, 4] (#2366) + // would move every calibrated reading off-scale (applyEstimateCalibration + // applies the stored factor unclamped), negative anchors/estimates are + // nonsense, empty origins match no route. // JSON encodes NaN/Infinity as null — the restore guards reject both. const bad = await loadMutated((st) => { st.calibratedEstimate = 5; diff --git a/tests/issue2366-cjk-billed-status.test.ts b/tests/issue2366-cjk-billed-status.test.ts new file mode 100644 index 0000000000..214f8df979 --- /dev/null +++ b/tests/issue2366-cjk-billed-status.test.ts @@ -0,0 +1,200 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig, createCore, createInitialState, assignRefs, emptyRefMap } from "acp-kernel"; +import type { CoreMessage } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { handleAcpStatus } from "../src/acp-status.ts"; +import { settleUsageReport } from "../src/cache-ledger.ts"; +import { applyEstimateCalibration } from "../src/util.ts"; + +// #2366: on CJK-heavy routes upstream billing runs 2.4–4.0× above the local +// chars/4 estimate, so every agent-visible surface (acp_status breakdown, +// nudge reason) understated real context pressure until the window was nearly +// full and little compressible mass remained — the "small-benefit fold loop". +// Two host-side fixes are pinned here: +// A) calibration is now two-way (clamp [0.25, 4]) so under-estimating routes +// learn k̂>1 instead of clamping back to the raw proxy; +// B) acp_status shows the usage-grade BILLED INPUT next to the estimate view +// (+ divergence NOTE at ratio ≥1.5, + PRESSURE NOTE when billed pressure +// is high but compressible mass is exhausted). + +let seq = 0; +function makeSession(): Session { + seq += 1; + return { + id: `i2366-${seq}`, + metadata: {}, + stats: {}, + state: { blocks: [], messageRefs: { byRaw: {}, byRef: {} }, tokenSnapshot: {} }, + } as unknown as Session; +} + +// One settled pair (pending estimate + its usage report) on a route. +function pair(s: Session, est: number, origin: string, billed: number): void { + s.stats.lastLocalTextEstimate = est; + s.stats.lastLocalTextEstimateOrigin = origin; + settleUsageReport(s, { total: billed, reportedCached: null, upstream: origin }); +} + +test("#2366 A: an under-estimating (CJK-like) route learns k̂>1 — two-way calibration", () => { + const s = makeSession(); + pair(s, 10000, "http://llama", 24000); // ratio 2.4 + assert.equal(s.stats.calibratedEstimate, undefined, "one sample must not publish"); + pair(s, 10000, "http://llama", 31000); // ratio 3.1 + assert.ok(Math.abs((s.stats.calibratedEstimate ?? 0) - 2.75) < 1e-9, `consistent under-estimate evidence publishes mean 2.75 unclamped, got ${s.stats.calibratedEstimate}`); + assert.equal(s.stats.calibratedEstimateOrigin, "http://llama"); +}); + +test("#2366 A: inflation is bounded at CLAMP_MAX 4, below the sample band max 5", () => { + const s = makeSession(); + pair(s, 10000, "http://llama", 46000); + pair(s, 10000, "http://llama", 48000); + assert.equal(s.stats.calibratedEstimate, 4, "mean 4.7 clamps to 4"); + + // A non-corresponding report (>5×) never enters the ring and cannot + // disturb a published factor. + pair(s, 10000, "http://llama", 60000); + assert.equal(s.stats.calibratedEstimate, 4, "out-of-band sample leaves the factor intact"); + assert.deepEqual(s.stats.calibrationRing?.values, [4.6, 4.8], "ring untouched by the rejected sample"); +}); + +test("#2366 A: applyEstimateCalibration moves both directions on the learned route only", () => { + assert.equal(applyEstimateCalibration(10000, 2.75, "http://llama", "http://llama/v1/chat/completions"), 27500, "same route inflates"); + assert.equal(applyEstimateCalibration(10000, 0.5, "http://relay", "http://relay"), 5000, "deflate direction unchanged"); + assert.equal(applyEstimateCalibration(10000, 2.75, "http://other", "http://llama"), 10000, "cross-route stays raw"); +}); + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +interface CtxOverrides { + lastInputTokens?: number; + source?: string; + contextTokensAt?: number; + systemPromptTokens?: number; +} + +function makeCtx(messages: CoreMessage[], o?: CtxOverrides): { + core: ReturnType; + config: ReturnType; + messages: CoreMessage[]; + session: Session; +} { + return { + core: createCore(), + config: defaultConfig(200000), + messages, + session: { + id: "i2366-ctx", + meta: {}, + stats: { + requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, + lastInputTokens: o?.lastInputTokens ?? 0, + ...(o?.source !== undefined ? { lastInputTokensSource: o.source as never } : {}), + compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, + storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0, + }, + metadata: { + ...(o?.contextTokensAt !== undefined ? { contextTokensAt: o.contextTokensAt } : {}), + ...(o?.systemPromptTokens !== undefined ? { systemPromptTokens: o.systemPromptTokens } : {}), + }, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + } as unknown as Session, + }; +} + +function asciiMsgs(count: number, charsPerMsg: number): CoreMessage[] { + const msgs: CoreMessage[] = []; + for (let i = 1; i <= count; i++) msgs.push(textMsg(`raw_${i}`, i % 2 === 1 ? "user" : "assistant", "x".repeat(charsPerMsg))); + return msgs; +} + +function withRefs(ctx: ReturnType): ReturnType { + ctx.session.state.messageRefs = assignRefs(ctx.messages, { existing: emptyRefMap(), nextIndex: 0 }).map; + return ctx; +} + +// 12 × 4000 ASCII chars → est-view total exactly 12000 tok (chars/4). +const MSGS = () => asciiMsgs(12, 4000); + +test("#2366 B: acp_status shows the billed input next to the estimate view, with a divergence note at ratio ≥ 1.5", () => { + const ctx = withRefs(makeCtx(MSGS(), { lastInputTokens: 30000, source: "usage", contextTokensAt: Date.now() })); + const out = handleAcpStatus({}, ctx).text; + assert.ok(out.includes("BILLED INPUT (upstream usage): 30000 tok"), `billed line present (got: ${out.slice(0, 400)})`); + assert.ok(out.includes("est-view total 12000 tok · ratio 2.5×"), "estimate-view total + ratio rendered"); + assert.ok(out.includes("Judge context pressure from BILLED INPUT"), "divergence note present at ratio 2.5×"); + assert.ok(!out.includes("measured "), "fresh measurement carries no age suffix"); +}); + +test("#2366 B: system-heavy sessions don't read as divergence — est view carries the system+tools overhead", () => { + // 12,000 tok of message text + 20,000 tok system/tools vs billed 36,000: + // message-only caliber would show 3.0× and blame the tokenizer; the + // like-for-like caliber (32,000 incl. overhead) shows 1.1× → no note. + const ctx = withRefs(makeCtx(MSGS(), { lastInputTokens: 36000, source: "usage", contextTokensAt: Date.now(), systemPromptTokens: 20000 })); + const out = handleAcpStatus({}, ctx).text; + assert.ok(out.includes("est-view total 32000 tok · ratio 1.1×"), `overhead folded into the est view (got: ${out.slice(0, 400)})`); + assert.ok(!out.includes("Judge context pressure from BILLED INPUT"), "same-caliber ratio 1.1× < 1.5 → no divergence note"); +}); + +test("#2366 B: stale measurement carries an age suffix; no note below ratio 1.5", () => { + const stale = withRefs(makeCtx(MSGS(), { lastInputTokens: 15000, source: "usage", contextTokensAt: Date.now() - 30 * 60_000 })); + const out = handleAcpStatus({}, stale).text; + assert.ok(out.includes("BILLED INPUT (upstream usage): 15000 tok, measured 30m ago"), "age rendered for a 30m-old measurement"); + assert.ok(!out.includes("Judge context pressure from BILLED INPUT"), "ratio 1.25× < 1.5 → no divergence note"); +}); + +test("#2366 B: estimate-grade anchors must not masquerade as billed input (#2029 class)", () => { + // legacy session: a positive lastInputTokens WITHOUT a usage-grade source + // is an estimate-grade value — statusInputBaseline returns 0, no line. + const legacy = withRefs(makeCtx(MSGS(), { lastInputTokens: 150000 })); + const out = handleAcpStatus({}, legacy).text; + assert.ok(!out.includes("BILLED INPUT"), "no usage-grade anchor → no BILLED line"); + + const fresh = withRefs(makeCtx(MSGS())); + assert.ok(!handleAcpStatus({}, fresh).text.includes("BILLED INPUT"), "never-reporting upstream → no BILLED line"); +}); + +test("#2366 B: overflow-arm readings are labelled as bounded, scope mode stays base-only", () => { + const arm = withRefs(makeCtx(MSGS(), { lastInputTokens: 90000, source: "overflow-arm" })); + assert.ok(handleAcpStatus({}, arm).text.includes("BILLED INPUT (overflow arm (bounded)): 90000 tok"), "bounded reading labelled distinctly"); + + const scoped = withRefs(makeCtx(MSGS(), { lastInputTokens: 30000, source: "usage" })); + const out = handleAcpStatus({ scope: "uncompressed" }, scoped).text; + assert.ok(!out.includes("BILLED INPUT"), "scope= short-circuit returns the base report only"); +}); + +test("#2366 B: PRESSURE NOTE fires at high billed pressure with exhausted compressible mass", () => { + // 130000/200000 = 65% ≥ 0.6; the 12k-tok message list leaves far less than + // the nudge growth threshold of compressible mass — the exact #2366 state + // ("max compressible 13355 < threshold 50000" while usage climbed past 66%). + const ctx = withRefs(makeCtx(MSGS(), { lastInputTokens: 130000, source: "usage", contextTokensAt: Date.now() })); + const out = handleAcpStatus({}, ctx).text; + assert.ok(out.includes("Nudge: idle"), `nudge idle in this state (got: ${out.slice(0, 400)})`); + assert.ok(out.includes("PRESSURE NOTE"), "pressure note present"); + assert.ok(out.includes("% of the 200000-token limit"), "note names the limit"); + assert.ok(out.includes("continue the task instead of folding again"), "note advises against repeated small folds"); +}); + +test("#2366 B: PRESSURE NOTE stays silent at low billed pressure", () => { + const ctx = withRefs(makeCtx(MSGS(), { lastInputTokens: 30000, source: "usage", contextTokensAt: Date.now() })); + const out = handleAcpStatus({}, ctx).text; + assert.ok(out.includes("Nudge: idle")); + assert.ok(!out.includes("PRESSURE NOTE"), "15% usage → no pressure note"); +}); + +test("#2366 B: plain sessions keep today's output exactly (additive-only change)", () => { + const ctx = withRefs(makeCtx(MSGS())); + const out = handleAcpStatus({}, ctx).text; + assert.ok(out.includes("Nudge:"), "nudge line still present"); + assert.ok(!out.includes("BILLED INPUT") && !out.includes("PRESSURE NOTE"), "no new sections without a usage-grade anchor"); +});