Skip to content
Merged
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
88 changes: 80 additions & 8 deletions src/loop/tag-echo-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,22 @@ const TRUNC_CLOSE = new RegExp("\x3c\\/" + NAME + "(?:\\s[^<>]{0,32})?$");
// ≤32 mirror the §4 close-name class minus non-ASCII breadth (unattested
// without the final >); the $ anchor keeps mid-text occurrences visible.
const TRUNC_REF_CLOSE = new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");

// #2862: a DEAD ref-close unit — a refs run glued to a close-tag head whose
// \x3e never arrives (no terminator within the 32 non-angle window that
// LONE_CLOSE / ORPHAN_REF_CLOSE need, and not at the $ anchor TRUNC_REF_CLOSE
// covers). Same residue family as #2190/#2348: genuine prose never puts
// mNNNNN directly against \x3c/word, so once a tag-echo is attested in the
// same response the ref + unterminated close head are dead markup TOGETHER,
// while the prose after the head is content and survives. The name class is
// the open ASCII set ([a-zA-Z]{0,32}, TRUNC_REF_CLOSE width): #2190's census
// showed the close-name drift set is open (ap/ck/ak/fullwidth …). Two
// lookaheads keep live closes out: a letter means the name is still growing
// (the longer match owns it), and \x3e within the LONE_CLOSE window means the
// close terminates — those belong to the existing close rules. The
// [\w>] lookbehind mirrors ORPHAN_REF_CLOSE: word-adjacent runs (xm01233) and
// runs right after a tag terminator (\x3e, #644) are not this unit.
const DEAD_REF_CLOSE = new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)", "g");
// The wrapped-turn imitation: the model opens a render tag and writes its
// payload where the attributes are still open, so the attribute list runs into
// a `<` instead of ending at its `>`. The recorded shape (architect session
Expand Down Expand Up @@ -429,6 +445,20 @@ export function stripAcpTags(text: string, dropToolCallEmission = false, request
.replace(new RegExp(LONE_OPEN.source, "g"), "")
.replace(new RegExp(MANGLED_OPEN.source, "g"), "")
.replace(new RegExp(LONE_CLOSE.source, "g"), "")
// #2862: dead ref-close units (ref + unterminated close head, mid-text or
// at EOF). Position matters twice: BEFORE the truncate passes — TRUNC_CLOSE
// eats the \x3c/name tail first and would leave the bare ref behind (the
// #2348 v4 shadow) — and AFTER the paired/degen/self/lone-open/lone-close
// passes: their removals ARE the same-text attestation (an unclosed open or
// a degen pair count too, not just an already-stripped span), and stripping
// an open also un-glues a ref that sat right after its \x3e so the [\w>]
// lookbehind admits it. A close-only shape with no other echo evidence
// leaves out === text and stays content-preserved (#1760); such sightings
// remain observable via the residue audits.
if (out !== text) {
out = out.replace(new RegExp(DEAD_REF_CLOSE.source, "g"), "");
}
out = out
.replace(new RegExp(TRUNC_OPEN.source), "")
.replace(new RegExp(TRUNC_CLOSE.source), "")
.replace(new RegExp(TRUNC_REF_CLOSE.source), "")
Expand Down Expand Up @@ -944,6 +974,29 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void, onResidu
}
recordDrop(snippet);
};
/** #2862: strip dead ref-close units (ref + unterminated close head) from
* a span about to be RELEASED as prose; each unit is one self-contained
* artifact. Only when a tag-echo is already attested in this response
* (droppedAny, or forced by the caller when the attesting match wins in
* THIS buffer but has not been recorded yet) — a close-only shape with
* no attested echo stays content-preserved (#1760). The head-boundary
* check mirrors charBeforeRun: a run at the released span's head that
* was preceded by an emitted word char (xm01233 across a chunk boundary)
* or \x3e (#644) is not this unit. */
const stripDeadRefCloses = (s: string, attested = false): string => {
if ((!attested && !droppedAny) || !s.includes("\x3c/")) return s;
const re = new RegExp(DEAD_REF_CLOSE.source, "g");
let out = "";
let last = 0;
let mm: RegExpExecArray | null;
while ((mm = re.exec(s)) !== null) {
if (mm.index === 0 && lastEmitted !== "" && /[\w>]/.test(lastEmitted)) continue;
out += s.slice(last, mm.index);
last = mm.index + mm[0].length;
drop(mm[0]);
}
return out + s.slice(last);
};
/** Character immediately before the refs run of an orphan-unit match —
* within the buffer, or the last emitted char when the run sits at the
* buffer head (chunk boundary). */
Expand Down Expand Up @@ -1056,7 +1109,9 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void, onResidu
if (broken && (m === null || broken.index < m.index)) {
swallowSessionCounted = false;
recordDrop(broken[0]);
out += buf.slice(0, broken.index);
// The broken open is attested (recorded above) — clean any
// settled dead unit out of the prose before it.
out += stripDeadRefCloses(buf.slice(0, broken.index));
buf = buf.slice(broken.index + broken[0].length);
swallowUntilClose = true;
swallowLimit = IMITATION_SWALLOW_CAP;
Expand All @@ -1073,22 +1128,36 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void, onResidu
// is never delayed or lost.
const definite = DEFINITE_TAIL.test(t[0]);
const cap = definite ? TAG_OPEN_CAP : HOLD_LIMIT;
// The settled prefix may already hold a dead unit while
// only the trailing head stays held — clean it on release.
const pre = stripDeadRefCloses(buf.slice(0, buf.length - t[0].length));
if (t[0].length <= cap) {
held = t[0];
out += buf.slice(0, buf.length - t[0].length);
out += pre;
} else if (definite) {
drop(t[0]);
out += buf.slice(0, buf.length - t[0].length);
// The dropped tail IS this response's attestation even
// though its drop was only just recorded — force the
// gate or a settled unit ahead of it leaks raw.
out += stripDeadRefCloses(buf.slice(0, buf.length - t[0].length), true);
} else {
out += buf;
// Same release-as-prose semantics as the short path:
// a settled dead unit dies when an echo is attested.
out += stripDeadRefCloses(buf);
}
} else {
if (onResidueWarn && containsEchoResidue(buf)) onResidueWarn(buf);
out += buf;
// #2862: release as prose, minus any dead ref-close unit
// (an echo is already attested in this response).
const rel = stripDeadRefCloses(buf);
if (onResidueWarn && containsEchoResidue(rel)) onResidueWarn(rel);
out += rel;
}
break;
}
out += buf.slice(0, m.index);
// The winning match itself attests an echo in this response even
// though its drop has not been recorded yet — force the gate for
// the prose released ahead of it.
out += stripDeadRefCloses(buf.slice(0, m.index), true);
buf = buf.slice(m.index + m[0].length);
// A PAIRED match is by definition a complete open+content+close
// span — only a LONE_OPEN leaves the stream mid-tag and needs to
Expand Down Expand Up @@ -1191,7 +1260,10 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void, onResidu
outputChars += r.length;
return r;
}
const rest = swallowed + held;
// #2862: dead ref-close units die before the truncate branches —
// TRUNC_CLOSE would otherwise eat the \x3c/name tail at EOF and
// shadow the unit down to a bare ref (#2348 v4 ordering).
const rest = stripDeadRefCloses(swallowed + held);
const wasSwallowing = swallowUntilClose;
swallowed = "";
held = "";
Expand Down
148 changes: 148 additions & 0 deletions tests/issue2190-degen-close.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,151 @@ test("#2190 round 2 gate: drift-name heads engage the render-tag predicates once
assert.equal(mayStartRenderTag("\x3caccount"), false, "genuine word stays prose");
assert.equal(mayStartRenderTag("\x3cacgroup"), false, "custom tag stays prose");
});

