diff --git a/src/acp-status.ts b/src/acp-status.ts index bcc125fd6f..98d16c57f5 100644 --- a/src/acp-status.ts +++ b/src/acp-status.ts @@ -3,7 +3,6 @@ import { countMessageTokens, defaultCountTokens, formatRanges, - viableRanges, type CompressionCore, type Config, type CoreMessage, @@ -11,10 +10,10 @@ import { import { conflictClientOf, conflictEventsOf, formatConflictSection } from "./conflict-watch.js"; import { getBlindTunnelStats } from "./mitm.js"; import { getUnrecognizedPathStats } from "./server/observability.js"; -import { ccrEnabled, ccrLoopConfig, contentStoreOf } from "./store.js"; +import { ccrEnabled, contentStoreOf } from "./store.js"; import { coveredRefSpan } from "./decompress-shared.js"; import { preCompactionArchiveOf, statusInputBaseline, type Session } from "./session.js"; -import { compressBreakerDetail, compressLastFailureCause } from "./stream.js"; +import { compressBreakerDetail, compressLastFailureCause, liveNudgeDecision, submitGatedRanges } from "./stream.js"; import { describeAdvisory, getAdvisoryState } from "./advisory.js"; import { getUpdateVisibility } from "./update-notes.js"; import { VERSION, BUILD_COMMIT } from "./version.js"; @@ -143,15 +142,7 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx const staleRef = lastCause !== undefined && lastCause.startsWith("stale-ref"); const substrateDestroyed = lastCause !== undefined && lastCause.startsWith("substrate-destruction"); try { - const turn = ctx.core.processTurn({ - messages: ctx.messages, - state: ctx.session.state, - config: ccrLoopConfig(ctx.session, ctx.config), - tokenCount: statusInputBaseline(ctx.session), - renderTags: "none", - contentStore: contentStoreOf(ctx.session), - }); - const nudge = turn.nudge; + const nudge = liveNudgeDecision(ctx); if (nudge) { extra.push(""); extra.push(nudge.shouldInject ? `Nudge: ACTIVE — ${nudge.reason}` : `Nudge: idle — ${nudge.reason}`); @@ -165,8 +156,7 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx // #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. - const minChars = ctx.config.compress.minCompressRange; - const ranges = viableRanges(nudge.compressibleRanges).filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars); + const ranges = submitGatedRanges(ctx.config, nudge); const protectedRanges = nudge.protectedRanges ?? []; // #2451 review (v2): the table is ALWAYS reported. It is live by // construction — buildCompressibleRanges (kernel/src/recommend.ts) diff --git a/src/stream.ts b/src/stream.ts index 6ac19c7f33..0438b82ada 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -1,5 +1,5 @@ import { createHash, randomBytes } from "node:crypto"; -import { collectBlockContent, countMessageTokens, defaultCountTokens, formatRanges, storeCoveredOriginals, viableRanges, type CompressionCore, type Config, type CoreMessage, type CompressionState, type NudgeDecision, type CompressParseDiagnostics } from "acp-kernel"; +import { collectBlockContent, countMessageTokens, defaultCountTokens, formatRanges, storeCoveredOriginals, viableRanges, type CompressionCore, type Config, type CompressibleRange, type CoreMessage, type CompressionState, type NudgeDecision, type CompressParseDiagnostics } from "acp-kernel"; import { handleAcpStatus } from "./acp-status.js"; import { handleAcpCache, recordCacheFoldsFromBlocks } from "./cache-ledger.js"; import { type Session, cacheBlockContent, markDirty, scrubTurnSeparatorIds, statusInputBaseline } from "./session.js"; @@ -7,7 +7,7 @@ import { COMPRESS_TOOL_NAME, parseCompressInput, ABSORB_TOOL_NAME, type ParsedRa import { effectiveAbsorbConfig, executeAbsorb, isProxyToolFor } from "./absorb.js"; import { executeSearchContextTarget, resolveDecompress } from "./decompress-shared.js"; import { ONE_CALL_HINT } from "acp-kernel"; -import { adoptContentStore, contentStoreOf, ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js"; +import { adoptContentStore, contentStoreOf, ccrEnabled, ccrLoopConfig, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js"; import { IMAGE_FULL_TOOL_NAME, executeImageFull, imageCompressionEnabled } from "./image-compress.js"; import { imagePlaceholdersForSummary } from "./image-note.js"; import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAcpTags } from "./loop/tag-echo-filter.js"; @@ -91,52 +91,72 @@ function refNum(ref: string): number { return Number(ref.replace(/\D/g, "")) || 0; } -/** #1026: recovery hint appended to failed-compress receipts — the raw-ref - * span NOT covered by active blocks right now. Kernel errors tell the model - * to run acp_status; a model that retries blind keeps anchoring on refs an - * earlier fold already consumed (01a0b0c4, 2026-09-18: three consecutive - * failed compresses, two full T1 checkpoints wasted, then it gave up and - * let the nudge re-fire every turn). Handing the live span over kills the - * retry loop without another round-trip. Boundary counts ACTIVE blocks - * only — after a decompress (blocks inactive) the restored span shows as - * compressible again, which is exactly the recoverable truth. */ -export function compressibleSpanHint(state: Pick): string { - const refs = Object.keys(state.messageRefs?.byRef ?? {}); - const highest = refs.reduce((m, r) => Math.max(m, r.startsWith("m") ? Number(r.slice(1)) || 0 : 0), 0); - const boundary = state.blocks.reduce((m, b) => (b.active && b.endRef?.startsWith("m") ? Math.max(m, Number(b.endRef.slice(1)) || 0) : m), 0); - const fmt = (n: number) => `m${String(n).padStart(5, "0")}`; - if (highest <= boundary) { - const actives = state.blocks.filter((b) => b.active).map((b) => b.blockId); - const span = actives.length >= 2 ? ` (e.g. startId ${actives[0]}, endId ${actives[actives.length - 1]})` : ""; - return ` No raw refs are directly compressible right now — compress a run of ACTIVE blocks instead${span}: fold their summaries into one higher-tier block. acp_status lists the current active blocks.`; +/** #2778: LIVE eligibility source shared by the failure receipts and acp_status. + * Runs processTurn read-only with the SAME call + args acp_status uses, so both + * surfaces derive compressible/protected ranges from ONE result instead of two + * divergent calculations. The old arithmetic hint (highest-ref minus block + * boundary, #1026/#1366/#2362) advertised spans the apply-side gate + * deterministically refuses — a protected tail, a covered prefix, or a + * sub-minimum range — so "Retry NOW" pointed at a guaranteed refusal and turned + * one bad call into a self-amplifying retry loop. processTurn is pure; the + * returned state is deliberately NOT adopted here (the receipt must not mutate + * session state as a side effect of reporting failure). */ +type LiveEligibilitySource = { core: CompressionCore; config: Config; messages: CoreMessage[]; session: Session }; + +export function liveNudgeDecision(src: LiveEligibilitySource): NudgeDecision | undefined { + try { + const turn = src.core.processTurn({ + messages: src.messages, + state: src.session.state, + config: ccrLoopConfig(src.session, src.config), + tokenCount: statusInputBaseline(src.session), + renderTags: "none", + contentStore: contentStoreOf(src.session), + }); + return turn.nudge; + } catch { + return undefined; } - // #1366: blocks need not be contiguous — a gap below the highest block end - // (e.g. m05027–m05052 between two blocks) is still compressible raw space, so - // claiming "everything up to N is inside blocks" misleads models into skipping it. - const covered = boundary > 0 ? ` (refs up to ${fmt(boundary)} are largely inside active blocks; isolated free gaps may still exist below it)` : ""; - // #2362: dead refs (the client history no longer carries their messages) - // can never compress — subtract them from the advertised span so a retry - // does not steer the model back into a doomed range (self-amplifying loop). - const dead = new Set(); - for (const r of state.deadRefs ?? []) { - const n = Number(r.replace(/\D/g, "")); - if (Number.isFinite(n) && n > boundary && n <= highest) dead.add(n); +} + +/** #847 submit gate, shared verbatim with acp_status: a range is only worth + * advertising when it clears BOTH the viability floor (>=200 tokens) and the + * apply-side minCompressRange char count — otherwise the kernel atomically + * rejects it and the model burns another round-trip on the refusal. */ +export function submitGatedRanges(config: Config, nudge: NudgeDecision): CompressibleRange[] { + const minChars = config.compress.minCompressRange; + return viableRanges(nudge.compressibleRanges).filter( + (r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars, + ); +} + +/** #2778: single-line recovery hint built from LIVE eligibility (the same source + * acp_status advertises). Offers only ranges that clear the viability floor AND + * the apply-side size gate, so "Retry NOW" can no longer point at a protected + * tail / covered prefix / sub-minimum range. When nothing raw is eligible it + * falls through to block distillation (>=2 active blocks) or an honest stop — + * never a fabricated span. Stays on one line: buildVisibilityMarker keeps only + * line 1 for the client ❌ marker (#1029), so no multi-line formatRanges here. */ +export function liveSpanHint(ctx: RewriteCtx): string { + const nudge = liveNudgeDecision(ctx); + if (!nudge) { + return ` Run acp_status to see the current compressible refs before retrying — do not guess a range.`; } - const spans: string[] = []; - let cursor = boundary + 1; - for (const d of [...dead].sort((a, b) => a - b)) { - if (d > cursor) spans.push(cursor === d - 1 ? fmt(cursor) : `${fmt(cursor)}–${fmt(d - 1)}`); - cursor = d + 1; - if (cursor > highest) break; + const ranges = submitGatedRanges(ctx.config, nudge); + if (ranges.length > 0) { + return ` Live compressible refs right now: ${ranges.map(spanText).join(", ")}. Retry NOW in this same turn using one of these exact ranges — each clears the size and protection gates.`; } - if (cursor <= highest) spans.push(cursor === highest ? fmt(cursor) : `${fmt(cursor)}–${fmt(highest)}`); - if (spans.length === 0) { - return ` No live raw refs right now: every ref between ${fmt(boundary + 1)} and ${fmt(highest)} is DEAD — the client history no longer carries those messages (host-native compaction or a bulk rewrite), so no range citing them can ever compress. Compress a run of ACTIVE blocks instead or work within your current visible context.`; + const actives = ctx.session.state.blocks.filter((b) => b.active).map((b) => b.blockId); + if (actives.length >= 2) { + return ` No raw refs are directly compressible right now — compress a run of ACTIVE blocks instead (startId ${actives[0]}, endId ${actives[actives.length - 1]}): fold their summaries into one higher-tier block. acp_status lists the current active blocks.`; } - const deadNote = dead.size > 0 - ? ` Excluded as DEAD (${dead.size} ref(s) whose messages the client no longer sends — they can never compress): ${[...dead].sort((a, b) => a - b).slice(0, 4).map(fmt).join(", ")}${dead.size > 4 ? ", …" : ""}.` - : ""; - return ` Live compressible refs: ${spans.join(", ")}${covered}. Retry NOW in this same turn with startId/endId inside that span.${deadNote}`; + return ` No compressible ranges right now — recent messages are protected and/or everything else is already folded, so nothing clears the compression gates yet. Continue the task without compressing; a range re-offers once enough new content accumulates.`; +} + +function spanText(r: { startRef: string; endRef: string }): string { + return refNum(r.startRef) <= refNum(r.endRef) + ? `${r.startRef}\u2013${r.endRef}` + : `${r.endRef}\u2013${r.startRef}`; } const M_REF_NUM_RE = /^m0*(\d{1,7})$/i; @@ -635,7 +655,7 @@ export function applyRanges(parsed: ReturnType, ctx: const truncNote = diagnostics.kind === "truncated" ? " (looks truncated)" : ""; return compressResult(`[Compression FAILED: the call's arguments (${argLen} chars) were not parseable JSON${truncNote} — the intended content was lost and nothing was compressed. Re-issue the compress call as well-formed JSON: a single object with a non-empty 'content' array of {startId, endId, summary} elements.${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); } - return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why} compress requires a non-empty 'content' array where each element is EITHER an object {startId, endId, summary} OR one line-form string whose first line is 'mNNNNN–mNNNNN optional topic' with the summary markdown on the following lines (a separate summary-only element right after a bare header line is also accepted). startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${compressibleSpanHint(ctx.session.state)} Re-issue the compress call with a valid content array.${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); + return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why} compress requires a non-empty 'content' array where each element is EITHER an object {startId, endId, summary} OR one line-form string whose first line is 'mNNNNN–mNNNNN optional topic' with the summary markdown on the following lines (a separate summary-only element right after a bare header line is also accepted). startId/endId are mNNNNN message refs from the conversation.${liveSpanHint(ctx)} Re-issue the compress call with a valid content array.${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); } // #847: detect reversed refs as SUBMITTED, before #1001 normalization // rewrites them (order matters — normalizeRangeOrder mutates in place). @@ -746,10 +766,7 @@ export function applyRanges(parsed: ReturnType, ctx: ? ` Note: startId > endId in range(s) ${revs.map((rg) => `${rg.startRef}→${rg.endRef}`).join(", ")} — your refs were reversed; they were normalized to ascending order before evaluation, so check your ref order.` : ""; ctx.log(`[acp-proxy: compress FAILED ${detail} → 0 blocks. ${errs}${revs.length > 0 ? " [reversed refs]" : ""}]`); - // #1036 span hint names boundary+1..highest ("still raw") — it - // duplicates the snapshot's lo–hi exactly when no fold covers - // anything, so only append it when active blocks exist. - const spanHint = ctx.session.state.blocks.some((b) => b.active) ? compressibleSpanHint(ctx.session.state) : ""; + const spanHint = liveSpanHint(ctx); // #1112: when the ENTIRE visible context is under the minimum, no // COMBINATION of ranges can succeed either (the kernel sums chars // across ranges against one threshold) — the generic "combine more diff --git a/tests/compress-span-hint.test.ts b/tests/compress-span-hint.test.ts index 0b89a1048b..7b5d18dfb6 100644 --- a/tests/compress-span-hint.test.ts +++ b/tests/compress-span-hint.test.ts @@ -1,12 +1,18 @@ -// #1026: failed compress receipts must name the live compressible span so the -// model recovers in one retry instead of re-issuing refs an earlier fold -// already consumed (port of PR #1008's head commit, slimmed). +// #2778: failed-compress recovery hints must advertise ONLY ranges the actual +// apply-side gate accepts. The old arithmetic hint (highest-ref minus block +// boundary) pointed "Retry NOW" at spans the gate deterministically refuses — +// a protected tail, a covered prefix, or a sub-minimum range — so one refused +// call became a self-amplifying retry loop. The hint now derives from the SAME +// live eligibility acp_status reports (shared liveNudgeDecision/submitGatedRanges +// source), and falls through to block distillation or an honest stop when +// nothing raw is eligible. Supersedes the #1026/#1366/#2362 arithmetic-era +// assertions below the shared-source rewrite. import { test } from "node:test"; import assert from "node:assert/strict"; -import type { CoreMessage } from "acp-kernel"; +import type { CoreMessage, Config } from "acp-kernel"; import { createCore, createInitialState, defaultConfig, assignRefs, emptyRefMap, deactivateBlock } from "acp-kernel"; import { parseCompressInput } from "../src/compress-tool.ts"; -import { applyRanges, compressibleSpanHint, type RewriteCtx } from "../src/stream.ts"; +import { applyRanges, liveSpanHint, type RewriteCtx } from "../src/stream.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; type Ctx = Omit & { log: (m: string) => void; logs: string[] }; @@ -17,11 +23,15 @@ const MESSAGES = Array.from({ length: 80 }, (_, i) => ({ text: "lorem ipsum dolor sit amet conseq ".repeat(8) + i, })) as unknown as CoreMessage[]; -function makeCtx(): Ctx { +function cfgNoProtect(): Config { + return defaultConfig(200000, { preserveRecentMessages: 0, preserveRecentTokens: 0 }); +} + +function makeCtx(config?: Config): Ctx { const logs: string[] = []; return { core: createCore(), - config: defaultConfig(200000), + config: config ?? defaultConfig(200000), messages: MESSAGES, session: { id: "span-hint-test", @@ -41,91 +51,117 @@ function makeCtx(): Ctx { }; } -/** refs m00001..m00080 + one ACTIVE kernel block covering m00002..m00020 */ -function makeFoldedCtx(): Ctx { - const ctx = makeCtx(); - ctx.session.state.messageRefs = assignRefs(MESSAGES, { existing: emptyRefMap(), nextIndex: 0 }).map; - const r = ctx.core.applyCompression({ ranges: [{ startRef: "m00002", endRef: "m00020", summary: "y".repeat(100) }], messages: MESSAGES, state: ctx.session.state, config: ctx.config }); +function seedRefs(ctx: Ctx): void { + ctx.session.state.messageRefs = assignRefs(ctx.messages, { existing: emptyRefMap(), nextIndex: 0 }).map; +} + +/** refs assigned + one ACTIVE kernel block covering m00002..m00020 */ +function makeFoldedCtx(config?: Config): Ctx { + const ctx = makeCtx(config); + seedRefs(ctx); + const r = ctx.core.applyCompression({ ranges: [{ startRef: "m00002", endRef: "m00020", summary: "y".repeat(100) }], messages: ctx.messages, state: ctx.session.state, config: ctx.config }); assert.equal(r.result.blocksCreated, 1, `seed fold must succeed: ${r.result.errors.join("; ")}`); ctx.session.state = r.state; return ctx; } -test("#1026: hint names the raw span past the highest ACTIVE block boundary", () => { +test("#2778: CORE — a fully-protected tail offers no retry push (old bug)", () => { + // defaultConfig(200000): preserveRecentTokens=5000 shields every remaining + // raw ref, so nothing clears the gate. The arithmetic hint used to say + // "Live compressible refs: m00021–m00080 … Retry NOW" here. const ctx = makeFoldedCtx(); - const hint = compressibleSpanHint(ctx.session.state); - assert.ok(hint.includes("m00021–m00080"), `span past boundary: ${hint}`); - assert.ok(hint.includes("inside active blocks"), `explains the covered prefix: ${hint}`); - // #1366: the covered-prefix claim must stay hedged — blocks need not be contiguous, - // and a flat "everything up to N" misled a model into skipping a live gap. - assert.ok(hint.includes("isolated free gaps may still exist"), `gap hedge present: ${hint}`); + const hint = liveSpanHint(ctx); + assert.ok(!hint.includes("Retry NOW"), `must not push a doomed retry: ${hint}`); + assert.ok(!hint.includes("Live compressible refs right now"), `must not advertise the protected tail: ${hint}`); + assert.ok(hint.includes("No compressible ranges right now"), `honest stop expected: ${hint}`); + assert.ok(hint.includes("Continue the task"), `tells the agent to move on: ${hint}`); + assert.ok(!hint.includes("\n"), `single-line receipt constraint (#1029): ${hint}`); }); -test("#1026: INACTIVE blocks (decompressed) do not hold the boundary", () => { - const ctx = makeFoldedCtx(); - ctx.session.state = deactivateBlock(ctx.session.state, [ctx.session.state.blocks[0]!.blockId]); - const hint = compressibleSpanHint(ctx.session.state); - assert.ok(hint.includes("m00001–m00080"), `decompressed block releases the boundary: ${hint}`); +test("#2778: eligible live ranges ARE offered when they clear the gates", () => { + const ctx = makeFoldedCtx(cfgNoProtect()); + const hint = liveSpanHint(ctx); + assert.ok(hint.includes("Live compressible refs right now"), `eligible span offered: ${hint}`); + assert.ok(hint.includes("Retry NOW"), `retry push only when genuinely eligible: ${hint}`); + assert.match(hint, /m0\d{4}–m0\d{4}/, `names concrete ref spans: ${hint}`); + assert.ok(!hint.includes("\n"), `single-line: ${hint}`); }); -test("#1026: exhausted refs fall back to compressing ACTIVE blocks by real id", () => { - const ctx = makeCtx(); - ctx.session.state.messageRefs = assignRefs(MESSAGES, { existing: emptyRefMap(), nextIndex: 0 }).map; - // fake blocks: only the shape compressibleSpanHint reads - ctx.session.state.blocks = [ - { blockId: "b7", endRef: "m00025", active: true }, - { blockId: "b11", endRef: "m00080", active: true }, - { blockId: "b13", endRef: "m00080", active: false }, - ] as never; - const hint = compressibleSpanHint(ctx.session.state); - assert.ok(hint.includes("compress a run of ACTIVE blocks"), `fallback wording: ${hint}`); - assert.ok(hint.includes("startId b7, endId b11"), `real block ids, inactive excluded: ${hint}`); +test("#2778: >=2 active blocks with no eligible raw falls to block distillation by real id", () => { + const ctx = makeCtx(cfgNoProtect()); + seedRefs(ctx); + for (const [s, e] of [["m00001", "m00040"], ["m00041", "m00080"]] as const) { + const r = ctx.core.applyCompression({ ranges: [{ startRef: s, endRef: e, summary: "y".repeat(100) }], messages: ctx.messages, state: ctx.session.state, config: ctx.config }); + assert.equal(r.result.blocksCreated, 1, `fold ${s}..${e}: ${r.result.errors.join("; ")}`); + ctx.session.state = r.state; + } + const actives = ctx.session.state.blocks.filter((b) => b.active).map((b) => b.blockId); + assert.ok(actives.length >= 2, `expected >=2 active blocks, got ${actives.join(",")}`); + const hint = liveSpanHint(ctx); + assert.ok(hint.includes("compress a run of ACTIVE blocks instead"), `distill wording: ${hint}`); + assert.ok(hint.includes(`startId ${actives[0]}, endId ${actives[actives.length - 1]}`), `real block ids: ${hint}`); + assert.ok(!hint.includes("Retry NOW"), `no raw-retry push when raw is exhausted: ${hint}`); }); -test("#1026: no-valid-ranges receipt carries the live span", () => { - _setStoreForTest(new SessionStore({ enabled: false })); - const ctx = makeFoldedCtx(); - const out = applyRanges(parseCompressInput({ content: [{ summary: "no bounds" }] }), ctx).text; - assert.ok(out.startsWith("[Compression FAILED"), `failure receipt: ${out}`); - assert.ok(out.includes("Live compressible refs: m00021–m00080"), `span inside receipt: ${out}`); +test("#2778: dead/absent refs are never named as offered targets", () => { + const ctx = makeFoldedCtx(cfgNoProtect()); + // client history rewrite drops two messages; record their refs dead. + ctx.messages = ctx.messages.filter((m) => m.id !== "raw40" && m.id !== "raw54"); + ctx.session.state.deadRefs = ["m00041", "m00055"]; + const hint = liveSpanHint(ctx); + // absent refs cannot be span endpoints, so the live source never surfaces + // them as offered targets (the old arithmetic hint carved fake gaps here). + assert.ok(!hint.includes("m00041"), `dead ref not offered: ${hint}`); + assert.ok(!hint.includes("m00055"), `dead ref not offered: ${hint}`); + assert.ok(!hint.includes("\n"), `single-line: ${hint}`); }); -test("#1026: blocksCreated=0 receipt carries the live span", () => { - _setStoreForTest(new SessionStore({ enabled: false })); - const ctx = makeFoldedCtx(); - // stale refs (never assigned) → kernel rejects the range → 0 blocks - const out = applyRanges(parseCompressInput({ content: [{ startId: "m09999", endId: "m09999", summary: "s" }] }), ctx).text; - assert.ok(out.startsWith("[Compression FAILED"), `failure receipt: ${out}`); - assert.ok(out.includes("Live compressible refs: m00021–m00080"), `span inside receipt: ${out}`); +test("#2778: a sub-minimum conversation offers no retry push (min size gate)", () => { + const ctx = makeCtx(cfgNoProtect()); + ctx.messages = MESSAGES.slice(0, 4); + seedRefs(ctx); + const hint = liveSpanHint(ctx); + assert.ok(!hint.includes("Retry NOW"), `below minCompressRange must not push retry: ${hint}`); + assert.ok(!hint.includes("Live compressible refs right now"), `sub-minimum range not advertised: ${hint}`); + assert.ok(hint.includes("No compressible ranges right now"), `honest stop: ${hint}`); }); -// #2362: dead refs can never compress — the advertised live span must subtract -// them so a retry does not steer the model back into a doomed range. +test("#2778: unavailable status degrades to 'run acp_status', never a guessed span", () => { + const ctx = makeCtx(); + seedRefs(ctx); + ctx.core.processTurn = () => { throw new Error("boom"); }; + const hint = liveSpanHint(ctx); + assert.ok(hint.includes("Run acp_status"), `points at acp_status: ${hint}`); + assert.ok(hint.includes("do not guess"), `forbids guessing a range: ${hint}`); + assert.ok(!hint.includes("Retry NOW"), `no retry push on unavailable status: ${hint}`); +}); -test("#2362: dead refs are carved out of the advertised live span", () => { - const ctx = makeFoldedCtx(); - ctx.session.state.deadRefs = ["m00041", "m00042", "m00055"]; - const hint = compressibleSpanHint(ctx.session.state); - assert.ok(hint.includes("Live compressible refs: m00021–m00040, m00043–m00054, m00056–m00080"), `spans minus dead: ${hint}`); - assert.ok(hint.includes("Excluded as DEAD (3 ref(s)"), `dead note present: ${hint}`); - assert.ok(hint.includes("m00041, m00042, m00055"), `dead refs named: ${hint}`); +test("#2778: a decompressed (inactive) block releases its span back into the offer", () => { + const ctx = makeFoldedCtx(cfgNoProtect()); + ctx.session.state = deactivateBlock(ctx.session.state, [ctx.session.state.blocks[0]!.blockId]); + const hint = liveSpanHint(ctx); + assert.ok(hint.includes("Live compressible refs right now"), `freed span offered again: ${hint}`); + assert.match(hint, /m0\d{4}–m0\d{4}/, `names concrete ref spans: ${hint}`); + assert.ok(!hint.includes("\n"), `single-line: ${hint}`); }); -test("#2362: an all-dead span says there are no live raw refs and drops the retry push", () => { +test("#2778: no-valid-ranges receipt carries the LIVE hint (no false protected-tail span)", () => { + _setStoreForTest(new SessionStore({ enabled: false })); const ctx = makeFoldedCtx(); - const dead = Object.keys(ctx.session.state.messageRefs.byRef) - .filter((r) => Number(r.slice(1)) > 20 && Number(r.slice(1)) <= 80); - ctx.session.state.deadRefs = dead; - const hint = compressibleSpanHint(ctx.session.state); - assert.ok(hint.includes("No live raw refs right now: every ref between m00021 and m00080 is DEAD"), `all-dead wording: ${hint}`); - assert.ok(!hint.includes("Retry NOW"), `no retry push into a doomed span: ${hint}`); + const out = applyRanges(parseCompressInput({ content: [{ summary: "no bounds" }] }), ctx).text; + assert.ok(out.startsWith("[Compression FAILED"), `failure receipt: ${out}`); + assert.ok(out.includes("No compressible ranges right now"), `live-derived honest stop: ${out}`); + assert.ok(!out.includes("Retry NOW in this same turn"), `no false retry into the protected tail: ${out}`); + assert.ok(!out.includes("\n"), `single-line receipt (#1029): ${out}`); }); -test("#2362: failure receipts advertise the dead-subtracted span", () => { +test("#2778: blocksCreated=0 receipt carries the LIVE hint (no false protected-tail span)", () => { _setStoreForTest(new SessionStore({ enabled: false })); const ctx = makeFoldedCtx(); - ctx.session.state.deadRefs = ["m00041", "m00042", "m00055"]; - const out = applyRanges(parseCompressInput({ content: [{ summary: "no bounds" }] }), ctx).text; + // stale refs (never assigned) → kernel rejects the range → 0 blocks + const out = applyRanges(parseCompressInput({ content: [{ startId: "m09999", endId: "m09999", summary: "s" }] }), ctx).text; assert.ok(out.startsWith("[Compression FAILED"), `failure receipt: ${out}`); - assert.ok(out.includes("Live compressible refs: m00021–m00040, m00043–m00054, m00056–m00080"), `receipt span excludes dead: ${out}`); + assert.ok(out.includes("No compressible ranges right now"), `live-derived honest stop: ${out}`); + assert.ok(!out.includes("Retry NOW in this same turn"), `no false retry into the protected tail: ${out}`); + assert.ok(!out.includes("\n"), `single-line receipt (#1029): ${out}`); });