Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion kernel/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
"version": "0.0.223",
"version": "0.0.224",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
24 changes: 23 additions & 1 deletion kernel/src/recommend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type {
} from "./types.js";
import type { CompressionState } from "./types.js";
import { isToolMessage } from "./message-kind.js";
import { coveredMessageIds, isLiveCheckpointCarrier } from "./state.js";
import { blockById, coveredMessageIds, isLiveCheckpointCarrier } from "./state.js";
import { SUMMARY_HEADER } from "./prune.js";
import {
collectFailedCompressCallIds,
Expand Down Expand Up @@ -800,6 +800,28 @@ export function screenRecommendedUnits(
}
return false;
}
// #8014: mirror the apply guard (compress.ts retiredConsumed) — a unit
// whose consumedBlockIds contains a retired block is a GUARANTEED
// apply-time throw ("would consume retired block(s) — their summaries are
// out of the resident view by explicit user decision"), so it must never
// be advertised. The screen previously had no retired judgment at all, so
// after a block was retired the top recommendation stayed a guaranteed
// rejection on every turn (the #3236 advertise/reject loop reached through
// its last shape). Unconditional (no refold carve): in apply the retired
// guard fires BEFORE the refold route, and a refold can only target
// restoredInline blocks — a retired block is not restoredInline — so a
// legitimate refold never consumes a retired block and this drop cannot
// break the refold route.
const retiredConsumed = projection.consumedBlockIds.filter(
(id) => blockById(state, id)?.retired === true,
);
if (retiredConsumed.length > 0) {
warnScreenDrop(
warn,
`dropped unit ${unit.startRef}..${unit.endRef}: consumes retired block(s) ${retiredConsumed.join(", ")} (out of the resident view by explicit user decision)`,
);
return false;
}
if (
projection.filteredIds.length === 0 &&
projection.consumedBlockIds.length === 0
Expand Down
238 changes: 238 additions & 0 deletions kernel/tests/issue8014-retired-recommend.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createCore } from "../src/compress.js";
import { createInitialState } from "../src/state.js";
import { defaultConfig } from "../src/config.js";
import { retireBlocks } from "../src/block-ops.js";
import { markBlockRestoredInline } from "../src/decompress.js";
import type { Config, CompressionState, CoreMessage } from "../src/types.js";

// #8014: after a block is retired (acp_retire / blockOps.enabled), the
// recommend/nudge screen kept advertising fold units that span it, while the
// apply lane refuses any range that would consume a retired block ("their
// summaries are out of the resident view by explicit user decision"). The top
// recommendation was therefore a guaranteed rejection on EVERY turn — the
// #3236 advertise/reject contract ("every advertised range must apply cleanly")
// violated through its last shape: the screen had no retired judgment at all.
//
// The screen now mirrors the apply guard (compress.ts retiredConsumed) and
// drops a unit whose consumedBlockIds contains a retired block. Contract: every
// advertised unit applies cleanly with a retired block mid-history, and the
// same stretch is still advertised when nothing is retired (no over-screening).

function config(): Config {
return defaultConfig(200000, {
preserveRecentMessages: 2,
preserveRecentTokens: 0,
blockOps: { enabled: true },
tiers: { enabled: true, tier2Trigger: 2, tier3Trigger: 3 },
compress: {
minCompressRange: 150,
maxSummaryLength: 20000,
minSummaryLength: 10,
},
});
}

function buildMessages(): CoreMessage[] {
return Array.from({ length: 36 }, (_, i) => ({
id: `id${i}`,
role: (i % 2 ? "assistant" : "user") as CoreMessage["role"],
contentType: "text" as const,
text: `message ${i} ` + "x".repeat(260),
}));
}

interface Scenario {
core: ReturnType<typeof createCore>;
state: CompressionState;
messages: CoreMessage[];
cfg: Config;
}

// Three same-tier blocks b1/b2/b3 over a 36-message history, b2 mid-history.
// `retire` marks b2 retired (the #8014 shape); the control leaves it active.
function buildScenario(retire: boolean): Scenario {
const cfg = config();
const messages = buildMessages();
const core = createCore();
let state = core
.processTurn({
messages,
state: createInitialState(),
config: cfg,
tokenCount: 100,
})
.state;
const ref = (id: string) => state.messageRefs.byRaw[id]!;
const fold = (a: string, b: string, label: string) => {
const r = core.applyCompression({
ranges: [{ startRef: a, endRef: b, summary: label + " " + "s".repeat(60) }],
messages,
state,
config: cfg,
});
assert.equal(
r.result.errors.length,
0,
`setup fold ${label} failed: ${r.result.errors.join("; ")}`,
);
state = r.state;
};
fold(ref("id1"), ref("id5"), "b1");
fold(ref("id7"), ref("id11"), "b2");
fold(ref("id13"), ref("id17"), "b3");
if (retire) {
const outcome = retireBlocks(state, ["b2"]);
assert.deepEqual(outcome.applied, ["b2"], "b2 retires");
}
return { core, state, messages, cfg };
}

function refNum(ref: string): number {
const m = /^m(\d+)$/i.exec(ref);
return m ? Number(m[1]) : -1;
}