// #2862: the dead ref-close unit — a refs run glued to a close head whose
// terminator (\x3e) never arrives mid-text (all LONE_CLOSE-family matchers
// require it, TRUNC_REF_CLOSE is $-anchored), released as prose with only a
// residue warn. Once an echo is attested in the same response, the unit dies
// whole and the prose after it survives.
const RESIDUE_MID = "done m00491\x3c/acp **resolved** next.";
const RESIDUE_MID_EXPECT = "done **resolved** next.";

test("#2862 streaming: attested pair + mid-text dead ref-close strips the unit, keeps prose", () => {
const whole = `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ${RESIDUE_MID}`;
const out = streamThrough([whole]);
assert.ok(!out.includes("m00491"), "dead ref must not leak");
assert.ok(!out.includes("\x3c/acp"), "dead close head must not leak");
assert.equal(out, ` ${RESIDUE_MID_EXPECT}`, "prose after the unit survives verbatim");
});

test("#2862 streaming: release path (markup after the head) strips the unit mid-stream", () => {
// The \x3cb\x3e after the head defeats every PARTIAL_TAIL hold, so the
// span reaches the plain release branch in one frame.
const whole = `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e done m00491\x3c/acp see \x3cb\x3e bold`;
const out = streamThrough([whole]);
assert.ok(!out.includes("m00491"), "dead ref must not leak");
assert.ok(!out.includes("\x3c/acp"), "dead close head must not leak");
assert.equal(out, " done see \x3cb\x3e bold", "prose and live markup survive");
});

test("#2862 streaming: character-sharded production shape (tokenizer fragments)", () => {
const whole = `\x3cacp tokens="23" type="text"\x3em05712\x3c/acp\x3e ${RESIDUE_MID}`;
const out = streamThrough([...whole]);
assert.equal(out, ` ${RESIDUE_MID_EXPECT}`, "sharded stream reassembles to the cleaned text");
});

test("#2862 streaming: EOF dead unit (TRUNC_CLOSE shadow) dies whole, not as a bare ref", () => {
const whole = `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e tail m01233\x3c/acp`;
const out = streamThrough([whole]);
assert.ok(!out.includes("m01233"), "ref must not survive as bare prose");
assert.ok(!out.includes("\x3c/acp"), "close head must not leak");
assert.equal(out, " tail ", "trailing prose survives");
});

test("#2862 streaming: live orphan close still goes through the close rules, not the dead-unit strip", () => {
const whole = `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ref m01233\x3c/acp x\x3e tail`;
const out = streamThrough([whole]);
// Exact equality: a dead-rule misfire on this LIVE close would strip only
// through the name and leave ` x>` behind — the weak includes/endsWith
// asserts below would have passed that corruption silently.
assert.equal(out, " ref tail", "orphan rule dies the whole unit incl. attrs, prose survives");
});

test("#2862 streaming: no attested echo — close-only shape stays verbatim (#1760 scope)", () => {
const prose = "see m00491\x3c/acp and \x3ci\x3e it";
const out = streamThrough([prose]);
assert.equal(out, prose, "close-only dead shape with no attestation passes byte-identical");
});

test("#2862 streaming: word-adjacent run (xm01233) is not a dead unit", () => {
const whole = `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e xm01233\x3c/acp and \x3ci\x3e ok`;
const out = streamThrough([whole]);
assert.ok(out.includes("xm01233"), "word-adjacent run survives (lookbehind guard)");
assert.ok(out.includes("\x3ci\x3e ok"), "prose survives");
});

test("#2862 stripAcpTags: dead units die whole-text, unattested stays verbatim", () => {
assert.equal(stripAcpTags(`\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ${RESIDUE_MID}`), ` ${RESIDUE_MID_EXPECT}`, "attested: unit dies, prose survives");
assert.equal(stripAcpTags(`\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e tail m01233\x3c/acp`), " tail ", "attested EOF: unit dies whole, not as a bare ref");
const unattested = "see m00491\x3c/acp and \x3ci\x3e it";
assert.equal(stripAcpTags(unattested), unattested, "close-only shape with no attestation stays byte-identical");
});

test("#2862 responses pipe: residue frame after an attested pair never reaches the client", async () => {
const out: string[] = [];
const res = makeRes(out);
const session = makeSession();
const events = [
sse({ type: "response.output_text.delta", item_id: "msg_1", output_index: 0, delta: `\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ` }),
sse({ type: "response.output_text.delta", item_id: "msg_1", output_index: 0, delta: RESIDUE_MID }),
sse({ type: "response.completed", response: { usage: { input_tokens: 7, output_tokens: 3 } } }),
];
await pipePluginResponsesWithStrip(streamOf(events), res, session);
const text = out.join("");
assert.ok(!text.includes("m00491"), "dead ref never reaches the client");
assert.ok(!text.includes("m05712"), "pair ref never reaches the client");
assert.ok(!JSON.stringify(text).includes("\\u003c/acp"), "close head never reaches the client");
assert.ok(text.includes("resolved"), "prose survives");
});

// #2862 review round: attestation evidence the first cut missed. An unclosed
// acplike open and a degen pair are removed LATER in the whole-text chain than
// the original gate sat — so their presence had to count as attestation too,
// and stripping the open also un-glues a ref that sat right after its \x3e
// (the [\w>] lookbehind otherwise admits nothing). Streaming release prefixes
// ahead of a just-won echo match had the same hole, plus one lookahead guard
// that no test could break.

test("#2862 r2 whole-text: unclosed-open attestation strips the dead unit", () => {
const input = `\x3cacp tokens="1" type="text"\x3em00491\x3c/acp **done** rest.`;
assert.equal(stripAcpTags(input), ` **done** rest.`, "open is attestation; un-glued ref dies with its close head");
});

