diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e73ff7075..90b52caa37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag - dsh 归因丢失协商回退(#4082/#3918/#2975):宿主重试/切模型/睡眠恢复的请求脱离 agent 执行链,归因为空时此前直接裸发上游(无压缩无护栏,且会话永久失守)。现在 shim 在归因正常时学习「车道 → 会话 + 边界指纹」(该次请求最后一条消息),归因丢失时若请求历史包含某已知边界且唯一命中,则由 takeover 门认领并原子补盖 x-bili-plugin-conversation(#3370 纪律),请求照常走插件车道;fork 从中间分叉不含边界 → 不认,行为与今天逐字节一致;无证据/多义 → 维持直发。每个 2xx 响应新增 x-bili-session 头(协议级,配合客户端可自持身份,见 PLUGIN.md);认领事件进 client 日志可见。 ### 压缩 +- **过小的陈旧 usage 样本不再冻结计量(#4383)**:同一会话 id 下的小而真实的 usage-grade 样本(标题生成/探测等侧车请求)被 settleUsageReport 无条件写进 lastUsageGradeTokens,所有输入基线读者(statusInputBaseline / effectiveTokenCount)原样信任——kernel 的 growth reference 是低水位标记(#1595)会跟到该值,growth ≡0、压力带失效,自动折叠整段停摆(复现:一次 4733-token 样本把 303k 上下文冻在 usage=1% 达 4h07m,154 次 nudge 全部 idle、零折叠;换模型前重启也不愈合)。现在两个共享读者都走同一个 stale-small 守卫:锚点低于当前出站 billing-caliber 本地估算(contextEstimateTokens)的 25%、且已被其后的一次主发送超越(contextTokensSource="estimate"——主发送逐次盖章、settle 翻回 "usage")时,降级为该估算值——即 #1595 书面承诺的"改用本地估算"兜底。新鲜度闸门区分"陈旧侧车样本"与"新鲜小样本"(后者保持权威,#1820 B 不变量有测试钉死);高于估算的锚点保持 #1839 优先(单向);无估算/无新鲜度戳的旧会话行为逐字节不变。preflight 本就自校正(max(baselineFloor, calibratedPayload)),不受影响;kernel 未动,无新增配置。 - **压缩区间跨越受保护消息时在边界截断,不再挖洞(#3953)**:此前模型选的区间如果中途扫过受保护消息(最近 N 条/最近一条用户消息),受保护消息会被从覆盖名单里挖掉、两侧照折——其回复(在受保护提问之后的消息)被摘要盖住,而摘要锚点落在提问之前,模型看到"答案摘要排在自己的问题上方"。现在区间在首个受保护消息处截断:从该位置起(受保护消息与其后的回复)全部保持可见,因果序不再被打穿。受保护消息恰在区间尾部的常规擦边(咨询式保护区原本设计的形状)行为逐字节不变;截断会清空区间或会劈开工具调用/结果对的形状退回原挖洞语义(吸收保护的吸收对不受影响)。 - **compress-from-store:被逐出的会话对着统一存储的原始视图折叠,不再永久拒收(#3982,根治 #3918 Phase 4)**:超过常驻池预算(默认 512 MiB)的大会话每次模型请求后都被逐出,活内存视图永不存活,`compress` 工具因此永久 REFUSED——而统一存储(#3911)本就每次保存把完整原始客户端视图镜像进 messages 表。现在 applyRanges 与外部摘要链在"有效视图为空"时先从统一正史恢复视图(只读、只窥探——绝不隐式建库;任一行不可解析维持诚实拒收),折叠落在持久化 state 上,与"下一轮模型请求后重试"路径完全同构。活视图在场时存储从不被咨询(零行为变化);无存储/legacy 模式拒收回执逐字节不变。 diff --git a/src/server.ts b/src/server.ts index 2699a7f7a0..9f0275ff50 100644 --- a/src/server.ts +++ b/src/server.ts @@ -56,7 +56,7 @@ import { FORCE_TEXT_PROTOCOL } from "./server/inject.js"; export { isChatGptCodexUpstream, isCodexResponsesLite, resolvePromptCacheKey, shouldInjectPromptCacheKey } from "./server/prepare-responses.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "./fold-reconcile.js"; import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js"; -import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js"; +import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, staleSmallAnchorFallback, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js"; import { detectStaleInstall } from "./update.js"; import { decideEaddrinuse, eaddrinuseExitCode, postBindCanLadder, UPGRADE_REPLACEMENT_ENV, type FailFastReason } from "./listen-policy.js"; import { getAdvisoryState, cannotResolveTarget } from "./advisory.js"; @@ -2329,7 +2329,11 @@ export function effectiveTokenCount(session: Session, msgs: CoreMessage[], inbou // #1839: an overflow arm rides in here too — it is evidence, not billing, // but it is bounded by the declared/stated window so it cannot produce // the >100% ghost class, and the next real usage report overwrites it. - if (session.stats.lastInputTokens > 0 && (session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm")) return { tokens: session.stats.lastInputTokens, source: "usage" }; + // #4383: a stale-small trusted anchor (a sidecar/side-request sample under + // the same session id, superseded by later main sends) must not freeze the + // meter — fall through instead: the post-rebuild anchor below (if any) is + // the fresher measurement, otherwise the calibrated-estimate branches win. + if (session.stats.lastInputTokens > 0 && (session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm") && staleSmallAnchorFallback(session.stats, session.stats.lastInputTokens) === null) return { tokens: session.stats.lastInputTokens, source: "usage" }; // #1820: right after a preflight rebuild the usage-grade baseline above is // momentarily absent (the rebuild request's own report hasn't landed yet, // or the upstream never reports), and every branch below sizes on the @@ -2362,7 +2366,14 @@ export function effectiveTokenCount(session: Session, msgs: CoreMessage[], inbou // upstreams (#553/#728) are unaffected: their anchor stays absent, so the // fail-closed upper bounds below still apply. const grade = session.stats.lastUsageGradeTokens; - if (grade !== undefined && grade > 0) return { tokens: grade, source: "usage" }; + if (grade !== undefined && grade > 0) { + // #4383: stale-small retained anchor — the calibrated local estimate + // of the current outbound is strictly better than the char-count + // branches below (#1839 inflation), so it wins immediately. + const fallback = staleSmallAnchorFallback(session.stats, grade); + if (fallback !== null) return { tokens: fallback, source: "estimate" }; + return { tokens: grade, source: "usage" }; + } // #553: zero-baseline ANCHOR-LESS anonymous sessions (prefix-affinity // mints/forks/reloads) fall back to the raw-history upper bound — see the // function header for why feeding 0 blinds them. diff --git a/src/session.ts b/src/session.ts index 8a0b5d1e89..96fea8acee 100644 --- a/src/session.ts +++ b/src/session.ts @@ -689,6 +689,43 @@ export function effectiveConfig(session: Session | undefined, fallback: Config): return classifier && !base.messagePathOf ? withDurableProtection(base, classifier) : base; } +// #4383: a positive usage-grade anchor below this share of the billing-caliber +// estimate of the last main send (contextEstimateTokens) cannot describe the +// payload this conversation actually carries — it measured a different, +// smaller request under the same session id (title-gen/probe sidecar) or +// predates a growth burst. 0.25 sits just inside the estimator's own error +// band (uncalibrated chars/4 over-counts ASCII up to ~3.5× ⇒ a legitimate +// same-payload sample lands ≈0.29× the estimate and survives; sidecar samples +// are typically <10% and get caught), matching the k̂ clamp floor (0.25–4). +const STALE_ANCHOR_RATIO = 0.25; + +/** #4383: stale-small usage-anchor guard shared by every input-baseline reader + * (statusInputBaseline, effectiveTokenCount). Returns the replacement reading + * — the calibrated local estimate itself (#1595's promised "ride local + * estimates until a usage-grade sample lands" fallback) — when BOTH hold: + * - `anchor` is below STALE_ANCHOR_RATIO × `stats.contextEstimateTokens` + * (magnitude-inconsistent with what this conversation actually sends); + * - `contextTokensSource === "estimate"`, i.e. a MAIN SEND has occurred + * since the last settled usage report (the relay chokepoint stamps it per + * send, settleUsageReport flips it back to "usage"). That freshness gate + * is what separates a STALE sidecar sample (superseded by later larger + * main sends) from a FRESH small one (the current send's own report, + * which keeps its #1820 authority over the post-rebuild anchor). + * One-directional by design: anchors ABOVE the estimate keep their #1839 + * precedence (fail-closed direction); only too-small poison is demoted. + * Absent/non-positive estimate (legacy sessions, no main send yet) → null, + * byte-identical legacy behavior. */ +export function staleSmallAnchorFallback( + stats: Pick, + anchor: number, +): number | null { + const est = stats.contextEstimateTokens; + return stats.contextTokensSource === "estimate" + && anchor > 0 && typeof est === "number" && Number.isFinite(est) && est > 0 && anchor < STALE_ANCHOR_RATIO * est + ? est + : null; +} + /** #2029: provenance-aware baseline for STATUS readers — acp_status nudge * recompute, plugin live nudge + panel, post-compress tail. Shared by every * status surface so none of them can present an estimate-grade reading as a @@ -710,12 +747,17 @@ export function effectiveConfig(session: Session | undefined, fallback: Config): * sentinel. Never clamps: a REAL over-window usage report must still read * >100%. The JSON observation contract (contextTokens/contextTokensSource, * #2017) is deliberately separate — it expresses unknown explicitly rather - * than as 0. */ + * than as 0. On top of all of that, the stale-small guard applies (#4383): an + * anchor below 25% of the billing-caliber local estimate of the current + * outbound AND superseded by a later main send is demoted to that estimate — + * it measured a different request under the same session id and must not + * blind the growth gate (see staleSmallAnchorFallback for the contract). */ export function statusInputBaseline(session: Session): number { const stats = session.stats; - return stats.lastInputTokensSource === "usage" || stats.lastInputTokensSource === "overflow-arm" + const baseline = stats.lastInputTokensSource === "usage" || stats.lastInputTokensSource === "overflow-arm" ? stats.lastInputTokens : stats.lastUsageGradeTokens ?? 0; + return staleSmallAnchorFallback(stats, baseline) ?? baseline; } /** #2117: the honest best reading of "how full is this context right now" for diff --git a/tests/issue4383-stale-anchor-fallback.test.ts b/tests/issue4383-stale-anchor-fallback.test.ts new file mode 100644 index 0000000000..61a6e73083 --- /dev/null +++ b/tests/issue4383-stale-anchor-fallback.test.ts @@ -0,0 +1,195 @@ +// #4383: a tiny but REAL usage-grade sample under the session id (title-gen / +// probe sidecar request) settles into lastUsageGradeTokens and blinds every +// input-baseline reader: the kernel's growth reference is a low-water mark +// (#1595) and rides down to the tiny reading, so growth stays ≡0, the pressure +// bands die, and auto-folding is disabled for hours until an unrelated external +// event lands a real report (repro: one 4733-token sample froze a 303k context +// at usage=1% for 4h07m — 154 nudges all idle, pendingT1 106k→284k, zero folds; +// recovery only when a model switch produced input=252154). #1595's written +// promise "nudge decisions ride local estimates until a usage-grade sample +// lands" was never implemented in the baseline readers. Fix: shared stale-small +// guard — an anchor below 25% of the billing-caliber local estimate of the +// current outbound (contextEstimateTokens) AND superseded by a later main send +// (contextTokensSource === "estimate": the relay chokepoint stamps it per send, +// settleUsageReport flips it back to "usage") is demoted to that estimate. The +// freshness gate is what keeps a FRESH small sample authoritative (#1820 B: a +// real usage-grade sample supersedes the post-rebuild anchor immediately); only +// a small sample OUTLIVED by larger main sends is sidecar poison. Anchors above +// the estimate keep their #1839 precedence (one-directional). These tests pin +// the guard matrix on both readers plus the end-to-end freeze-breaker (the +// exact repro shape through handleAcpStatus) and its negative control (same +// poison, no estimate → legacy behavior byte-identical). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { CoreMessage } from "acp-kernel"; +import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; +import { zeroStats, statusInputBaseline, displayContextBest, staleSmallAnchorFallback, type Session } from "../src/session.ts"; +import { effectiveTokenCount } from "../src/server.ts"; +import { handleAcpStatus } from "../src/acp-status.ts"; + +const EST = 303093; // the issue's calibrated estimate (output-budget line input~303093) +const POISON = 4733; // the issue's sidecar sample + +type Scenario = { name: string; stats: Partial; expected: number }; + +// Freshness shorthand: "estimate" = a main send has occurred since the last +// settled sample (guard may fire); "usage" = the sample IS the latest event +// (guard must stay off — #1820 B authority). +const FRESH = { contextTokensSource: "estimate" as const }; +const SETTLED = { contextTokensSource: "usage" as const }; + +const SCENARIOS: Scenario[] = [ + { name: "issue repro: 4.7k sidecar sample under a 303k context falls back to the calibrated estimate", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, expected: EST }, + { name: "legacy unflagged path: same poison via the retained anchor", stats: { lastInputTokens: POISON, lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, expected: EST }, + { name: "estimate-grade failure arm swallowed, live estimate wins (armFailureShrink egress)", stats: { lastInputTokens: 1108494, lastInputTokensSource: "estimate", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, expected: EST }, + { name: "stale-small overflow-arm demoted too", stats: { lastInputTokens: POISON, lastInputTokensSource: "overflow-arm", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, expected: EST }, + { name: "fresh small sample keeps authority even far below the estimate (#1820 B)", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...SETTLED }, expected: POISON }, + { name: "legitimate sample inside the estimator error band stays trusted", stats: { lastInputTokens: Math.round(EST / 3), lastInputTokensSource: "usage", lastUsageGradeTokens: Math.round(EST / 3), contextEstimateTokens: EST, ...FRESH }, expected: Math.round(EST / 3) }, + { name: "anchor above the estimate keeps #1839 precedence (one-directional)", stats: { lastInputTokens: 400000, lastInputTokensSource: "usage", lastUsageGradeTokens: 400000, contextEstimateTokens: EST, ...FRESH }, expected: 400000 }, + { name: "real over-window report never clamped even against a low estimate", stats: { lastInputTokens: 800000, lastInputTokensSource: "usage", lastUsageGradeTokens: 800000, contextEstimateTokens: EST, ...FRESH }, expected: 800000 }, + { name: "no estimate yet (legacy session) → anchor verbatim", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON }, expected: POISON }, + { name: "zero estimate → anchor verbatim", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: 0, ...FRESH }, expected: POISON }, + { name: "unknown sentinel (no anchor) untouched", stats: {}, expected: 0 }, +]; + +test("#4383: staleSmallAnchorFallback demotes only too-small anchors superseded by a main send", () => { + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...FRESH }, POISON), EST); + // exact-integer boundary (est divisible by 4): at the line → trusted (strict <); one below → demoted + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: 400000, ...FRESH }, 100000), null, "anchor exactly at 25% is trusted (strict <)"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: 400000, ...FRESH }, 99999), 400000, "one token below the line is demoted"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...FRESH }, Math.round(EST / 3)), null, "estimator-error-band sample survives"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...FRESH }, EST * 10), null, "stale-high keeps precedence"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...FRESH }, 0), null, "unknown sentinel passes"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...FRESH }, -5), null); + assert.equal(staleSmallAnchorFallback({}, POISON), null, "absent estimate → legacy behavior"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: 0, ...FRESH }, POISON), null); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: Number.NaN, ...FRESH }, POISON), null); + // freshness gate: magnitude alone never demotes a FRESH sample (#1820 B) + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST, ...SETTLED }, POISON), null, "settled-latest small sample stays authoritative"); + assert.equal(staleSmallAnchorFallback({ contextEstimateTokens: EST }, POISON), null, "no freshness stamp (legacy session) → legacy behavior"); +}); + +test("#4383: statusInputBaseline demotes stale-small anchors across the provenance matrix", () => { + for (const sc of SCENARIOS) { + const session = { stats: { ...zeroStats(), ...sc.stats } } as Session; + assert.equal(statusInputBaseline(session), sc.expected, sc.name); + } +}); + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function makeMessages(n: number): CoreMessage[] { + const msgs: CoreMessage[] = []; + for (let i = 1; i <= n; i++) { + msgs.push(textMsg(`raw_${i}`, i % 2 === 1 ? "user" : "assistant", "x".repeat(5000))); + } + return msgs; +} + +function makeSession(stats: Partial): Session { + return { stats: { ...zeroStats(), ...stats } } as Session; +} + +test("#4383: effectiveTokenCount demotes stale-small anchors on both anchor branches", () => { + const msgs = makeMessages(12); + const cases: Array<{ name: string; stats: Partial; tokens: number; source: "usage" | "estimate" }> = [ + { name: "branch 1 (trusted source) stale-small → calibrated estimate", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, tokens: EST, source: "estimate" }, + { name: "branch 1 fresh small sample keeps authority (#1820 B)", stats: { lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...SETTLED }, tokens: POISON, source: "usage" }, + { name: "branch 1 trusted in-band → unchanged", stats: { lastInputTokens: Math.round(EST / 3), lastInputTokensSource: "usage", lastUsageGradeTokens: Math.round(EST / 3), contextEstimateTokens: EST, ...FRESH }, tokens: Math.round(EST / 3), source: "usage" }, + { name: "branch 1 real over-window → verbatim", stats: { lastInputTokens: 800000, lastInputTokensSource: "usage", lastUsageGradeTokens: 800000, contextEstimateTokens: EST, ...FRESH }, tokens: 800000, source: "usage" }, + { name: "branch 3 (retained grade, non-trusted source) stale-small → calibrated estimate", stats: { lastInputTokens: 1108494, lastInputTokensSource: "estimate", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, ...FRESH }, tokens: EST, source: "estimate" }, + { name: "branch 3 trusted in-band → unchanged", stats: { lastInputTokens: 1108494, lastInputTokensSource: "estimate", lastUsageGradeTokens: Math.round(EST / 3), contextEstimateTokens: EST, ...FRESH }, tokens: Math.round(EST / 3), source: "usage" }, + { name: "poison without any estimate → legacy branch-3 value (byte-identical pre-fix)", stats: { lastInputTokens: 1108494, lastInputTokensSource: "estimate", lastUsageGradeTokens: POISON }, tokens: POISON, source: "usage" }, + ]; + for (const c of cases) { + assert.deepEqual(effectiveTokenCount(makeSession(c.stats), msgs), { tokens: c.tokens, source: c.source }, c.name); + } +}); + +// displayContextBest is deliberately UNCHANGED by #4383 — the field dynamics +// already keep it honest in the poison state: while main sends continue the +// relay chokepoint has flipped contextTokensSource to "estimate", so the panel +// serves the calibrated estimate (kind "estimate"); only between a settle and +// the next main send does it show the just-settled sample, which at that +// instant IS the newest measurement. These cases pin that existing behavior so +// a future reader-side change cannot silently re-introduce a stale usage-kind +// reading into the panel. +test("#4383: displayContextBest stays honest across the poison lifecycle (unchanged behavior)", () => { + const steadyPoison = { + stats: { contextTokens: 900000, contextTokensSource: "estimate" as const, lastUsageGradeTokens: POISON, lastInputTokensSource: "usage" as const, contextEstimateTokens: EST, contextEstimateCalibrated: true }, + metadata: {}, + }; + assert.deepEqual(displayContextBest(steadyPoison), { tokens: EST, kind: "estimate", calibrated: true }); + const freshSettle = { + stats: { contextTokens: POISON, contextTokensSource: "usage" as const, lastUsageGradeTokens: POISON, lastInputTokensSource: "usage" as const, contextEstimateTokens: EST }, + metadata: { contextTokensAt: 1761191519122 }, + }; + assert.deepEqual(displayContextBest(freshSettle), { tokens: POISON, kind: "usage", at: 1761191519122 }); + const legacy = { + stats: { contextTokens: POISON, contextTokensSource: "usage" as const, lastUsageGradeTokens: POISON, lastInputTokensSource: "usage" as const }, + metadata: {}, + }; + assert.deepEqual(displayContextBest(legacy), { tokens: POISON, kind: "usage" }); +}); + +// End-to-end freeze-breaker: the issue's exact shape — limit 750000, one 4733 +// usage-grade sample settled, kernel reference already ridden down to it +// (lastPerMessageNudgeTokens=4733), ~60×5000-char messages pending (~70k+ T1 +// mass). Pre-fix the meter fed 4733 (usage 1%, growth 0/22500, idle forever — +// the 4h07m zero-fold signature); post-fix it feeds the calibrated estimate +// and the growth gate opens immediately. +const LIMIT = 750000; + +function makeCtx(stats: Session["stats"], frozenRef: boolean): { seen: number[]; nudges: Array<{ shouldInject: boolean; reason: string; breakdown: Record }> } { + const messages = makeMessages(60); + const refs = assignRefs(messages, { existing: emptyRefMap(), nextIndex: 0 }); + const session: Session = { + id: "issue4383-e2e", + meta: {}, + stats, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + }; + session.state.messageRefs = refs.map; + if (frozenRef) session.state.nudge.lastPerMessageNudgeTokens = POISON; + const core = createCore(); + const seen: number[] = []; + const nudges: Array<{ shouldInject: boolean; reason: string; breakdown: Record }> = []; + const orig = core.processTurn.bind(core); + core.processTurn = (input: Parameters[0]) => { + seen.push(input.tokenCount); + const out = orig(input); + nudges.push({ shouldInject: out.nudge?.shouldInject ?? false, reason: out.nudge?.reason ?? "", breakdown: (out.nudge?.breakdown ?? {}) as Record }); + return out; + }; + handleAcpStatus({}, { core, config: defaultConfig(LIMIT), messages, session }); + return { seen, nudges }; +} + +test("#4383: the frozen meter opens on the calibrated estimate (issue repro)", () => { + // contextTokensSource "estimate": main sends have continued since the + // sidecar sample settled — the issue's steady-state freeze window. + const stats: Session["stats"] = { ...zeroStats(), lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON, contextEstimateTokens: EST, contextTokensSource: "estimate" }; + const { seen, nudges } = makeCtx(stats, true); + assert.deepEqual(seen, [EST], "tokenCount handed to the kernel is the calibrated estimate, not the poison"); + assert.ok(nudges.length === 1 && nudges[0].shouldInject, `nudge must INJECT after the fix (got: ${nudges[0]?.reason})`); + assert.equal(nudges[0].breakdown.growthReference, POISON, "growth reference still rides the low-water mark"); + assert.ok(nudges[0].breakdown.growth! >= 22500, `growth crosses the floor (${nudges[0].breakdown.growth})`); + assert.match(nudges[0].reason, /T1 effective \d+ >= 50000/); +}); + +test("#4383: negative control — same poison without an estimate keeps legacy behavior", () => { + const stats: Session["stats"] = { ...zeroStats(), lastInputTokens: POISON, lastInputTokensSource: "usage", lastUsageGradeTokens: POISON }; + const { seen, nudges } = makeCtx(stats, true); + assert.deepEqual(seen, [POISON], "without contextEstimateTokens the reader is byte-identical pre-fix"); + assert.equal(nudges[0].shouldInject, false, "the frozen meter stays frozen (documented legacy behavior)"); + assert.match(nudges[0].reason, /growth 0 < floor 22500/); +});