Skip to content

Commit 6e29fbf

Browse files
committed
fix(markdown-core): move code-region detection to canonical mdast adapter
The old flat scanner in packages/normalization-core/src/code-regions.ts opened an indented code block only when the nearest non-blank predecessor line was itself unindented. That heuristic misfires for valid indented code nested under a CommonMark list container whose content indent is >= 4 columns (nested lists, or a list item whose continuation line is itself indented). A qualified antml:/mm:/ function_calls invoke example placed in such nested code was recognised as prose by the downstream visible-text and persistence scrubbers and silently removed from both delivered replies and persisted assistant history. Route the code-region source through the canonical mdast implementation: - Add packages/markdown-core/src/code-regions.ts, a small adapter over findMarkdownCodeSpans exposing the existing CodeRegion / findCodeRegions / isInsideCode surface via a dedicated @openclaw/markdown-core/code-regions subpath. - Delete the leaf flat scanner from packages/normalization-core and drop its export; a leaf cannot import markdown-core without cycling. - Repoint packages/tool-call-repair/src/payload-strip-invoke.ts and src/shared/text/code-regions.ts to the markdown-core adapter. The link tool-call-repair -> markdown-core -> normalization-core stays acyclic. - Regenerate docs/.generated/plugin-sdk-api-baseline.sha256 via the repo's own generator; the public CodeRegion shape is preserved. Add coverage across the sanitiser boundary: - Positive-preserved: qualified invoke in indented code nested under a >= 4 column list container (real reachable case); a second container variant; single-level list still preserved; blockquote invoke preserved as an invariant lock, with a comment noting the scrubber requires '<' at line start (skipLineIndentation skips only spaces/tabs, not '>'), so any future scrubber change consuming '>' must re-check code detection. - Negative still-scrubbed: plain paragraph + 4-space continuation, tight-list lazy continuation, loose-list non-code continuation. Guard the reasoning-progress streaming hot path with a cheap tag-presence gate in src/channels/progress-draft-status-text.ts so the mdast-backed detector only runs when a reasoning tag is actually present. Micro-bench on a 17KB no-tag sample: normalize 965 ms -> 17 ms, format 1706 ms -> 62 ms, mergeDeltas 44 ms -> 1 ms across 200 iterations.
1 parent 6d6c490 commit 6e29fbf

15 files changed

Lines changed: 226 additions & 187 deletions

File tree

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,8 @@ ff35f9f74d35d37a2eb6126b57f3dc5a4d580b6222fe3a34c9368779ad32eab7 module/state-p
136136
537047854c21ad20ea0572f8019503cbda3bbafece8194a28c30b0639bde2fde module/string-coerce-runtime
137137
1b5b9a4532db991fce807ba736b550de27aa5f9de2e1f508a8f4f09cae76ea29 module/telegram-account
138138
110944726884fca94f38c9c329b5950629438b9a719f4782c4beeade8bd67746 module/temp-path
139-
7a0193007ebda11514f83255fc8584671ce4008303fdc67db7551d260b9abd37 module/text-chunking
140-
72affa6a592e35a1329c2cd577eb0121cdf37d83c2f93bc979c44b6968cb3825 module/text-runtime
139+
04c46d3965a6f5beef681519f73749ccc7a2983542625a1d3e125440adbe3a2c module/text-chunking
140+
a1b337b29651023b3ce17e33d0ebe78ebaf90cd8808884c6ca6bedf56a3f29a5 module/text-runtime
141141
a94c9ff59cc361b04f8731a47d722c4bc88cfabf942221369a8cb67bdcda7249 module/tool-plugin
142142
89846974257b7551d46a514902998d0592fc67b1d8ce036c6514d7b9cd1bc159 module/tool-results
143143
9d6ab352913a573b226e054e1dc8c6d088493aea9954950c65585923b5b6895a module/tool-send