test("#2862 r2 whole-text: degen-pair attestation strips a later dead unit", () => {
const input = `\x3cacp\x3em00491\x3c/err\x3e done m00500\x3c/acp **z**`;
assert.equal(stripAcpTags(input), ` done **z**`, "degen pair is attestation for the later unit");
});

test("#2862 r2 streaming: dead unit before the first echo dies when the echo lands later", () => {
const out = streamThrough([`m00491\x3c/acp `, `\x3cacp tokens="1"\x3em05712\x3c/acp\x3e rest`]);
// The dead unit dies whole; its trailing space and the pair's leading
// space both survive byte-exact.
assert.equal(out, ` rest`, "prefix released ahead of the attesting pair is cleaned, not raw");
});

test("#2862 r2 streaming: settled dead unit in a hold-prefix releases clean", () => {
// First frame attests; second frame settles a dead unit mid-buffer while a
// fresh partial close tail holds — the prefix between them must not leak
// the settled unit verbatim.
const out = streamThrough([
`\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e x`,
` m00491\x3c/acp see \x3cb\x3e bold m00500\x3c/ac`,
]);
assert.equal(out, ` x see \x3cb\x3e bold `, "settled unit dies on prefix release; live markup and prose survive");
});

test("#2862 r2: live NON-acplike close survives the dead-unit rule (liveness lookahead teeth)", () => {
// Only the dead rule can touch this shape (LONE/ORPHAN need the acplike
// name class). A correct liveness lookahead sees the \x3e within 32 chars
// and skips; a broken one would strip through the name and leave ` x>`.
const tail = `ref m01233\x3c/ap x\x3e tail`;
assert.equal(
stripAcpTags(`\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ${tail}`),
` ${tail}`,
"whole-text: live non-acplike close byte-identical",
);
assert.equal(
streamThrough([`\x3cacp tokens="1" type="text"\x3em05712\x3c/acp\x3e ${tail}`]),
` ${tail}`,
"streaming: live non-acplike close byte-identical",
);
});

test("#2862 r3 streaming: over-cap definite tail as first event cleans its released prefix", () => {
// The >TAG_OPEN_CAP unterminated <acp opening is this response's FIRST
// echo event: its drop is recorded only as the settled prefix is being
// released, so the prefix must be cleaned with forced attestation —
// otherwise the dead unit ahead of it leaks verbatim (#2862 shape).
const out = streamThrough([`m00491\x3c/acp prose ` + "\x3cacp " + "x".repeat(4200)]);
assert.equal(out, " prose ", "settled unit dies with the over-cap tail drop; prose survives byte-exact");
});
13 changes: 7 additions & 6 deletions tests/tag-echo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,11 @@ test("stripAcpTags: malformed close (missing >) does not eat following content (
const content = "这是真实的正文内容,不应被过滤器吃掉。".repeat(12);
const malformed = `${LT}acp tokens="245" type="text">m01998${LT}/acp` + content;
const out = stripAcpTags(malformed);
assert.ok(out.includes(content), "real content survives the malformed close (not eaten)");
assert.ok(out.includes("m01998"), "the ref is preserved");
assert.notEqual(out, "m01998", "not stripped to the bare ref");
// #2862 behavior change (was: ref+close survived as visible residue):
// the attested echo makes the ref glued to the unterminated close head a
// dead unit - it dies whole. The original #644 guarantee (real content
// is never eaten) is unchanged.
assert.equal(out, content, "dead unit dies whole; real content survives byte-exact");
});

test("streaming filter matches stripAcpTags for a malformed close at every split position (#644)", () => {
Expand Down Expand Up @@ -147,9 +149,8 @@ test("stripAcpTags: malformed close with trailing space does not eat following c
const content = "这是真实的正文内容,不应被过滤器吃掉。".repeat(12);
const malformed = `${LT}acp tokens="245" type="text">m01998${LT}/acp ` + content;
const out = stripAcpTags(malformed);
assert.ok(out.includes(content), "real content survives the malformed close (not eaten)");
assert.ok(out.includes("m01998"), "the ref is preserved");
assert.notEqual(out, "m01998", "not stripped to the bare ref");
// Same #2862 evolution as the no-whitespace variant above.
assert.equal(out, " " + content, "dead unit dies whole; real content survives byte-exact");
});

test("streaming filter matches stripAcpTags for the incident-shape malformed close at every split position (#644)", () => {
Expand Down
Loading