/** True when the advertised unit [startRef, endRef] covers the whole stretch
* [loRef, hiRef] (the retired block's first..last covered message). */
function coversStretch(
unit: { startRef: string; endRef: string },
loRef: string,
hiRef: string,
): boolean {
return refNum(unit.startRef) <= refNum(loRef) && refNum(unit.endRef) >= refNum(hiRef);
}

/** THE contract (#3236 lineage, #8014 shape): every advertised unit applies
* cleanly against the very state it was advertised from. */
function assertAdvertisedApplyCleanly(
scenario: Scenario,
label: string,
): void {
const { core, state, messages, cfg } = scenario;
const processed = core.processTurn({
messages,
state,
config: cfg,
tokenCount: 9000,
renderTags: "none",
});
const ranges = processed.nudge?.compressibleRanges ?? [];
assert.ok(ranges.length > 0, `${label}: fresh content must be advertised`);
for (const r of ranges) {
const applied = core.applyCompression({
ranges: [
{ startRef: r.startRef, endRef: r.endRef, summary: "apply " + "s".repeat(60) },
],
messages,
state: structuredClone(state),
config: cfg,
});
assert.equal(
applied.result.errors.length,
0,
`${label}: advertised ${r.startRef}-${r.endRef} failed to apply: ${applied.result.errors.join("; ")}`,
);
}
}

test("#8014: every advertised unit applies cleanly with a retired block mid-history", () => {
const scenario = buildScenario(true);
const { state, messages, cfg, core } = scenario;
const ref = (id: string) => state.messageRefs.byRaw[id]!;
const b2Lo = ref("id7");
const b2Hi = ref("id11");

const processed = core.processTurn({
messages,
state,
config: cfg,
tokenCount: 9000,
renderTags: "none",
});
const ranges = processed.nudge?.compressibleRanges ?? [];
assert.ok(ranges.length > 0, "retired: non-spanning content must still be advertised");

// The spanning unit over the retired block b2 must NOT be advertised — it is
// a guaranteed apply-time throw ("would consume retired block(s) b2").
const spanning = ranges.filter((r) => coversStretch(r, b2Lo, b2Hi));
assert.equal(
spanning.length,
0,
`retired: no advertised unit may span the retired block b2 (${b2Lo}..${b2Hi}), got: ${spanning
.map((r) => `${r.startRef}..${r.endRef}`)
.join(", ")}`,
);

// THE contract: every advertised unit applies cleanly.
assertAdvertisedApplyCleanly(scenario, "retired");
});

test("#8014 control: the same stretch is still advertised when nothing is retired", () => {
const scenario = buildScenario(false);
const { state, messages, cfg, core } = scenario;
const ref = (id: string) => state.messageRefs.byRaw[id]!;
const b2Lo = ref("id7");
const b2Hi = ref("id11");

const processed = core.processTurn({
messages,
state,
config: cfg,
tokenCount: 9000,
renderTags: "none",
});
const ranges = processed.nudge?.compressibleRanges ?? [];

// No over-screening: with b2 active, the spanning unit covering b2's stretch
// (the one the retired case drops) MUST still be advertised.
assert.ok(
ranges.some((r) => coversStretch(r, b2Lo, b2Hi)),
`control: the stretch over the active block b2 (${b2Lo}..${b2Hi}) must be advertised, got: ${ranges
.map((r) => `${r.startRef}..${r.endRef}`)
.join(", ")}`,
);

// And it applies cleanly (b2 is active, so consuming it is legal).
assertAdvertisedApplyCleanly(scenario, "control");
});

// Corner (ported from the parallel #8014 PR's suite): a block that is BOTH
// retired AND restoredInline. The unit spanning it also consumes the
// restored-inline neighbour b1, so evaluateRefold classifies it "refold" —
// the exact shape a refold carve-out in the screen would have kept
// advertised. But apply's retired guard runs BEFORE its refold route
// (applySingleRange), so such a unit is a guaranteed rejection and must not
// be advertised.
test("#8014 corner: a retired+restoredInline block is not advertised either (no refold exception)", () => {
const scenario = buildScenario(false);
const { state, messages, cfg, core } = scenario;
let s = markBlockRestoredInline(state, "b1").state;
s = markBlockRestoredInline(s, "b2").state;
const outcome = retireBlocks(s, ["b2"]);
assert.deepEqual(outcome.applied, ["b2"], "b2 retires");
const retired = s.blocks.find((b) => b.blockId === "b2")!;
assert.equal(retired.retired, true);
assert.equal(retired.restoredInline, true);
const ref = (id: string) => s.messageRefs.byRaw[id]!;
const b2Lo = ref("id7");
const b2Hi = ref("id11");

const processed = core.processTurn({
messages,
state: s,
config: cfg,
tokenCount: 9000,
renderTags: "none",
});
const ranges = processed.nudge?.compressibleRanges ?? [];
const spanning = ranges.filter((r) => coversStretch(r, b2Lo, b2Hi));
assert.equal(
spanning.length,
0,
`corner: no advertised unit may span the retired+restoredInline block b2 (${b2Lo}..${b2Hi}), got: ${spanning
.map((r) => `${r.startRef}..${r.endRef}`)
.join(", ")}`,
);
});
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading