From b554d4db96fb6120bd32a2b7dd2141da6dcb477f Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 9 Oct 2026 01:14:43 +0800 Subject: [PATCH 1/2] fix: drain first-sight mass in one batched compress call (#2326) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hosts that hand bili a pre-inflated history (dsh plugin mode, CLI hand-off, resumed rollout) make the first requests see a large ready mass with zero growth baseline; the kernel marks those nudges ' [first-sight mass]' and re-arms after every successful fold, and the model folded the backlog one small call per request. Each front-positioned fold rewrites the request prefix, so every piecemeal landing re-pays the ENTIRE remaining tail to the prefix cache (2.29x/tok re-pay for a 5-fold cascade vs 0.032x/tok for one big fold, ~70x — issue log eb985b31 vs 5c5c26d1). A one-call batch was also physically unexecutable without external summaries: the model's per-response output budget cannot hold N 20K-char summaries. withFirstSightDrain(text, reason, external) keys on the kernel marker at all 12 nudge injection points (4 adapters x advisory + decide directive): during digestion it appends a byte-stable batched-drain note and suppresses the smooth-transition staged note (whose smaller/tail-biased steering is exactly wrong for a backlog that must be drained); the decide-directive variant carries an explicit precedence sentence over the stock single-span wording. No marker -> byte-identical to the legacy staged path; no new config surface. The external variant tells the model the summary service writes the summaries so its own response budget is not a limit — combined with compress.externalSummary the batched instruction becomes executable for arbitrarily large backlogs (targets may even point at the same endpoint+key: the win comes from the channel, not the author). Tests: tests/first-sight-drain.test.ts (marker keying, byte-identity outside digestion, staged suppression inside it, external variant, byte-stability). Verified: typecheck, full unit suite (4841 pass / 42 fail, failure set byte-identical to clean master in this sandbox — pre-existing env flakes), build, and ACP_TEST_E2E=1 codex lane (real client, live compression) against local sglang. --- CHANGELOG.md | 2 + src/compress-tool.ts | 41 ++++++++++++++++++++ src/server.ts | 2 +- src/server/prepare-anthropic.ts | 8 ++-- src/server/prepare-google.ts | 8 ++-- src/server/prepare-openai.ts | 8 ++-- src/server/prepare-responses.ts | 8 ++-- tests/first-sight-drain.test.ts | 67 +++++++++++++++++++++++++++++++++ 8 files changed, 127 insertions(+), 17 deletions(-) create mode 100644 tests/first-sight-drain.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bda0ae067..238a945466 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] +- **First-sight mass digestion now drains in one batched call (#2326)**: hosts that hand bili a pre-inflated history (dsh plugin mode after its own digestion, CLI hand-off, resumed rollout) make the first requests see a large ready mass with zero growth baseline; the kernel marks those nudges ` [first-sight mass]` and re-arms after every successful fold, and the model folded the backlog one small call per request — each front-positioned fold rewrites the request prefix, so every piecemeal landing re-pays the ENTIRE remaining tail to the prefix cache (measured 2.29×/tok re-pay for a 5-fold cascade vs 0.032×/tok for one big fold, ~70×; issue log eb985b31 vs 5c5c26d1). Root constraint: a one-call batch is physically unexecutable when the model must write N summaries in one response — the per-response output budget caps how many 20K-char summaries fit, so the existing batching hints (SUMMARY_BUDGET_NOTE, ONE_CALL_HINT) degrade to piecemeal folds on big masses. `withFirstSightDrain(text, reason, external)` now keys on the kernel marker at all 12 nudge injection points (4 adapters × advisory/decide-directive): during digestion it appends a byte-stable "First-sight digestion" note (drain the WHOLE backlog in ONE batched compress call; split oversized spans into multiple ranges at logical boundaries but submit them all together in the same call; keep draining while the nudge repeats — it stops when the backlog is gone) and SUPPRESSES the smooth-transition staged note, whose smaller/tail-biased steering is exactly wrong for a backlog that must be drained; the decide-directive path carries an explicit precedence sentence over the stock "exactly this span" wording. No marker → byte-identical to the legacy staged path (steady-state guidance unchanged); no new config surface. The external variant of the note additionally tells the model that with `compress.externalSummary` enabled the independent summary service writes the summaries, so its own response-length budget is not a limit — combining the note with external summaries (targets may even point back at the same endpoint+key: the win comes from the channel — disjoint side requests, one landing — not the author) makes the batched instruction executable for arbitrarily large backlogs. Tests: `tests/first-sight-drain.test.ts` (marker keying, byte-identity outside digestion, staged suppression inside it, external variant, byte-stability). + - **Proxy spawn under GUI/Electron hosts finds Node without a full PATH (#1429)**: `resolveNodeRuntime()` (#819) resolved the executable that runs the spawned proxy as live Node → `BILLION_CONTEXT_NODE` override → PATH search → throw. GUI-launched hosts have a minimal PATH (launchd on macOS, the Windows GUI session) that omits normal install locations, so native plugins bootstrapped inside such hosts (e.g. deepseek-harness desktop's Electron process) threw before spawning and every session silently degraded to direct send (no compression), traceable only in bili.log (#1158 shape). Resolution now continues into well-known install locations the minimal PATH omits (`/usr/local/bin`, `/opt/homebrew/bin`, `/opt/local/bin`, Volta, `~/.local/bin`; on Windows `C:/Program Files/nodejs`, `%LOCALAPPDATA%/Programs/nodejs`, Volta), and as a last resort under an Electron host returns the host's own binary — which runs as plain Node when `ELECTRON_RUN_AS_NODE=1` is honored (the runAsNode fuse is on by default in standard builds); `ensureProxyRunning` forces that variable into the child env so the child runs Node instead of relaunching the desktop app. A real node always wins over the Electron-binary-as-node fallback; non-Electron behavior is unchanged (the env spread adds nothing outside Electron, the throw path is untouched). Entry backfilled here — PR #1436 shipped without a changelog line (#1576). - **PR builds publish under one rolling `pr` tag with globally monotonic versions — per-PR dist-tag growth stops (#1385)**: the registry's `pr-N` dist-tags grew unboundedly (~595 live, +~40/day) because every PR push created/refreshed its own tag. `pr-artifact.yml` now publishes each build as `0.0.-pr..[-a]` under the SINGLE rolling `pr` tag — new dist-tag growth is exactly zero, and the legacy `pr-N` tags are frozen in place (still resolvable/installable, they just stop moving). PR bot comments switch Option A from `npm install -g billion-context@pr-N` to the EXACT immutable version string of that build (reproducible install, per #1108's exact-pin conclusion); `@pr` means "newest test build across ALL PRs" (semantics change: old `pr-N` meant "latest build of THAT PR"). The `0.0.x-pr.*` prerelease form is unchanged in properties: no semver range can ever resolve a PR build; `github.run_number` is unique+monotonic **per workflow** (gaps allowed) and `pr-artifact.yml` is the sole 0.0.x publisher, so concurrent publishes cannot collide, and `-a` makes a rerun of one run publish a fresh version instead of failing E409. Release drift guards (`release-manual.yml` Drift guard, `release.yml` Read version) now abort any target version `< 0.1.0`, enforcing that official releases always sort above the PR-build line. Instances explicitly configured with `ACP_UPDATE_TAG=pr-N` freeze at that tag's final build (no forced migration; see CONFIGURATION.md). diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 55d5484a8a..40d2780dd3 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -451,6 +451,47 @@ export function withStagedCompressGuidance(text: string): string { return text + STAGED_COMPRESS_GUIDANCE; } +// #2326 first-sight mass digestion. When a host hands bili a pre-inflated +// history (dsh plugin mode after its own digestion, CLI hand-off, resumed +// rollout), the first requests see a large ready mass with zero growth +// baseline: the kernel marks those nudges " [first-sight mass]" and re-arms +// after every SUCCESSFUL fold, so the backlog gets folded one small call per +// request. Each front-positioned fold rewrites the request prefix, so every +// piecemeal landing re-pays the ENTIRE remaining tail to the prefix cache — +// measured 2.29x/tok re-pay for a 5-fold cascade vs 0.032x/tok for one big +// fold (issue log: eb985b31 vs 5c5c26d1, ~70x). This note tells the model, +// at the moment of the nudge, that the ranges are a pre-existing backlog to +// drain in ONE batched call — split oversized spans into multiple ranges at +// logical boundaries (each under its per-summary cap, per the budget note +// above) but submit them ALL together in the same call — instead of piecemeal +// front folds. It deliberately REPLACES withStagedCompressGuidance during +// digestion: the smooth-transition note (smaller, tail-biased, keep the +// prefix intact) is exactly wrong for a backlog that must be drained. The +// closing precedence sentence keeps it correct on #2228 decide-directive +// injections, whose stock text pins ONE span. Byte-stable constants (like +// the notes above) so the prefix-cache anchor stays intact. +const FIRST_SIGHT_DRAIN_NOTE = + "\n\n[First-sight digestion: the compressible ranges above are a pre-existing backlog this session arrived with, not growth from your current task. Drain the backlog in ONE batched compress call — cover EVERY ready range, splitting oversized spans into multiple smaller ranges at logical boundaries (each summary within its cap), and submit them all together in the same call (content: [{startId,endId,summary}, {…}]). Do NOT fold piecemeal across turns: every small front fold re-bills the whole remaining tail to the prefix cache, while one batched call lands once. Keep draining while the nudge repeats — it stops when the backlog is gone. Where this conflicts with a single-span directive above, this takes precedence: the cited span is the starting point of the batch, not its limit.]"; +const FIRST_SIGHT_DRAIN_NOTE_EXTERNAL = + "\n\n[First-sight digestion: the compressible ranges above are a pre-existing backlog this session arrived with, not growth from your current task. The independent summary service writes the summaries — you only select the ranges (plus optional topic hints), so your own response-length budget is not a limit here. Drain the backlog in ONE batched compress call — cover EVERY ready range, splitting oversized spans into multiple smaller ranges at logical boundaries, and submit them all together in the same call (content: [{startId,endId,summary}, {…}]). Do NOT fold piecemeal across turns: every small front fold re-bills the whole remaining tail to the prefix cache, while one batched call lands once. Keep draining while the nudge repeats — it stops when the backlog is gone. Where this conflicts with a single-span directive above, this takes precedence: the cited span is the starting point of the batch, not its limit.]"; + +/** True when the kernel flagged the nudge reason with the first-sight mass + * marker (kernel/src/compress.ts appends " [first-sight mass]" while a + * pre-inflated backlog is still being digested — the marker re-rides every + * re-armed nudge until the mass drops below the growth floor). */ +export function firstSightDrainActive(reason: string | undefined): boolean { + return reason !== undefined && reason.includes("[first-sight mass]"); +} + +/** Nudge range guidance, first-sight aware (#2326): during first-sight mass + * digestion append the batched-drain note (and drop the smooth-transition + * note, which would steer the opposite direction); otherwise behave exactly + * like withStagedCompressGuidance. */ +export function withFirstSightDrain(text: string, reason: string | undefined, external: boolean): string { + if (!firstSightDrainActive(reason)) return withStagedCompressGuidance(text); + return text + (external ? FIRST_SIGHT_DRAIN_NOTE_EXTERNAL : FIRST_SIGHT_DRAIN_NOTE); +} + // #717 anti-forgery rule for ACP confirmation markers. Under sustained // context pressure a model was observed writing the proxy's own marker format // ("📦 [ACP] Compressed …") as plain assistant text — 17 fake compressions, diff --git a/src/server.ts b/src/server.ts index 27c6f22be9..c887f27033 100644 --- a/src/server.ts +++ b/src/server.ts @@ -72,7 +72,7 @@ import { type GoogleSystemInstruction, type GoogleTool, } from "acp-kernel/wire"; -import { ABSORB_TOOL_NAME, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, absorbToolsFor, retrieveToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; +import { ABSORB_TOOL_NAME, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_GOOGLE_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, absorbToolsFor, retrieveToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withMarkerIntegrityNote, withSummaryBudgetNote } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, ccrPluginWireOk, commitRetrievals, commitRetrievalNotes, contentStoreOf, dropRetrievals, executeRetrieve, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes, storeEffectiveCcr, type CcrSettings } from "./store.js"; import { buildIncomingImageIndex, foldAnchoredCutoff, pruneRetrieveImgExports } from "./image-restore.js"; diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index b8f6ff2360..adec2a3a1a 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -9,7 +9,7 @@ import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, r import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { nudgeSuppressed } from "../session-self-heal.js"; import { applyCompactionArchive, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type PendingRetrieval, type Session } from "../session.js"; -import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL, RULE_TOOL, absorbToolsFor, retrieveToolsFor, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "../compress-tool.js"; +import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL, RULE_TOOL, absorbToolsFor, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote } from "../compress-tool.js"; import { applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetrievals, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes } from "../store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote } from "../image-compress.js"; @@ -268,7 +268,7 @@ export async function prepareAnthropic( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } } catch { } @@ -280,7 +280,7 @@ export async function prepareAnthropic( if (outcome.kind === "yes") { const span = resolveDecisionRange(outcome, ranges); if (span) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(buildDirectiveText(span.startRef, span.endRef, outcome.topic)), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } else { log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); } @@ -290,7 +290,7 @@ export async function prepareAnthropic( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } } catch { } diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 49c2fab4f9..5dd590bc34 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -9,7 +9,7 @@ import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, r import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { nudgeSuppressed } from "../session-self-heal.js"; import { applyCompactionArchive, foldCoverage, markDirty, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type Session } from "../session.js"; -import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL_GOOGLE, RULE_TOOL_GOOGLE, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "../compress-tool.js"; +import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL_GOOGLE, RULE_TOOL_GOOGLE, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "../store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote } from "../image-compress.js"; @@ -196,7 +196,7 @@ export async function prepareGoogle( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withStagedCompressGuidance(renderedWithPayload), visibilityMarkers)); + rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), visibilityMarkers)); } } catch { } @@ -207,7 +207,7 @@ export async function prepareGoogle( if (outcome.kind === "yes") { const span = resolveDecisionRange(outcome, ranges); if (span) { - rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withStagedCompressGuidance(buildDirectiveText(span.startRef, span.endRef, outcome.topic)), visibilityMarkers)); + rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), visibilityMarkers)); } else { log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); } @@ -217,7 +217,7 @@ export async function prepareGoogle( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withStagedCompressGuidance(renderedWithPayload), visibilityMarkers)); + rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), visibilityMarkers)); } } catch { } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index d111e4ac6f..9755dc9539 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -11,7 +11,7 @@ import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, r import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { nudgeSuppressed } from "../session-self-heal.js"; import { applyCompactionArchive, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type PendingRetrieval, type Session } from "../session.js"; -import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL_OPENAI, RULE_TOOL_OPENAI, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "../compress-tool.js"; +import { ABSORB_TOOL_NAME, IMAGE_FULL_TOOL_OPENAI, RULE_TOOL_OPENAI, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetrievals, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes } from "../store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote } from "../image-compress.js"; @@ -229,7 +229,7 @@ export async function prepareOpenai( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } } catch { } @@ -245,7 +245,7 @@ export async function prepareOpenai( if (outcome.kind === "yes") { const span = resolveDecisionRange(outcome, ranges); if (span) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(buildDirectiveText(span.startRef, span.endRef, outcome.topic)), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } else { log("info", `[${sessionId}] [acp-decide] yes but no live range left to target — skipping injection`); } @@ -255,7 +255,7 @@ export async function prepareOpenai( const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections); const renderedWithPayload = rendered.text; if (rendered.text) { - rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }]; + rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }]; } } catch { } diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 31bb326d59..c473d87037 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -13,7 +13,7 @@ import { dropWhitespaceResponsesMessages, normalizeResponsesMessageItems, saniti import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; import { nudgeSuppressed } from "../session-self-heal.js"; import { foldCoverage, markDirty, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type Session } from "../session.js"; -import { ABSORB_TOOL_NAME, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL_RESPONSES, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressHybridSystemPrompt, buildCompressSystemPrompt, retrieveToolsFor, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "../compress-tool.js"; +import { ABSORB_TOOL_NAME, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL_RESPONSES, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressHybridSystemPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "../store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote } from "../image-compress.js"; @@ -304,7 +304,7 @@ export async function prepareResponses( const inputItems: ResponseInputItem[] = typeof rebuiltInput === "string" ? [{ type: "message", role: "user", content: rebuiltInput }] : rebuiltInput; - inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }); + inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }); rebuiltInput = inputItems; log("debug", `[${sessionId}] [inject] ephemeral nudge appended as trailing user turn (${rendered.text.length} chars)`); } @@ -325,7 +325,7 @@ export async function prepareResponses( const inputItems: ResponseInputItem[] = typeof rebuiltInput === "string" ? [{ type: "message", role: "user", content: rebuiltInput }] : [...stableItems]; - inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(buildDirectiveText(span.startRef, span.endRef, outcome.topic)), externalSummaryEnabled(config)), visibilityMarkers) }); + inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(buildDirectiveText(span.startRef, span.endRef, outcome.topic), turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }); rebuiltInput = inputItems; log("debug", `[${sessionId}] [inject] compress directive appended as trailing user turn`); } else { @@ -340,7 +340,7 @@ export async function prepareResponses( const inputItems: ResponseInputItem[] = typeof rebuiltInput === "string" ? [{ type: "message", role: "user", content: rebuiltInput }] : rebuiltInput; - inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }); + inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withFirstSightDrain(renderedWithPayload, turn.nudge.reason, externalSummaryEnabled(config)), externalSummaryEnabled(config)), visibilityMarkers) }); rebuiltInput = inputItems; log("debug", `[${sessionId}] [inject] ephemeral nudge appended as trailing user turn (${rendered.text.length} chars)`); } diff --git a/tests/first-sight-drain.test.ts b/tests/first-sight-drain.test.ts new file mode 100644 index 0000000000..5f49c928c4 --- /dev/null +++ b/tests/first-sight-drain.test.ts @@ -0,0 +1,67 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { firstSightDrainActive, withFirstSightDrain, withStagedCompressGuidance } from "../src/compress-tool.ts"; + +// #2326 first-sight mass digestion guidance. The kernel appends +// " [first-sight mass]" to the nudge reason while a pre-inflated backlog is +// still being digested (and re-arms it after every successful fold), so the +// host can key the batched-drain note on that marker. Outside digestion the +// wrapper must stay byte-identical to the legacy staged-guidance path. + +const MARKER_REASON = "context pressure: first-sight mass ready [first-sight mass]"; +const PLAIN_REASON = "context pressure: growth 51200 tokens since reference"; + +function withShrinkSwitch(value: string | undefined, fn: () => void): void { + const prev = process.env.BILI_MAX_SHRINK_PER_COMPRESS; + try { + if (value === undefined) delete process.env.BILI_MAX_SHRINK_PER_COMPRESS; + else process.env.BILI_MAX_SHRINK_PER_COMPRESS = value; + fn(); + } finally { + if (prev === undefined) delete process.env.BILI_MAX_SHRINK_PER_COMPRESS; + else process.env.BILI_MAX_SHRINK_PER_COMPRESS = prev; + } +} + +test("#2326: firstSightDrainActive keys on the kernel marker only", () => { + assert.equal(firstSightDrainActive(MARKER_REASON), true); + assert.equal(firstSightDrainActive(PLAIN_REASON), false); + assert.equal(firstSightDrainActive(""), false); + assert.equal(firstSightDrainActive(undefined), false); +}); + +test("#2326: no marker → byte-identical to the legacy staged path", () => { + withShrinkSwitch(undefined, () => { + assert.equal(withFirstSightDrain("NUDGE", PLAIN_REASON, false), withStagedCompressGuidance("NUDGE"), "switch off → unchanged"); + assert.equal(withFirstSightDrain("NUDGE", undefined, true), withStagedCompressGuidance("NUDGE"), "reason undefined → unchanged"); + }); + withShrinkSwitch("0.3", () => { + assert.equal(withFirstSightDrain("NUDGE", PLAIN_REASON, false), withStagedCompressGuidance("NUDGE"), "switch on, no marker → staged guidance still applies"); + }); +}); + +test("#2326: marker → drain note appended, staged guidance suppressed", () => { + withShrinkSwitch("0.3", () => { + const out = withFirstSightDrain("NUDGE", MARKER_REASON, false); + assert.ok(out.startsWith("NUDGE"), "keeps the original nudge"); + assert.ok(out.includes("First-sight digestion"), "appends the drain note"); + assert.ok(out.includes("ONE batched compress call"), "steers toward one batched call"); + assert.ok(out.includes("starting point of the batch, not its limit"), "carries the directive-precedence sentence"); + assert.ok(!out.includes("Smooth-transition guidance"), "staged note suppressed during digestion (opposite steering)"); + }); +}); + +test("#2326: marker + external summaries → external variant", () => { + const out = withFirstSightDrain("NUDGE", MARKER_REASON, true); + assert.ok(out.includes("independent summary service"), "external variant names the service"); + assert.ok(out.includes("response-length budget is not a limit"), "external variant lifts the output-budget concern"); + assert.ok(!out.includes("each summary within its cap"), "per-summary cap wording only in the self-written variant"); + assert.ok(!out.includes("Smooth-transition guidance"), "staged note suppressed during digestion"); +}); + +test("#2326: drain note is byte-stable for equal inputs", () => { + const a = withFirstSightDrain("NUDGE", MARKER_REASON, false); + const b = withFirstSightDrain("NUDGE", MARKER_REASON, false); + assert.equal(a, b, "prefix-cache anchor requires deterministic text"); + assert.notEqual(a, withFirstSightDrain("NUDGE", MARKER_REASON, true), "external flag switches the constant"); +}); From c2567d5780b6a680ef6d11991889a9cf29692291 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 9 Oct 2026 09:53:05 +0800 Subject: [PATCH 2/2] test: wire-level regression net for the first-sight batched-drain note (#2326) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fake-upstream harness (no model): when the kernel nudge reason carries ' [first-sight mass]', the forwarded body must carry the batched-drain note and must NOT carry the staged smooth-transition note (suppression scoped to digestion); steady-state nudges stay byte-identical to the legacy guidance; small/thin sessions never see either artifact. Also documents two sizing pitfalls the harness has to steer around: - a fresh session's first request sizes on 0 (#1492/#1820), so the first-sight nudge rides r2, sized by r1's usage report; - the model-table window (claude-sonnet-4-5 → 200K) outranks the startServer modelContextLimit fallback — pin via compress.modelContextLimit. --- tests/first-sight-drain-wire.test.ts | 247 +++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 tests/first-sight-drain-wire.test.ts diff --git a/tests/first-sight-drain-wire.test.ts b/tests/first-sight-drain-wire.test.ts new file mode 100644 index 0000000000..083ec7c236 --- /dev/null +++ b/tests/first-sight-drain-wire.test.ts @@ -0,0 +1,247 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; +// Activate the staged smooth-transition note for the whole file: the drain +// switch must SUPPRESS it inside the first-sight window (test 1) while leaving +// it on the wire in steady state (test 2) — suppression scoped to digestion. +process.env.BILI_MAX_SHRINK_PER_COMPRESS = "0.3"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// #2326: a pre-inflated history handed to bili (dsh plugin hand-off, CLI +// resume, rollout adoption) is a first-sight mass. The nudge decision for a +// brand-new session sizes on 0 (no usage report yet — see effectiveTokenCount +// #1492/#1820), so the mass lands as: r1 carries the backlog (no nudge), the +// upstream reports its real input size, and r2 — same full history resent, +// usage now known — fires the nudge with the kernel's ' [first-sight mass]' +// marker. The request pipeline must then steer the model to drain the whole +// backlog in ONE batched compress call: cascading single folds re-bill the +// remaining tail to the prefix cache on every piecemeal landing (2.29×/tok +// vs 0.032×/tok, ~70×). +// +// Wire-level regression net (fake upstream, no model): the batched-drain note +// must appear on the forwarded body exactly when the first-sight marker rides +// the nudge, and must NOT leak into steady-state nudges (byte-identical legacy +// guidance there, staged note intact). + +const MODEL = "claude-sonnet-4-5"; +// Sizing: the outbound payload (~234K chars ≈ 104K upper-bound est) must stay +// under the 95% truncate band (LIMIT 120K → 87%), while the usage-grade report +// (95K/120K = 79%) sits in the pressure band — above maxContextLimitPct 75%, +// below EMERGENCY 95% — and the ~60K pending clears the flat 50K growth cap. +const LIMIT = 120_000; +const REPORTED = 95_000; // fake upstream's usage report (sizes r2+) + +function okSse(inputTokens: number): string { + return ( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: inputTokens } } })}\n\n` + + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } })}\n\n` + + `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } })}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +// ~234K chars of compressible filler ≈ 60K pending tokens: above the 50K +// growth cap (first-sight needs a ≥-cap penalty) and an 87%-of-LIMIT upper +// bound on the outbound (under the 95% truncate band). +function bigConversation(): Array<{ role: string; content: string }> { + const msgs: Array<{ role: string; content: string }> = []; + for (let i = 0; i < 13; i++) { + const role = i % 2 === 0 ? "user" : "assistant"; + const filler = `FILLER_${i}_x`.repeat(3000); // 18K chars per message, ≥ minCompressRange + msgs.push({ role, content: `Backlog message ${i}. ${filler}` }); + } + return msgs; +} + +interface Rig { + proxyPort: number; + upstreamPort: number; + forwards: string[]; + proxy: http.Server; + upstream: http.Server; +} + +async function startRig(): Promise { + const forwards: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let parsed: { stream?: boolean } = {}; + try { parsed = JSON.parse(raw); } catch { /* keep {} */ } + if (parsed.stream) { + forwards.push(raw); + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(okSse(forwards.length === 1 ? REPORTED : REPORTED)); + } else { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "msg_s", type: "message", role: "assistant", model: MODEL, content: [{ type: "text", text: "s" }], stop_reason: "end_turn", usage: { input_tokens: 500, output_tokens: 5 } })); + } + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: LIMIT, + kernelConfig: defaultConfig(LIMIT), + // Pin the window via the OPERATOR setting (compress.modelContextLimit): + // it outranks the model-table native window (claude-sonnet-4-5 → 200K + // would otherwise win and read 58K as 29% — below the nudge band) and + // is exempt from codex-alignment clamping. + compress: { injectTool: true, injectNudge: true, modelContextLimit: LIMIT }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: true, + logFile: "/home/dog/tmp/bili12/wire-diag.log", + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + }); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + return { proxyPort, upstreamPort, forwards, proxy, upstream }; +} + +function url(rig: Rig): string { + return `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/messages`; +} + +async function post(rig: Rig, session: string, messages: Array<{ role: string; content: string }>): Promise { + const r = await fetch(url(rig), { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": session }, + body: JSON.stringify({ model: MODEL, max_tokens: 1024, stream: true, messages }), + }); + assert.equal(r.status, 200); + await r.text(); +} + +const DRAIN = "First-sight digestion"; +const BATCHED = "ONE batched compress call"; +const STAGED = "Smooth-transition guidance"; +const NUDGE_HINT = "ONE call, ONE string"; // rides every rendered nudge (ONE_CALL_HINT) + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +test("wire: first-sight mass → batched-drain note forwarded, staged note suppressed", async () => { + const rig = await startRig(); + try { + // r1: the whole backlog arrives (dsh hand-off shape). A brand-new + // session sizes on 0 — no nudge yet; the fake upstream reports the + // real input size in the SSE usage. + await post(rig, "fs-drain-1", bigConversation()); + assert.ok(!rig.forwards[0]!.includes(NUDGE_HINT), "no nudge before any usage report"); + + // r2: same full history resent, usage now usage-grade 95K/120K = 79% + // (pressure band, below EMERGENCY), pending ~60K over the 50K cap, + // fresh nudge state → band nudge + ' [first-sight mass]'. + await post(rig, "fs-drain-1", bigConversation()); + const fwd = rig.forwards[rig.forwards.length - 1]!; + assert.ok(fwd.includes(NUDGE_HINT), "nudge fired on the usage report"); + assert.ok(fwd.includes(DRAIN), "batched-drain note rides the first-sight nudge"); + assert.ok(fwd.includes(BATCHED), "note names the ONE batched call"); + assert.ok(!fwd.includes(STAGED), "smooth-transition note suppressed during digestion (BILI_MAX_SHRINK_PER_COMPRESS is set)"); + } finally { + await closeRig(rig); + } +}); + +test("wire: steady-state nudge (no first-sight marker) → legacy guidance, no drain note", async () => { + const rig = await startRig(); + try { + // r1: backlog lands; r2: first-sight nudge (marker) — sets the stamp. + await post(rig, "fs-steady", bigConversation()); + await post(rig, "fs-steady", bigConversation()); + assert.ok(rig.forwards[1]!.includes(DRAIN), "r2 was first-sight"); + + // r3: same mass again, usage still pressure-band (79%) → nudge fires + // again, but lastNudgeShownTokens > 0 and no fold re-armed it → no + // first-sight marker → output must be the legacy shape: staged note + // present (env set), drain note absent. + await post(rig, "fs-steady", bigConversation()); + const fwd = rig.forwards[rig.forwards.length - 1]!; + assert.ok(fwd.includes(NUDGE_HINT), "steady-state nudge still fires (pressure band)"); + assert.ok(!fwd.includes(DRAIN), "no batched-drain note outside the first-sight window"); + assert.ok(fwd.includes(STAGED), "staged smooth-transition note intact in steady state (no regression)"); + } finally { + await closeRig(rig); + } +}); + +test("wire: small fresh session → no nudge artifacts at all", async () => { + const rig = await startRig(); + try { + await post(rig, "fs-small", [ + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" }, + { role: "user", content: "whats up" }, + ]); + const fwd = rig.forwards[rig.forwards.length - 1]!; + assert.ok(!fwd.includes(DRAIN), "no drain note without a first-sight mass"); + assert.ok(!fwd.includes(NUDGE_HINT), "no nudge at low usage"); + assert.ok(!fwd.includes(STAGED), "no staged note either"); + } finally { + await closeRig(rig); + } +}); + +test("wire: pressure from usage report but NO mass → nudge without the drain note", async () => { + const rig = await startRig(); + try { + // r1: tiny chat (but the fake upstream reports 95K usage); r2: same + // tiny history + one small compressible message. Usage is pressure-band + // → the nudge would fire, but the compressible penalty (~4.5K tokens) is + // far under the growth cap → no first-sight marker, no drain note: the + // note keys on the MASS, not on fresh-session pressure alone. (With no + // effective pending the kernel may suppress the nudge entirely — then + // the drain note is trivially absent too; both outcomes assert that.) + const small = [ + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" }, + { role: "user", content: `Small tool result. ${"pad_x".repeat(3000)}` }, // ~6K chars, one small range + ]; + await post(rig, "fs-thin", small); + await post(rig, "fs-thin", small); + const fwd = rig.forwards[rig.forwards.length - 1]!; + if (fwd.includes(NUDGE_HINT)) { + assert.ok(!fwd.includes(DRAIN), "no drain note when there is no mass to drain"); + } else { + // Kernel suppressed the nudge entirely (benefit below floor) — also + // acceptable: either way no drain note. + assert.ok(!fwd.includes(DRAIN), "no drain note when there is no mass to drain"); + } + } finally { + await closeRig(rig); + } +});