diff --git a/kernel/package-lock.json b/kernel/package-lock.json
index 00da442c39..df80849a7c 100644
--- a/kernel/package-lock.json
+++ b/kernel/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "acp-kernel",
- "version": "0.0.160",
+ "version": "0.0.161",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "acp-kernel",
- "version": "0.0.160",
+ "version": "0.0.161",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.0.0",
diff --git a/kernel/package.json b/kernel/package.json
index 976310a02e..e41b7fbd61 100644
--- a/kernel/package.json
+++ b/kernel/package.json
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
- "version": "0.0.160",
+ "version": "0.0.161",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
diff --git a/kernel/src/wire/anthropic.ts b/kernel/src/wire/anthropic.ts
index 9a97a4d4de..0af98bd7ab 100644
--- a/kernel/src/wire/anthropic.ts
+++ b/kernel/src/wire/anthropic.ts
@@ -363,21 +363,11 @@ function rebuildSystemMessage(
};
}
-// #4292: bili's prune inserts each fold summary at the earliest covered
-// position (kernel/src/prune.ts insertAt), so a client mid-conversation
-// system message (verbatim via rawAnthropicMessage) orphaned by that fold is
-// ALWAYS immediately followed by the no-sidecar core system anchor —
-// emitting [.., system, anchor-as-user, ..] makes Anthropic 400 the session
-// permanently ("role 'system' must precede an 'assistant' message or end
-// the array"). Re-voice exactly that adjacency to user; every other client
-// layout stays verbatim — the kernel is transport, not a validator, so even
-// positionally-illegal client shapes round-trip byte-exact. Fresh objects
-// are substituted, never mutations, so session sidecars stay intact.
-// A directive-only system (empty content + output_config) is accepted at ANY
-// position by Anthropic's mid-conversation-system rule, so it is never part of
-// the orphan signature. Re-voicing it would mint an empty-content user message
-// that 400s on its own — leave those in place (mirrors the reporter's
-// isAnthropicDirectiveOnlySystem; #4292 hardening).
+// #4292 hardening, kept for #4457's backstop: a directive-only system
+// (empty content + output_config) is accepted at ANY position by
+// Anthropic's mid-conversation-system rule, so it is never healed; demoting
+// it would mint an empty-content user message that 400s on its own
+// (mirrors the reporter's isAnthropicDirectiveOnlySystem).
function isDirectiveOnlySystem(e: AnthropicWireMessage): boolean {
return (
e.role === "system" &&
@@ -387,12 +377,57 @@ function isDirectiveOnlySystem(e: AnthropicWireMessage): boolean {
);
}
-function revoiceFoldOrphanedSystems(out: AnthropicWireMessage[]): void {
- for (let j = out.length - 1; j >= 0; j--) {
+// #4457: Anthropic accepts a mid-conversation system only immediately
+// before an assistant message or at the end of the array — any other
+// position 400s the whole request, permanently killing the session (a run
+// of consecutive systems is judged by the run's first non-system follower:
+// Pi's trailing tool-delta + effort-marker runs are legal at array end).
+// The fold layer keeps sidecar systems OUT of folds (kernel/src/protected.ts
+// never-fold carve): their tool deltas are FUNCTIONAL under Anthropic's
+// mid-conversation-tool-changes contract — tools[] stays static for cache
+// stability and the deltas control which tools are offered (defer_loading
+// surfacing, by-value definitions, removals, MCP toolsets) — so folding them
+// would silently alter the effective tool set. Orphans still arise when a
+// fold covers the assistant that legitimized one; this position-based
+// backstop heals whatever still arrives illegal: sessions folded by older
+// builds and positionally-illegal client input. Demotion re-voices to user
+// with tool_addition/tool_removal blocks stripped first (WC-022 forbids them
+// outside system) and drops the entry when nothing remains; a
+// directive-only system (empty content + output_config) is accepted at ANY
+// position, so it is never healed. Fresh objects only — sidecars stay
+// intact for future verbatim emission once re-legitimized.
+function isToolUpdateBlock(b: { type?: unknown }): boolean {
+ return b.type === "tool_addition" || b.type === "tool_removal";
+}
+
+function healIllegalSystemPositions(out: AnthropicWireMessage[]): void {
+ for (let j = 0; j < out.length; j++) {
const e = out[j];
- if (!e || e.role !== "system") break;
- if (isDirectiveOnlySystem(e)) continue;
- out[j] = { ...e, role: "user" };
+ if (!e || e.role !== "system" || isDirectiveOnlySystem(e)) continue;
+ let k = j + 1;
+ while (k < out.length && out[k]!.role === "system") k++;
+ const next = out[k];
+ if (!next || next.role === "assistant") continue;
+ if (typeof e.content === "string") {
+ // An empty string demoted to user would mint an empty-content user
+ // message, which 400s on its own — drop instead.
+ if (e.content === "") {
+ out.splice(j, 1);
+ j--;
+ } else {
+ out[j] = { role: "user", content: e.content };
+ }
+ continue;
+ }
+ const kept = e.content.filter(
+ (b) => !isToolUpdateBlock(b as { type?: unknown }),
+ );
+ if (kept.length === 0) {
+ out.splice(j, 1);
+ j--;
+ continue;
+ }
+ out[j] = { role: "user", content: kept };
}
}
@@ -419,12 +454,9 @@ export function coreToAnthropic(
out.push(rebuildSystemMessage(m, cacheControls?.get(m.id)));
continue;
}
- // #4292: a no-sidecar core system is a kernel-rendered fold anchor; the
- // sidecar systems directly before it (current === null ⇒ the previous
- // core emitted one) are the fold-orphaned run — re-voice it to user.
- if (m.role === "system" && current === null) {
- revoiceFoldOrphanedSystems(out);
- }
+ // #4292/#4457: fold-orphaned and client-illegal system positions are
+ // healed by the position-based backstop after assembly (see below) —
+ // no shape matching here.
const target: "user" | "assistant" =
m.role === "assistant" ? "assistant" : "user";
if (!current || current.role !== target) {
@@ -472,6 +504,7 @@ export function coreToAnthropic(
}
}
flush();
+ healIllegalSystemPositions(out);
return out;
}
diff --git a/kernel/tests/anthropic-system-message-passthrough.test.ts b/kernel/tests/anthropic-system-message-passthrough.test.ts
index 3a3bf7763f..30f6b4ebbf 100644
--- a/kernel/tests/anthropic-system-message-passthrough.test.ts
+++ b/kernel/tests/anthropic-system-message-passthrough.test.ts
@@ -105,7 +105,10 @@ test("one core per system wire message, role system, wireIndex kept", () => {
assert.match(systems[1]!.text as string, /\[tool_addition\]$/);
});
-test("system message between two user turns does not merge them", () => {
+test("system message between two user turns heals to user (#4457)", () => {
+ // [user, system, user] is positionally illegal on the anthropic wire —
+ // the backstop re-voices it (tool blocks stripped per WC-022) instead of
+ // forwarding a request Anthropic guarantees to 400.
const body = {
messages: [
{ role: "user", content: [{ type: "text", text: "a" }] },
@@ -114,7 +117,19 @@ test("system message between two user turns does not merge them", () => {
],
};
const rebuilt = coreToAnthropic(anthropicToCore(body as never).msgs as never);
- assert.deepEqual(rebuilt, body.messages);
+ assert.deepEqual(rebuilt, [
+ { role: "user", content: [{ type: "text", text: "a" }] },
+ {
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: 'Updated system prompt section "tools":\n…',
+ },
+ ],
+ },
+ { role: "user", content: [{ type: "text", text: "b" }] },
+ ]);
});
test("string-content system message round-trips", () => {
diff --git a/kernel/tests/issue4292-orphan-system-guard.test.ts b/kernel/tests/issue4292-orphan-system-guard.test.ts
index 46364e0736..18242a3951 100644
--- a/kernel/tests/issue4292-orphan-system-guard.test.ts
+++ b/kernel/tests/issue4292-orphan-system-guard.test.ts
@@ -7,16 +7,17 @@ import type {
} from "../src/wire/anthropic.js";
import type { BiliMessage } from "../src/wire/bili-message.js";
-// #4292: a fold covers the assistant messages that legitimized a client
-// mid-conversation system message. Because prune inserts each summary at
-// the EARLIEST covered position (kernel/src/prune.ts insertAt), the orphaned
-// sidecar system is always IMMEDIATELY followed by the no-sidecar core
-// system anchor (rendered summary), which emits as user — producing
-// [.., system, user, ..] that Anthropic rejects ("role 'system' must precede
-// an 'assistant' message or end the array"), 400ing the session forever.
-// coreToAnthropic re-voices exactly that adjacency (the fold signature) to
-// user. Everything else emits verbatim: the kernel is transport, not a
-// validator, so positionally-illegal client layouts round-trip byte-exact.
+// #4292/#4457: a fold that covers the assistant messages legitimizing a
+// client mid-conversation system message leaves it in a wire position
+// Anthropic rejects ("role 'system' must precede an 'assistant' message or
+// end the array"), 400ing the session forever. The fold layer keeps these
+// sidecar systems out of folds (their tool deltas are functional — see
+// protected.ts), so orphans still arise; coreToAnthropic therefore ends
+// with a POSITION-based backstop: any non-directive
+// system whose first non-system follower is neither an assistant nor the
+// array end is healed — re-voiced to user with tool_update blocks stripped
+// (WC-022), dropped when nothing remains. Legal layouts (assistant next,
+// array end, trailing runs, directive-only anywhere) round-trip verbatim.
function sys(content: AnthropicSystemMessage["content"]): AnthropicSystemMessage {
return { role: "system", content };
@@ -85,7 +86,7 @@ test("#4292 shape: sidecar system immediately before the anchor is re-voiced", (
});
});
-test("consecutive orphaned systems before the anchor re-voice as a whole run", () => {
+test("consecutive orphaned systems before the anchor heal as a whole run", () => {
const S1 = sys([{ type: "text", text: "first" }]);
const S2 = sys([
{ type: "text", text: "second" },
@@ -102,7 +103,9 @@ test("consecutive orphaned systems before the anchor re-voice as a whole run", (
assert.equal(rebuilt[1]!.role, "user");
assert.deepEqual(rebuilt[1]!.content, S1.content);
assert.equal(rebuilt[2]!.role, "user");
- assert.deepEqual(rebuilt[2]!.content, S2.content);
+ // #4457/WC-022: tool_update blocks never survive a demotion to user —
+ // the text block alone is re-voiced, byte-identical.
+ assert.deepEqual(rebuilt[2]!.content, [{ type: "text", text: "second" }]);
assert.deepEqual(rebuilt[3], {
role: "user",
content: [
@@ -141,13 +144,22 @@ test("Pi shape: system run at array end (no anchor after) round-trips verbatim",
assert.deepEqual(roundTrip({ messages }), messages);
});
-test("sidecar system followed by a plain user message stays verbatim", () => {
+test("sidecar system followed by a plain user message is healed (#4457 shape)", () => {
+ // [user, system, user] is exactly the #4457 wire: Anthropic 400s it
+ // ("system must precede an assistant message or end the array") — the
+ // backstop re-voices it to user instead of forwarding a dead request.
const messages = [
{ role: "user", content: [{ type: "text", text: "a" }] },
sys([{ type: "text", text: "between user turns" }]),
{ role: "user", content: [{ type: "text", text: "b" }] },
] as AnthropicWireMessage[];
- assert.deepEqual(roundTrip({ messages }), messages);
+ const rebuilt = coreToAnthropic(anthropicToCore({ messages } as never).msgs as never);
+ assert.deepEqual(orphans(rebuilt), []);
+ assert.deepEqual(rebuilt, [
+ { role: "user", content: [{ type: "text", text: "a" }] },
+ { role: "user", content: [{ type: "text", text: "between user turns" }] },
+ { role: "user", content: [{ type: "text", text: "b" }] },
+ ]);
});
test("sidecar system immediately followed by an assistant stays verbatim", () => {
@@ -180,17 +192,18 @@ test("directive-only system adjacent to the anchor stays system (legal anywhere)
assert.equal(rebuilt[2]!.role, "user");
});
-test("run separated from a later anchor by a user core stays verbatim", () => {
- // The anchor adjacency must be immediate: a user core between the system
- // and the anchor means the system was NOT orphaned by that fold.
+test("system separated from a later anchor by a user core is healed too", () => {
+ // #4457/S2: the orphaning fold's anchor lands BEFORE the surviving
+ // system — no anchor adjacency exists, only the position rule catches it.
const rebuilt = coreToAnthropic([
{ id: "u0", role: "user", contentType: "text", text: "q1" },
{ id: "s1", role: "system", contentType: "text", text: "mid", rawAnthropicMessage: sys("mid") },
{ id: "u1", role: "user", contentType: "text", text: "gap" },
anchor("a1", "[Compressed conversation section] x"),
] as never);
- assert.equal(rebuilt[1]!.role, "system");
- assert.deepEqual(rebuilt[1], sys("mid"));
+ assert.deepEqual(orphans(rebuilt), []);
+ assert.equal(rebuilt[1]!.role, "user");
+ assert.equal(rebuilt[1]!.content, "mid");
});
test("sidecar system before an assistant and a later anchor stays verbatim", () => {
@@ -242,3 +255,58 @@ test("edge arrays are unaffected: empty, user-only, assistant-only", () => {
[{ role: "assistant", content: [{ type: "text", text: "hey" }] }],
);
});
+
+// --- #4457 backstop edges ---------------------------------------------------
+
+test("#4457: tool-block-only orphaned system is dropped, not re-voiced empty", () => {
+ const S = sys([TOOL_ADDITION]);
+ const rebuilt = coreToAnthropic([
+ { id: "u0", role: "user", contentType: "text", text: "q1" },
+ { id: "s1", role: "system", contentType: "text", text: "[tool_addition]", rawAnthropicMessage: S },
+ { id: "u1", role: "user", contentType: "text", text: "after" },
+ ] as never);
+ assert.deepEqual(orphans(rebuilt), []);
+ // The demotion drops the entry entirely (nothing re-voicable remains);
+ // the neighbouring user turns stay separate entries — the backstop
+ // never merges.
+ assert.deepEqual(rebuilt, [
+ { role: "user", content: [{ type: "text", text: "q1" }] },
+ { role: "user", content: [{ type: "text", text: "after" }] },
+ ]);
+});
+
+test("#4457: string-content orphaned system re-voices with the string intact", () => {
+ const S = sys("policy delta");
+ const rebuilt = coreToAnthropic([
+ { id: "u0", role: "user", contentType: "text", text: "q1" },
+ { id: "s1", role: "system", contentType: "text", text: "policy delta", rawAnthropicMessage: S },
+ { id: "u1", role: "user", contentType: "text", text: "after" },
+ ] as never);
+ assert.deepEqual(rebuilt[1], { role: "user", content: "policy delta" });
+});
+
+test("#4457: consecutive system run is judged by its first non-system follower", () => {
+ // Pi's trailing tool-delta + effort-marker run at array end is LEGAL —
+ // byte-exact verbatim even though the first system's immediate next is
+ // another system, not an assistant.
+ const messages = [
+ { role: "user", content: [{ type: "text", text: "a" }] },
+ sys([{ type: "text", text: "tools" }, TOOL_ADDITION]),
+ sys([{ type: "text", text: "trailing effort" }]),
+ ] as AnthropicWireMessage[];
+ assert.deepEqual(roundTrip({ messages }), messages);
+ // The same run followed by a user turn is illegal as a whole — every
+ // member is healed (tool blocks stripped, text kept).
+ const illegal = [
+ { role: "user", content: [{ type: "text", text: "a" }] },
+ sys([{ type: "text", text: "tools" }, TOOL_ADDITION]),
+ sys([{ type: "text", text: "trailing effort" }]),
+ { role: "user", content: [{ type: "text", text: "b" }] },
+ ] as AnthropicWireMessage[];
+ const rebuilt = coreToAnthropic(anthropicToCore({ messages: illegal } as never).msgs as never);
+ assert.deepEqual(orphans(rebuilt), []);
+ assert.equal(rebuilt[1]!.role, "user");
+ assert.deepEqual(rebuilt[1]!.content, [{ type: "text", text: "tools" }]);
+ assert.equal(rebuilt[2]!.role, "user");
+ assert.deepEqual(rebuilt[2]!.content, [{ type: "text", text: "trailing effort" }]);
+});
diff --git a/kernel/tests/issue4457-sidecar-system-folds.test.ts b/kernel/tests/issue4457-sidecar-system-folds.test.ts
new file mode 100644
index 0000000000..a7501f0bbc
--- /dev/null
+++ b/kernel/tests/issue4457-sidecar-system-folds.test.ts
@@ -0,0 +1,156 @@
+// #4457: control-plane sidecar system cores (rawAnthropicMessage —
+// mid-conversation tool deltas / effort markers) stay OUT of folds: under
+// Anthropic's mid-conversation-tool-changes contract the deltas are
+// FUNCTIONAL — tools[] stays static for cache stability and the offered
+// tool set is controlled by tool_addition/tool_removal (defer_loading
+// surfacing, by-value definitions, removals, MCP toolsets) — so folding one
+// silently alters the effective tool set. The #4292-family bug was NOT the
+// never-fold carve itself but that the carve could ORPHAN these messages:
+// a fold covering the assistant that legitimized one leaves it in a wire
+// position Anthropic rejects ("role 'system' must precede an 'assistant'
+// message or end the array"), 400ing the session forever. This pins both
+// halves of the #4457 fix through the real chain: the protection survives,
+// AND the position-based backstop (wire/anthropic.ts
+// healIllegalSystemPositions) heals the orphan so the session lives.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createCore } from "../src/compress.js";
+import { createInitialState } from "../src/state.js";
+import { assignRefs } from "../src/refs.js";
+import { prune } from "../src/prune.js";
+import { anthropicToCore, coreToAnthropic } from "../src/wire/anthropic.js";
+import { hasUnrecoverableMediaPayload } from "../src/protected.js";
+import { defaultCountTokens } from "../src/tokenize.js";
+import type { Config, CoreMessage } from "../src/types.js";
+
+function config(): Config {
+ return {
+ tiers: { enabled: false },
+ nudge: {
+ maxContextLimitPct: 0.55, minContextLimitPct: 0.45, frequency: 5,
+ iterationThreshold: 15, force: "soft", growthRatio: 0.05,
+ growthFloor: 6000, growthCap: 50000, minGrowthFloor: 5000,
+ minGrowthRatio: 0.45, emergencyThresholdPct: 0.98,
+ },
+ promotionThreshold: 5,
+ truncate: { threshold: 1 },
+ merge: { maxSummaryLength: 3000, minOldGenBlocks: 3 },
+ compress: { minCompressRange: 1000, maxSummaryLength: 20000, minSummaryLength: 1 },
+ protectedTools: [],
+ preserveRecentMessages: 0,
+ preserveRecentTokens: 0,
+ modelContextLimit: 100000,
+ };
+}
+
+const TOOL_DELTA_SYSTEM = {
+ role: "system",
+ content: [
+ {
+ type: "text",
+ text: 'Updated system prompt section "tools":\n…',
+ },
+ { type: "tool_addition", name: "search", input_schema: { type: "object" } },
+ ],
+};
+
+function baseMessages(): CoreMessage[] {
+ return anthropicToCore({
+ messages: [
+ { role: "user", content: [{ type: "text", text: "q1 " + "x".repeat(400) }] },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "a1 " + "y".repeat(4000) }],
+ },
+ TOOL_DELTA_SYSTEM,
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "a2 " + "y".repeat(4000) }],
+ },
+ { role: "user", content: [{ type: "text", text: "q2" }] },
+ ],
+ } as never).msgs;
+}
+
+/** Wire systems violating the Anthropic position rule (run-aware: a run of
+ * consecutive systems is judged by its first non-system follower). */
+function orphanSystems(
+ messages: Array<{ role: string; content: unknown; output_config?: unknown }>,
+): number[] {
+ const bad: number[] = [];
+ for (let j = 0; j < messages.length; j++) {
+ const e = messages[j]!;
+ if (e.role !== "system") continue;
+ const c = e.content;
+ const directiveOnly =
+ (typeof c === "string" ? false : Array.isArray(c) && c.length === 0) &&
+ e.output_config != null;
+ if (directiveOnly) continue;
+ let k = j + 1;
+ while (k < messages.length && messages[k]!.role === "system") k++;
+ const next = messages[k];
+ if (!next || next.role === "assistant") continue;
+ bad.push(j);
+ }
+ return bad;
+}
+
+test("#4457: tool-carrying sidecar system stays never-fold (functional delta)", () => {
+ const msgs = baseMessages();
+ const sys = msgs.find((m) => m.role === "system");
+ assert.ok(sys);
+ assert.ok((sys as { rawAnthropicMessage?: unknown }).rawAnthropicMessage);
+ assert.equal(hasUnrecoverableMediaPayload(sys), true);
+});
+
+test("#4457: fold around the never-fold system applies clean; backstop heals the orphan", () => {
+ const msgs = baseMessages();
+ const state = createInitialState();
+ state.messageRefs = assignRefs(msgs, {
+ existing: state.messageRefs,
+ nextIndex: 1,
+ }).map;
+ const core = createCore({ countTokens: defaultCountTokens });
+ const applied = core.applyCompression({
+ ranges: [
+ {
+ startRef: "m00001",
+ endRef: "m00004",
+ summary: "covered early turns around the tool-delta system",
+ },
+ ],
+ messages: msgs,
+ state,
+ config: config(),
+ });
+ assert.deepEqual(applied.result.errors, []);
+ // the never-fold sidecar is excluded from coverage and reported as such
+ assert.ok(
+ applied.result.warnings.some((w) => w.includes("Excluded")),
+ applied.result.warnings.join(" | "),
+ );
+ const view = prune(msgs, applied.state);
+ // the sidecar SURVIVES the fold (excluded), and the anchor landed BEFORE
+ // it — the exact #4457 field layout that 400ed on v0.1.205
+ const sidecarInView = view.find(
+ (m) => (m as { rawAnthropicMessage?: unknown }).rawAnthropicMessage,
+ );
+ assert.ok(sidecarInView, "the never-fold sidecar must survive the fold");
+ const anchorIdx = view.findIndex((m) => m.id.startsWith("acp_summary_"));
+ assert.ok(anchorIdx >= 0, "the fold anchor must be present");
+ assert.ok(
+ anchorIdx < view.findIndex((m) => m.id === sidecarInView!.id),
+ "anchor lands before the surviving sidecar (#4457 layout)",
+ );
+ const out = coreToAnthropic(view);
+ assert.deepEqual(orphanSystems(out), [], JSON.stringify(out));
+ // the orphan healed to a text-only user entry (tool block stripped)
+ const healed = out.find((m) =>
+ JSON.stringify(m).includes("Updated system prompt section"),
+ );
+ assert.ok(healed, "the healed entry must carry the delta's text");
+ assert.equal(healed!.role, "user");
+ assert.ok(!JSON.stringify(healed).includes("tool_addition"));
+ // the fold summary survives into the emission
+ assert.ok(JSON.stringify(out).includes("covered early turns"));
+});
diff --git a/package-lock.json b/package-lock.json
index 731af8f794..26d2d3372a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -50,7 +50,7 @@
},
"kernel": {
"name": "acp-kernel",
- "version": "0.0.160",
+ "version": "0.0.161",
"dev": true,
"license": "MIT",
"devDependencies": {
diff --git a/tests/issue4292-anthropic-fold-orphan-system.test.ts b/tests/issue4292-anthropic-fold-orphan-system.test.ts
index 73da404d65..67f5497602 100644
--- a/tests/issue4292-anthropic-fold-orphan-system.test.ts
+++ b/tests/issue4292-anthropic-fold-orphan-system.test.ts
@@ -9,15 +9,17 @@ import {
} from "acp-kernel/wire";
import type { BiliMessage } from "acp-kernel/wire";
-// #4292: v0.1.204 (#3991) made client mid-conversation Anthropic
-// `role:"system"` messages re-emit verbatim in place, but a compression fold
-// can cover the assistant messages that legitimized such a message. Because
-// prune inserts the summary at the EARLIEST covered position, the orphaned
-// system is always immediately followed by the anchor (a no-sidecar core
-// system emitting as user) — [.., system, user, ..] makes Anthropic 400 the
-// session permanently (`messages.N: role 'system' must precede an 'assistant'
-// message or end the array`). coreToAnthropic re-voices exactly that fold
-// signature to user; every other client layout stays byte-exact.
+// #4292 → #4457: a compression fold can cover the assistant messages that
+// legitimized a client mid-conversation system. coreToAnthropic ends with a
+// POSITION-based backstop: any non-directive system whose first non-system
+// follower is neither an assistant nor the array end is healed — re-voiced
+// to user with tool_addition/tool_removal blocks stripped (WC-022) and
+// dropped when nothing remains. The fold layer keeps these sidecar systems
+// out of folds (kernel protected.ts never-fold carve — their tool deltas
+// are functional), so folds still orphan them; the backstop also heals
+// sessions folded by older builds and positionally-illegal client input.
+// Legal layouts
+// (assistant next, array end, directive-only anywhere) stay byte-exact.
/** Indices of system entries violating the Anthropic position rule. */
function orphanSystems(messages: AnthropicWireMessage[]): number[] {
@@ -86,19 +88,24 @@ test("pre-fold wire round-trips byte-identical (no fold, no re-voicing)", () =>
assert.deepEqual(orphanSystems(rebuilt), []);
});
-test("without the anchor adjacent, the orphaned system would stay system (documents #4292)", () => {
- // The fold covered a DIFFERENT region: the client system keeps its
- // verbatim system emission even though the assistants around it are gone.
- // That emission is what Anthropic rejects — the kernel only re-voices the
- // anchor-adjacency signature, so this shape is the host's to avoid.
+test("without the anchor adjacent, the orphaned system heals anyway (#4457 backstop)", () => {
+ // The fold covered a DIFFERENT region — no anchor adjacency exists. The
+ // #4457 position-based backstop does not need the fold signature: any
+ // system whose follower is neither an assistant nor the array end is
+ // healed, so this previously-fatal shape survives too.
const cores = postFoldCore().filter((m) => m.id !== "anchor");
const rebuilt = coreToAnthropic(cores as never);
- assert.equal(rebuilt[1]!.role, "system");
- assert.deepEqual(rebuilt[1]!.content, CLIENT_SYSTEM.content);
- assert.deepEqual(orphanSystems(rebuilt), [1]);
+ assert.deepEqual(orphanSystems(rebuilt), []);
+ assert.equal(rebuilt[1]!.role, "user");
+ assert.deepEqual(rebuilt[1]!.content, [
+ {
+ type: "text",
+ text: 'Updated system prompt section "tools":\n…',
+ },
+ ]);
});
-test("post-fold: anchor adjacency re-voices the orphan, bytes preserved", () => {
+test("post-fold: the backstop re-voices the orphan, tool blocks stripped (#4457)", () => {
const cores = postFoldCore();
const rebuilt = coreToAnthropic(cores as never);
assert.deepEqual(
@@ -106,9 +113,15 @@ test("post-fold: anchor adjacency re-voices the orphan, bytes preserved", () =>
[],
"no illegal-position system remains after the fold guard",
);
- // The orphaned system became a user message with byte-identical blocks.
+ // The orphaned system became a user message: text blocks byte-identical,
+ // tool_addition stripped (WC-022 forbids it outside role:system).
assert.equal(rebuilt[1]!.role, "user");
- assert.deepEqual(rebuilt[1]!.content, CLIENT_SYSTEM.content);
+ assert.deepEqual(rebuilt[1]!.content, [
+ {
+ type: "text",
+ text: 'Updated system prompt section "tools":\n…',
+ },
+ ]);
// Anchor + tail keep their user mapping with verbatim text.
assert.deepEqual(rebuilt[2], {
role: "user",
@@ -122,6 +135,11 @@ test("post-fold: anchor adjacency re-voices the orphan, bytes preserved", () =>
(cores[1]!.rawAnthropicMessage as AnthropicSystemMessage).role,
"system",
);
+ assert.equal(
+ (cores[1]!.rawAnthropicMessage as AnthropicSystemMessage).content.length,
+ 2,
+ "the stored sidecar keeps its tool block for decompress",
+ );
});
test("post-fold with a surviving assistant after the anchor stays fully legal", () => {