‎packages/markdown-core/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@
1919
"import": "./dist/code-spans.mjs",
2020
"default": "./dist/code-spans.mjs"
2121
},
22+
"./code-regions": {
23+
"types": "./dist/code-regions.d.mts",
24+
"import": "./dist/code-regions.mjs",
25+
"default": "./dist/code-regions.mjs"
26+
},
2227
"./fences": {
2328
"types": "./dist/fences.d.mts",
2429
"import": "./dist/fences.mjs",

packages/normalization-core/src/code-regions.test.ts renamed to packages/markdown-core/src/code-regions.test.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { describe, expect, it } from "vitest";
2-
import { findCodeRegions, type CodeRegion } from "./code-regions.js";
2+
import { findCodeRegions, isInsideCode, type CodeRegion } from "./code-regions.js";
33

44
/** Slices each discovered region out of the source so tests assert exact spans. */
5-
function regionText(text: string, regions: CodeRegion[]): string[] {
5+
function regionText(text: string, regions: readonly CodeRegion[]): string[] {
66
return regions.map((region) => text.slice(region.start, region.end));
77
}
88

@@ -30,8 +30,6 @@ describe("findCodeRegions", () => {
3030
});
3131

3232
it("does not treat a paragraph-continuation indented line as a region", () => {
33-
// A 4-space line directly following prose is a lazy paragraph continuation,
34-
// not an indented code block, so a leaked call there stays scrubbable.
3533
const text = ["paragraph text", " still same paragraph"].join("\n");
3634
expect(findCodeRegions(text)).toEqual([]);
3735
});
@@ -54,9 +52,22 @@ describe("findCodeRegions", () => {
5452
["```html", "<block>", "```"].join("\n"),
5553
" <indented>",
5654
]);
57-
// Regions are non-overlapping and sorted by start.
5855
for (let index = 1; index < regions.length; index += 1) {
5956
expect(regions[index]!.start).toBeGreaterThanOrEqual(regions[index - 1]!.end);
6057
}
6158
});
59+
60+
it("detects indented code nested under a list container", () => {
61+
const text = ["- outer", " - middle", " - inner", "", " literal"].join("\n");
62+
expect(regionText(text, findCodeRegions(text))).toEqual([" literal"]);
63+
});
64+
65+
it("reports whether positions are inside discovered regions", () => {
66+
const text = "plain `code` done";
67+
const regions = findCodeRegions(text);
68+
69+
expect(isInsideCode(text.indexOf("code"), regions)).toBe(true);
70+
expect(isInsideCode(text.indexOf("plain"), regions)).toBe(false);
71+
expect(isInsideCode(regions[0]!.end, regions)).toBe(false);
72+
});
6273
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { findMarkdownCodeSpans } from "./reasoning-tag-parser.js";
2+
3+
export interface CodeRegion {
4+
start: number;
5+
end: number;
6+
}
7+
8+
/** Finds CommonMark/GFM code regions so text sanitizers can avoid examples. */
9+
export function findCodeRegions(text: string): CodeRegion[] {
10+
return findMarkdownCodeSpans(text).map(([start, end]) => ({ start, end }));
11+
}
12+
13+
/** Returns true when a character offset falls inside one of the discovered code regions. */
14+
export function isInsideCode(pos: number, regions: readonly CodeRegion[]): boolean {
15+
let low = 0;
16+
let high = regions.length - 1;
17+
while (low <= high) {
18+
const middle = Math.floor((low + high) / 2);
19+
const region = regions[middle];
20+
if (!region) {
21+
return false;
22+
}
23+
if (pos < region.start) {
24+
high = middle - 1;
25+
} else if (pos >= region.end) {
26+
low = middle + 1;
27+
} else {
28+
return true;
29+
}
30+
}
31+
return false;
32+
}

‎packages/normalization-core/src/code-regions.ts‎

Lines changed: 0 additions & 173 deletions
This file was deleted.

‎packages/normalization-core/src/index.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
export * from "./boolean-coercion.js";
44
export * from "./cjk-chars.js";
5-
export * from "./code-regions.js";
65
export * from "./error-coercion.js";
76
export * from "./expect.js";
87
export * from "./format.js";

‎packages/tool-call-repair/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
".": "./src/index.ts"
88
},
99
"dependencies": {
10+
"@openclaw/markdown-core": "workspace:*",
1011
"@openclaw/normalization-core": "workspace:*"
1112
}
1213
}

‎packages/tool-call-repair/src/payload-strip-invoke.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Tool Call Repair module implements standalone invoke-dialect strip helpers.
2-
import { findCodeRegions, isInsideCode } from "@openclaw/normalization-core";
2+
import { findCodeRegions, isInsideCode } from "@openclaw/markdown-core/code-regions";
33
import {
44
consumeLineBreak,
55
consumeStructuralLineBreakAfterHorizontalWhitespace,

‎packages/tool-call-repair/src/payload.test.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, expect, it } from "vitest";
2+
import { stripToolCallXmlTags } from "../../../src/shared/text/assistant-visible-text.js";
23
import { scanXmlishToolCall } from "./grammar.js";
34
import { scanPlainTextJsonToolCall, stripPlainTextToolCallBlocks } from "./payload.js";
45

