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.218",
"version": "0.0.219",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
13 changes: 13 additions & 0 deletions kernel/src/boundaries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,19 @@ function resolveAnchorIndex(
// hole (pruned or skipped) and must not be read as cross-session.
const highest = highestUsedIndex(state.messageRefs);
if (boundary.numericId > highest) {
// #7821: a START endpoint at exactly highest+1 is the assistant message
// the model is currently writing — it has no ref yet (refs are minted
// on the next request). The generic "stale artifact or typo" message
// sent the model probing for a valid number instead of continuing the
// turn, and each probe re-armed the breaker. A dedicated message tells
// it to continue the turn; the message becomes compressible next call.
if (endpoint === "start" && boundary.numericId === highest + 1) {
throw new BoundaryNotFoundError(
"unknown",
endpoint,
`${label}="${boundary.raw}" is the assistant message you are currently writing — it has no ref yet (refs are minted on the next request). Do not compress it now; continue the turn and it will be compressible on a later call.`,
);
}
// #4521: an endId above the highest allocated ref is the model aiming
// at "the newest tail" without knowing where it ends — the single most
// common compress failure on long sessions (it cannot see refs minted
Expand Down
10 changes: 8 additions & 2 deletions kernel/src/parse-compress-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,6 @@ function parseLineEntry(
): EntryOutcome {
const nl = entry.indexOf("\n");
const head = (nl === -1 ? entry : entry.slice(0, nl)).trim();
const summary = (nl === -1 ? "" : entry.slice(nl + 1)).trim();
const pair = REF_PAIR_IN_LINE.exec(head);
let startRef: string;
let endRef: string;
Expand All @@ -537,13 +536,20 @@ function parseLineEntry(
endRef = startRef;
afterRefs = single.index + single[0].length;
}
// Text after the refs on the header line. In a one-line entry (no newline)
// this IS the summary — the advertised contract ("summary on the same or the
// next line", #7821) requires accepting it; treating it as topic-only
// rejected the one-line form the tool description advertises. In a multi-line
// entry it is the optional topic; the summary is the remaining lines.
const headerText = head.slice(afterRefs).trim();
const summary = nl === -1 ? headerText : entry.slice(nl + 1).trim();
if (summary.length === 0)
// #4521: name the two most common shapes behind this parse error — a
// stray note line about an already-folded range, and a block rewrite
// written as refs — so the model fixes the entry instead of resending it
// verbatim (each resend was a full failed round-trip).
return { reason: "line entry: missing summary after the refs header line (every entry needs refs THEN its summary text on the same or the next line; a note about an already-folded range does not belong in the batch — drop it; to rewrite an existing block use a bN..bM block-id header entry)" };
const explicitTopic = head.slice(afterRefs).trim();
const explicitTopic = nl !== -1 ? headerText : "";
const range: CompressRangeSpec = {
startRef,
endRef,
Expand Down
47 changes: 47 additions & 0 deletions kernel/tests/issue4521-retry-livelock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,53 @@ test("#4521: a range of pure protected tool pairs is the same no-op class", () =
);
});

test("#7821: startId at exactly highest+1 (the in-flight message) gets a dedicated message", () => {
const core = createCore();
const messages = [text("u0", "user"), text("a1", "assistant"), text("a2", "assistant")];
const state = seed(messages);
// highest = m00003 (the last message). highest+1 = m00004 (the in-flight message).
const r = core.applyCompression({
ranges: [{ startRef: "m00004", endRef: "m00004", summary: "in-flight" }],
messages,
state,
config: config(),
});

assert.equal(r.result.blocksCreated, 0);
assert.ok(r.result.errors.length > 0, "the in-flight message cannot be compressed");
// The per-range error (from boundaries.ts) carries the dedicated in-flight
// message. The aggregated error (from compress.ts) is a generic
// "unknown to this session" message that may mention "stale artifact" as
// one possible cause, so we check the per-range portion specifically.
const perRange = r.result.errors.find((e) => e.startsWith("range m00004"));
assert.ok(perRange, `per-range error present (errors: ${JSON.stringify(r.result.errors)})`);
assert.match(perRange!, /assistant message you are currently writing/);
assert.match(perRange!, /no ref yet/);
assert.match(perRange!, /continue the turn/);
// The in-flight message is NOT described as a "stale artifact" in the
// per-range error (it is the current turn's message, not a stale one).
assert.doesNotMatch(perRange!, /stale artifact from an earlier generation/);
});

test("#7821: startId above highest+1 (not the in-flight message) keeps the stale-ref message", () => {
const core = createCore();
const messages = [text("u0", "user"), text("a1", "assistant"), text("a2", "assistant")];
const state = seed(messages);
// highest = m00003. highest+1 = m00004. m00005 is above highest+1.
const r = core.applyCompression({
ranges: [{ startRef: "m00005", endRef: "m00005", summary: "phantom" }],
messages,
state,
config: config(),
});

assert.equal(r.result.blocksCreated, 0);
assert.ok(r.result.errors.length > 0);
assert.match(r.result.errors.join("; "), /stale artifact from an earlier generation/);
// The in-flight message is NOT the cause (m00005 is not highest+1).
assert.doesNotMatch(r.result.errors.join("; "), /assistant message you are currently writing/);
});

test("#4521/#6928: armed-but-silent nudge window no longer emits a status line", () => {
const core = createCore();
const cfg = config();
Expand Down
45 changes: 40 additions & 5 deletions kernel/tests/parse-compress-input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -974,7 +974,10 @@ test("parseCompressArgs keeps a stray refless string invalid after a complete li
});

test("parseCompressArgs still rejects a header-only entry with nothing to adopt (#1001)", () => {
const input = { content: ["m00001\u2013m00002 topic"] };
// #7821: a header-only entry is one with NO text after the refs (a bare
// refs line). A one-line entry with text after the refs is now accepted
// (the text is the summary), so the header-only case is a bare refs line.
const input = { content: ["m00001\u2013m00002"] };
const { ranges, diagnostics } = parseCompressArgs(input);
assert.equal(ranges.length, 0);
assert.equal(diagnostics.kind, "no-valid-ranges");
Expand Down Expand Up @@ -1304,9 +1307,12 @@ test("parseCompressArgs does NOT apply flat single-range when content carries re
assert.equal(ok.ranges.length, 1);
assert.equal(ok.ranges[0]?.startRef, "m00010");
assert.equal(ok.diagnostics.flatSummarySalvage, undefined);
// ...and header-only entries report the missing summary, not a salvage.
// ...and header-only entries (no text after the refs) report the missing
// summary, not a salvage. #7821: a one-line entry WITH text after the refs
// is now accepted (the text is the summary), so the header-only case is a
// bare refs line.
const bad = parseCompressArgs({
content: "m00010–m00020 topic only",
content: "m00010–m00020",
startId: "m00001",
endId: "m00099",
});
Expand All @@ -1323,17 +1329,46 @@ test("parseCompressArgs keeps headerless prose without top-level refs as content
});

test("parseCompressArgs reports header-only line entries as no-valid-ranges with reasons", () => {
// #7821: the second range is a bare refs line (no text after the refs), so
// it is still header-only. A one-line entry WITH text after the refs is now
// accepted (the text is the summary), so the header-only case is a bare
// refs line.
const { diagnostics } = parseCompressArgs({
content: "m00010–m00020 topic one\nsummary ok.\nm00030–m00040 topic two",
content: "m00010–m00020 topic one\nsummary ok.\nm00030–m00040",
});
assert.equal(diagnostics.kind, "ok"); // 1 valid + 1 invalid
assert.equal(diagnostics.invalidItems, 1);
assert.match(diagnostics.invalidReasons?.[0] ?? "", /missing summary/);
const none = parseCompressArgs({ content: "m00010–m00020 topic only" });
// A bare refs line (no text after the refs) is still header-only.
const none = parseCompressArgs({ content: "m00010–m00020" });
assert.equal(none.diagnostics.kind, "no-valid-ranges");
assert.match(none.diagnostics.invalidReasons?.[0] ?? "", /missing summary/);
});

test("line form: one-line entry with text after refs is accepted as summary (#7821)", () => {
const { ranges, diagnostics } = parseCompressArgs({
content: ["m09309–m09309 Final."],
});
assert.equal(diagnostics.kind, "ok");
assert.equal(diagnostics.invalidItems, 0);
assert.equal(ranges.length, 1);
assert.equal(ranges[0]!.startRef, "m09309");
assert.equal(ranges[0]!.endRef, "m09309");
assert.equal(ranges[0]!.summary, "Final.");
});

test("line form: one-line single-ref entry with text after refs is accepted (#7821)", () => {
const { ranges, diagnostics } = parseCompressArgs({
content: ["m09309 Final."],
});
assert.equal(diagnostics.kind, "ok");
assert.equal(diagnostics.invalidItems, 0);
assert.equal(ranges.length, 1);
assert.equal(ranges[0]!.startRef, "m09309");
assert.equal(ranges[0]!.endRef, "m09309");
assert.equal(ranges[0]!.summary, "Final.");
});

// ---------------------------------------------------------------------------
// Refs separator variants: a pair divider outside the recognized dash class
// must never silently narrow the range to its first ref.
Expand Down
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.

29 changes: 20 additions & 9 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,18 +616,29 @@ export function parseCompressInput(input: unknown, callId?: string, options: { q
const normalized = normalizeCompressInput(input);
let parsed = parseCompressArgs(normalized, { callId });
const note = (message: string): void => { if (!options.quiet) loggerLog("warn", message); };
// #3780: retry the double-escaped line form once. Adopt the result only if
// it parses strictly MORE ranges than the undecoded attempt — a no-real-
// newline string always yields zero ranges undecoded, so this can never
// degrade a working parse. #1494 precedent: host-side pre-normalization of
// compress-arg drift before the kernel. The ultimate shared home for this
// decode is the kernel's parseLineEntry (kernel/src/parse-compress-input.ts);
// it stays there pending a kernel change — this salvage covers every lane now.
if (!parsed.diagnostics.ok && parsed.diagnostics.kind !== "ok") {
// #3780: retry the double-escaped line form once. The decode applies to a
// no-real-newline string carrying a literal backslash-n. Pre-#7821 such a
// string ALWAYS yielded zero ranges undecoded (missing summary), so the
// salvage gated on a failed parse and adopted on strictly MORE ranges.
// #7821's one-line acceptance (text after the refs IS the summary) broke
// that invariant: the undecoded double-escaped string now "parses" with
// the literal backslash-n glued into the summary, so the gate must also
// fire on a SUCCESSFUL parse of that shape, and adoption must accept the
// same range count — the decoded parse carries the real header/summary
// split, the undecoded one cannot. #1494 precedent: host-side
// pre-normalization of compress-arg drift before the kernel. The ultimate
// shared home for this decode is the kernel's parseLineEntry
// (kernel/src/parse-compress-input.ts); it stays there pending a kernel
// change — this salvage covers every lane now.
const content0 = isPlainObject(normalized) ? normalized["content"] : undefined;
const doubleEscapedShape = typeof content0 === "string" && !content0.includes("\n") && content0.includes("\\n");
if ((!parsed.diagnostics.ok && parsed.diagnostics.kind !== "ok") || (doubleEscapedShape && parsed.diagnostics.kind === "ok")) {
const decoded = decodeDoubleEscapedContent(normalized);
if (decoded !== undefined) {
const retry = parseCompressArgs(decoded, { callId });
if (retry.ranges.length > parsed.ranges.length) {
const adopt = retry.ranges.length > parsed.ranges.length
|| (doubleEscapedShape && retry.ranges.length === parsed.ranges.length && retry.ranges.length > 0);
if (adopt) {
note(`[acp-compress-input] double-escape salvage: recovered ${retry.ranges.length} range(s) after decoding literal backslash-n separators once (kind was ${parsed.diagnostics.kind}) (#3780)`);
parsed = retry;
}
Expand Down
36 changes: 32 additions & 4 deletions src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,13 @@ function substrateDestructionPauseParagraph(n: number): string {
// parse are never refused here (see applyRanges), so the #2432 substrate
// recovery step — acp_status once, then ONE live range — still goes through
// and can clear the breaker.
function armedRefusalReceipt(n: number, decayMinutes: number): string {
return `[Compression refused: this call carried no usable ranges and the compress circuit breaker is still armed (${n} consecutive failures) — while it stays armed, repeat parse-failure lectures are withheld. Format reminder: 'content' is ONE string holding every range — each block starts with its 'mNNNNN–mNNNNN optional topic' header line followed by its summary markdown, using refs from your visible history. The breaker disarms on one substantial fold (a trivial one that saves almost nothing does not count) or ${decayMinutes} minutes without a failing call. Continue your task without compressing.]`;
function armedRefusalReceipt(n: number, decayMinutes: number, cause?: string): string {
// #7821: the specific cause (invalidReasons[0]) was withheld while armed, so
// the model never saw WHY the call failed and kept retrying the same shape.
// Include the first reason (already truncated to 160 chars by the caller) so
// the model can self-correct even while the breaker is armed.
const causeNote = cause ? ` Last failure: ${cause}.` : "";
return `[Compression refused: this call carried no usable ranges and the compress circuit breaker is still armed (${n} consecutive failures)${causeNote} — while it stays armed, repeat parse-failure lectures are withheld. Format reminder: 'content' is ONE string holding every range — each block starts with its 'mNNNNN–mNNNNN optional topic' header line followed by its summary markdown, using refs from your visible history. The breaker disarms on one substantial fold (a trivial one that saves almost nothing does not count) or ${decayMinutes} minutes without a failing call. Continue your task without compressing.]`;
}

// #5986 review fix: the observed failure mode after a compress rejection is the
Expand Down Expand Up @@ -1349,6 +1354,15 @@ export function applyRanges(parsed: ReturnType<typeof parseCompressInput>, ctx:
? "Do not retry the same corrupt byte string — re-issue the call as one well-formed JSON object."
: "Fix the argument shape against the format below instead of re-issuing the same malformed call.",
);
// #7821: if the breaker is already armed, this is a refusal, not a new
// failure — don't count it toward the streak (it would re-arm the decay
// timer and hide the cause). Return the armed refusal with the specific
// cause instead.
if (trackLoop && compressBreakerArmed(ctx.session)) {
const armedDetail = compressBreakerDetail(ctx.session)!;
ctx.log(`[acp-proxy: parse-failure receipt collapsed to short refusal (breaker already armed, n=${armedDetail.n}, kind=${diagnostics.kind})`);
return compressResult(armedRefusalReceipt(armedDetail.n, armedDetail.decayMinutes, reasons[0]), "refused", 0, `parse:${diagnostics.kind}`);
}
const loopGuard = trackLoop ? noteCompressLoopFailure(ctx, parseKey) : "";
// #4812: enforce the armed breaker on parse-failure receipts — see
// armedRefusalReceipt for the invariants (arm-moment receipt unchanged;
Expand All @@ -1357,7 +1371,7 @@ export function applyRanges(parsed: ReturnType<typeof parseCompressInput>, ctx:
const armedDetail = trackLoop ? compressBreakerDetail(ctx.session) : undefined;
if (armedDetail !== undefined && armedDetail.n > COMPRESS_LOOP_THRESHOLD) {
ctx.log(`[acp-proxy: parse-failure receipt collapsed to short refusal (breaker armed, n=${armedDetail.n}, kind=${diagnostics.kind})`);
return compressResult(armedRefusalReceipt(armedDetail.n, armedDetail.decayMinutes), "refused", 0, `parse:${diagnostics.kind}`);
return compressResult(armedRefusalReceipt(armedDetail.n, armedDetail.decayMinutes, reasons[0]), "refused", 0, `parse:${diagnostics.kind}`);
}
// Repeat-parse-failure collapse: from the 2nd identical parse failure
// on, the full format lecture + eligibility list re-appends ~200 words
Expand Down Expand Up @@ -1713,7 +1727,21 @@ export function applyRanges(parsed: ReturnType<typeof parseCompressInput>, ctx:
const dropped = droppedEntriesNote(diagnostics);
const specKey = normalizedSpecKey(ranges);
const repeatGuard = recordCompressFailure(ctx.session, specKey);
const loopGuard = trackLoop ? noteCompressLoopFailure(ctx, specKey, errs) : "";
// #7821: if the breaker is already armed, this is a refusal, not a
// new failure — don't count it toward the streak (it would re-arm the
// decay timer). Return the full receipt with the pause paragraph
// (same as before) but don't increment n or refresh lastAt, so the
// decay can actually elapse.
let loopGuard: string;
if (trackLoop && compressBreakerArmed(ctx.session)) {
const armedDetail = compressBreakerDetail(ctx.session)!;
const cause = compressFailureCause(errs, ctx.session);
loopGuard = cause.startsWith("substrate-destruction")
? substrateDestructionPauseParagraph(armedDetail.n)
: loopNoisePauseParagraph(armedDetail.n);
} else {
loopGuard = trackLoop ? noteCompressLoopFailure(ctx, specKey, errs) : "";
}
const beyond = beyondFrontierNote(ctx.session.state, ranges);
const clamp = frontierClampNote(ctx.session.state, ranges, beyond);
// #2146: once the breaker arms, the diagnostic hint cluster it used
Expand Down
Loading
Loading