@@ -257,19 +258,73 @@ describe("stripPlainTextToolCallBlocks: degraded invoke dialect (#97750)", () =>
257258
.split("\n")
258259
.map((line) => pad + line)
259260
.join("\n");
261+
const expectPreservedByScrubbers = (raw: string) => {
262+
expect(stripPlainTextToolCallBlocks(raw)).toBe(raw);
263+
expect(stripToolCallXmlTags(raw, { stripFunctionCallsXmlPayloads: true })).toBe(raw);
264+
};
265+
const expectScrubbedByScrubbers = (raw: string, expectedPlain: string, expectedXml: string) => {
266+
expect(stripPlainTextToolCallBlocks(raw)).toBe(expectedPlain);
267+
expect(stripToolCallXmlTags(raw, { stripFunctionCallsXmlPayloads: true })).toBe(expectedXml);
268+
};
260269

261270
it("preserves an indented namespaced invoke example after a blank line (#97750)", () => {
262271
// A 4-space indented block after a blank line is a CommonMark indented code
263272
// block, so the qualified invoke example inside it is documentation, not a leak.
264273
const raw = `Here you go.\n\n${indentLines(block("antml:"), " ")}`;
265-
expect(stripPlainTextToolCallBlocks(raw)).toBe(raw);
274+
expectPreservedByScrubbers(raw);
275+
});
276+
277+
it("preserves a namespaced invoke example in indented code under a nested list (#97750)", () => {
278+
const raw = [
279+
"- outer",
280+
" - middle",
281+
" - inner",
282+
"",
283+
indentLines(block("antml:"), " "),
284+
].join("\n");
285+
expectPreservedByScrubbers(raw);
286+
});
287+
288+
it("preserves a function_calls invoke example in indented code under a blockquote list (#97750)", () => {
289+
const raw = [
290+
"> - quoted item",
291+
">",
292+
...indentLines(
293+
`${LT}function_calls>\n${block("mm:")}\n${LT}/function_calls>`,
294+
"> ",
295+
).split("\n"),
296+
].join("\n");
297+
expectPreservedByScrubbers(raw);
298+
});
299+
300+
it("preserves a namespaced invoke example in single-level list indented code (#97750)", () => {
301+
const raw = ["- item", "", indentLines(block("antml:"), " ")].join("\n");
302+
expectPreservedByScrubbers(raw);
303+
});
304+
305+
it("preserves blockquote-prefixed indented code examples (#97750)", () => {
306+
// The plain-text scrubber requires `<` at line start: skipLineIndentation in
307+
// grammar.ts skips only spaces/tabs, not `>`. If a future scrubber starts
308+
// consuming `>`, re-check blockquote code detection before changing this.
309+
const raw = indentLines(block("antml:"), "> ");
310+
expectPreservedByScrubbers(raw);
266311
});
267312

268313
it("scrubs an indented namespaced invoke on a paragraph-continuation line (#97750)", () => {
269314
// A 4-space indented invoke directly under prose is a lazy paragraph
270315
// continuation, not indented code, so a genuine leak there is still removed.
271316
const raw = `Some prose paragraph.\n${indentLines(block("antml:"), " ")}`;
272-
expect(stripPlainTextToolCallBlocks(raw)).toBe("Some prose paragraph.\n");
317+
expectScrubbedByScrubbers(raw, "Some prose paragraph.\n", "Some prose paragraph.\n ");
318+
});
319+
320+
it("scrubs a tight-list namespaced invoke continuation (#97750)", () => {
321+
const raw = ["- item", indentLines(block("antml:"), " ")].join("\n");
322+
expectScrubbedByScrubbers(raw, "- item\n", "- item\n ");
323+
});
324+
325+
it("scrubs a loose-list non-code namespaced invoke continuation (#97750)", () => {
326+
const raw = ["- item", "", indentLines(block("mm:"), " ")].join("\n");
327+
expectScrubbedByScrubbers(raw, "- item\n\n", "- item\n\n ");
273328
});
274329

275330
it("scrubs a fenced namespaced invoke when the predicate never preserves (strict)", () => {

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)