Skip to content

Fix false strikethrough from stray ~ by upgrading marked (GitHub GFM parity) - #578

Merged
m-aebrer merged 6 commits into
masterfrom
feature/issue-576-strikethrough-gfm-parity
Nov 13, 2026
Merged

m-aebrer merged 6 commits into
masterfrom
feature/issue-576-strikethrough-gfm-parity

Conversation

@m-aebrer

Copy link
Copy Markdown
Collaborator

Closes #576

Fix false strikethrough from stray ~ (e.g. ~7 percent vs ~12 percent) and match GitHub GFM strikethrough rules on every dreb markdown surface. The plan is to upgrade marked from v15 to ^18.2.0 in tui, coding-agent and dashboard. Upstream fixed the strikethrough flanking rules in 17.0.2. The plan also replaces the vendored v15.0.4 copy used by the HTML session export, and adds regression tests for each surface.

Implementation plan posted as a comment below.

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Implementation Plan

Problem analysis

All three dreb markdown surfaces use marked v15. The TUI and the dashboard use marked@15.0.12 from npm. The HTML export uses a separate vendored marked v15.0.4 (export-html/vendor/marked.min.js). The v15 single-tilde del rule (/^(~~?)(?=[^\s~])(…)\1(?=[^~]|$)/) ignores GFM flanking rules. Its inline lexer also tries del before it finds the closing backtick of a code span, so a ~ inside backticks can close a strikethrough. Upstream fixed this in marked 17.0.2 ("fix strikethrough flanking rules", upstream issue 3882). The current latest release is 18.2.0.

I checked this with throwaway probes in /tmp and changed no repo files:

  • Strikethrough parity: marked 18.2.0 parseInline matches the issue's GitHub column on every row. The reported example and (see `~`) render with no <del> and keep <code>~</code> intact. (~7 percent) vs (~12 percent) stays literal. 5~7 and 10~12, ~~real strike~~ and ~single strike~, word ~~real strike~~ here and a ~single~ b still strike.
  • TUI with marked 18.2.0: I copied packages/tui, swapped in marked 18.2.0, and ran it. The full node --test suite passes (653/653) and tsgo --noEmit is clean. A 20-sample render corpus (lists, loose/task/nested lists, tables, code, blockquotes, headings, hr, trailing blanks) produced the same output under 15.0.12 and 18.2.0, with two exceptions: the strikethrough fix, and one new blank line after an HTML block that is followed by a blank line. That second change comes from v18 trimming trailing blank lines from block tokens, so the blank line now arrives as its own space token. It matches how every other block type is spaced.
  • Task lists (v17 checkbox token): In tight task lists, the new top-level checkbox token falls through renderListItem's inline fallback and renders as nothing. TUI output is therefore unchanged: task markers were already dropped and still are. That behaviour is out of scope.
  • Dashboard with marked 18.2.0: I copied the dashboard and ran its suite. Exactly one marked-related failure appeared: screens.test.tsx › "transcript renders thinking markdown and hides HTML-comment separators". In v15 the HTML-comment block kept its trailing \n\n. Once DOMPurify stripped the comment, that left </p>\n\n\n<p> in .thinking-body, which is white-space: pre-wrap, so extra blank lines showed. In v18 the output is </p>\n<p>, the same as a plain paragraph break with no separator. This is a whitespace-only improvement. The test pins the old inter-block newline count and needs updating (see Testing). All other failures in the copied environment came from files the probe didn't copy (READMEs, docs, fonts), not from marked.
  • HTML export with marked 18 lib/marked.umd.js: It runs with the template's exact marked.use({ breaks, gfm, renderer: { code, text, codespan } }) config. It exposes the same browser global API (marked.use, marked.parse). On the sample corpus it matches v15.0.4 except for three things: the strikethrough fix, harmless whitespace around HTML blocks, and loose task lists. Under the vendored v15.0.4 with the template's text renderer override, loose task lists were emitting an escaped &lt;input … type="checkbox"&gt;. In v18 they render a real checkbox.
  • Packaging: marked 16+ is ESM-only (no require condition) and needs Node ≥20. All three consumers use ESM import, nothing calls require("marked"), and the repo pins Node 26. marked has no dependencies and no install scripts, so allowScripts needs no change. Only the three dreb workspaces depend on marked, so the lockfile will keep one hoisted copy.

The fix is to upgrade marked to ^18.2.0 everywhere and re-vendor the export copy. That needs no custom tokenizer. A del tokenizer override on v15 would be more code to maintain and would still have to re-implement code-span precedence. GitHub (cmark-gfm) and marked ≥17.0.2 now agree on these cases, so following upstream gives parity for free.

Deliverables

  1. Dependency upgrade: marked changes from ^15.0.12 to ^18.2.0 in packages/tui, packages/coding-agent and packages/dashboard. package-lock.json is regenerated with the pinned npm and still resolves one hoisted node_modules/marked at 18.2.0.
  2. Re-vendored export copy: delete export-html/vendor/marked.min.js (v15.0.4). Add export-html/vendor/marked.umd.js, copied verbatim from node_modules/marked/lib/marked.umd.js (the file marked ≥16 tells you to use in place of marked.min.js; it is already minified). Point export-html/index.ts at the new filename. The copy-assets and copy-binary-assets scripts glob vendor/*.js, so they keep working without changes.
  3. Drift guard: a test that fails loudly if the vendored export bundle differs from the installed marked package's lib/marked.umd.js, with remediation in the failure message (the cp command). This prevents a repeat of today's split, where the export used 15.0.4 while everything else used 15.0.12.
  4. Regression tests on every fixed surface (TUI, dashboard, HTML export, plus the coding-agent buddy speech bubble, which also lexes with marked). They cover the reported example and every row of the issue table.
  5. Dashboard README screenshots: after the build, regenerate them with npm run screenshots -w @dreb/dashboard. Commit them only if they change. Expected: byte-identical, because no fixture contains ~ patterns, HTML blocks in thinking, or loose task lists.

Acceptance criteria

  • On the TUI Markdown component, the dashboard (MarkdownBody / transcript, including thinking blocks), and the HTML session export, every input in the issue table renders the way the GitHub column says.
  • The reported example renders with no strikethrough on every surface: Starting from the first ~ in "~7 percent vs ~12 percent", the 7 passes the lookahead, but the next `~` sits after a space, so nothing ends a valid match there.
  • Code spans win: a ~ inside backticks is never used as a strikethrough delimiter, and the code span renders intact (TUI: theme.code("~"); HTML: <code>~</code>).
  • Intentional strikethrough keeps working on every surface: ~~text~~, ~text~, word ~~text~~ here, and intra-word 5~7 and 10~12.
  • The HTML export inlines the vendored marked 18.x bundle byte-for-byte, and that bundle is identical to the installed marked/lib/marked.umd.js. A test enforces both.
  • package.json files declare marked ^18.2.0. npm ls --all passes. npm install --package-lock-only is a byte-for-byte no-op. npm run build leaves package-lock.json untouched.
  • npm run check and npm test pass for all packages, including the existing TUI list/table/spacing tests and the updated dashboard thinking-separator test.
  • README screenshots are regenerated, and committed if anything changed.

Files to create or modify

File Change
packages/tui/package.json marked → ^18.2.0
packages/coding-agent/package.json marked → ^18.2.0
packages/dashboard/package.json marked → ^18.2.0 (devDependency, bundled by Vite)
package-lock.json Regenerated by the pinned npm (Node 26 / npm 11); single hoisted marked 18.2.0
packages/coding-agent/src/core/export-html/vendor/marked.min.js Delete (v15.0.4)
packages/coding-agent/src/core/export-html/vendor/marked.umd.js New, verbatim copy of node_modules/marked/lib/marked.umd.js (v18.2.0)
packages/coding-agent/src/core/export-html/index.ts Read vendor/marked.umd.js instead of vendor/marked.min.js
packages/tui/test/markdown.test.ts New Strikethrough describe block; HTML-block spacing test
packages/dashboard/test/client/markdown-strikethrough.test.tsx (new, jsdom docblock) or a new describe in screens.test.tsx MarkdownBody table cases and a Transcript thinking-block case for the reported example
packages/dashboard/test/client/screens.test.tsx Update "transcript renders thinking markdown and hides HTML-comment separators" (see Testing)
packages/coding-agent/test/export-html-markdown.test.ts (new) Export strikethrough regression, vendored-bundle drift guard, verbatim-inlining check
packages/coding-agent/test/export-html-images.test.ts Only if the template harness is factored into a shared helper (preferred over duplicating it)
packages/coding-agent/test/buddy-component.test.ts Tilde/code-span regression for speech-bubble inline markdown
packages/dashboard/docs/screenshots/* Regenerated; committed only if changed

No code changes are needed in packages/tui/src/components/markdown.ts, transcript.tsx, buddy-component.ts or template.js. The upgrade alone fixes the behaviour, and the probes found no breaking API impact. If the implementation turns up a real incompatibility, fix it in that renderer and add a test.

No user-facing docs change. No README or docs page mentions marked's version or strikethrough semantics. The TUI README's strikethrough theme hook is unchanged.

Testing approach

TUI (packages/tui/test/markdown.test.ts, node:test, defaultMarkdownTheme with chalk level 3):

  • New describe("Strikethrough"). One case for each row of the issue table plus a ~single~ b. Render at a width wide enough to avoid wrapping (or join the lines), then assert:
    • Non-strike rows (reported example, (see `~`), (~7 percent) vs (~12 percent)): the output has no strikethrough SGR (\x1b[9m). The literal ~7 / ~12 survive in the ANSI-stripped text. Where there is a code span, ~ appears styled by theme.code (yellow), and no bare backticks remain in the plain text.
    • Strike rows: the exact expected spans are wrapped in strikethrough (7 and 10, real strike, single strike). A custom marker theme such as strikethrough: t => "<del>" + t + "</del>" can make these assertions exact, if that is clearer than matching SGR codes.
  • HTML-block spacing: <div>hi</div>\n\ntext renders as ["<div>hi</div>", "", "text"]. This pins the v18 spacing change, which is now consistent with the existing "Spacing after …" tests.
  • The existing nested list, ordered list, table, code-block-in-list and spacing tests must stay green unchanged. They exercise the v17 list-token and v18 trailing-blank changes.

Dashboard (vitest + jsdom, the mount() pattern from screens.test.tsx):

  • Mount MarkdownBody with each table row. Assert no del element for the non-strike rows. Assert that code has textContent === "~", that the paragraph text still contains ~7 percent and ~12 percent, and that no stray backtick characters remain. For the strike rows, assert del elements with the expected textContent values (7 and 10, real strike, single strike).
  • Mount Transcript with an assistant entry whose thinking block holds the reported example. This is the surface where the bug was reported. Assert the same things inside .thinking-body.
  • Update the separator test: keep the checks that the comment is not visible and that strong is "Before". Replace the inter-block newline-count assertion. The new check is that the comment-separated thinking renders as two paragraphs (Before, after), the same as the same text without the separator. That is the intended behaviour (the separator is hidden and adds no extra gap), and the test no longer depends on how marked serialises newlines.

HTML export (vitest, packages/coding-agent/test/export-html-markdown.test.ts):

  • Real pipeline: export a session file through exportFromFile. Take the inlined marked script from the generated HTML (the block after <!-- Vendored libraries -->) and run it in a node:vm context with no module/exports, as a browser would, to get the marked global. Run the real template.js with the existing DOM/hljs stubs, so the template's own marked.use({ breaks, gfm, renderer }) config takes effect. Two ways to do this: (a) generalise the existing loadTemplateInternals harness so it can return internals after the safeMarkedParse definition (the only top-level statements between the current marker and marked.use are computeStats(entries) and new Map(), which touch no DOM), or (b) call the real config another way that runs the shipped template code. Prefer sharing the harness with export-html-images.test.ts over duplicating it.
  • Render assistant-text, thinking and summary entries through the real renderEntry. For the reported example and the non-strike rows, assert no <del> and the presence of <code>~</code>. For the strike rows, assert <del> around the expected text.
  • Drift guard: the vendored vendor/marked.umd.js must equal the installed marked package's lib/marked.umd.js, resolved through createRequire(...).resolve("marked/package.json") (allowed by marked's exports map). The comparison is byte-for-byte, and the failure message must say how to re-vendor.
  • Verbatim inlining: the exported HTML contains the vendored marked bundle unmodified (see the $ note under Risks).

Buddy speech bubble (packages/coding-agent/test/buddy-component.test.ts, existing mocked theme where code produces `x`):

  • showSpeech("about ~7 percent vs ~12 percent (see `~`)") renders ~7 percent vs ~12 percent with both tildes kept, and the code span renders via theme.code. Under v15 the bubble rendered about 7 percent vs ~12 percent (see ``). The bubble falls back to token.text for del tokens, so the tilde that opened the false strikethrough was dropped and the code span was broken.

Repository checks: npm run build, npm run check, npm test, npm run verify-workspace-links, npm ls --all, the --package-lock-only no-op check, and the dashboard screenshot regeneration. Last, a manual check with the built dreb binary: render the reported text in the TUI and in an /export HTML file.

Risks and open questions

  • v17 list tokenizer changes (checkbox token, loose-list paragraph tokens, consecutive text tokens). The TUI test copy and the corpus diff found no regressions, and the existing list tests guard this area. Task-list checkboxes are still not shown in the TUI. That is existing behaviour, which this PR leaves unchanged.
  • v18 trailing-blank trimming. Visible effects are an extra blank line after HTML blocks in the TUI (consistent with other blocks) and fewer stray blank lines around HTML-comment separators in dashboard thinking. Both are improvements, and both get tests. Tables, headings, code, hr and blockquotes rendered the same in the corpus.
  • Export bundle size and source map. lib/marked.umd.js is about 51 KB, against 39 KB for the old marked.min.js, so each export file grows by roughly 12 KB. It ends with a //# sourceMappingURL=marked.umd.js.map comment, which in an inline script only affects devtools. The file is vendored verbatim so the drift guard can compare it byte-for-byte.
  • TypeScript 6 types in marked 18. In the TUI copy, tsgo --noEmit passed with marked 18.2.0. The dashboard (marked.parse(text, { async: false }) as string) and buddy (any tokens) use minimal type surface. The full npm run check confirms this.
  • Lockfile discipline. Only the pinned npm may write package-lock.json. There is no overrides entry for marked, so a normal workspace install re-resolves it.
  • Discovery, out of scope, recorded neutrally: export-html/index.ts inlines the vendor scripts with String.prototype.replace(placeholder, string), which interprets $ patterns in the replacement text. The new marked 18.2.0 bundle contains only $1, which is inert there, so this PR is not affected, and the verbatim-inlining test will catch it if a future marked bundle is. The vendored highlight.min.js does contain a $&, which is currently substituted during export, so one highlight.js grammar regex is altered in exported HTML. That is separate from strikethrough. It could be its own issue if wanted.

Plan created by mach6

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Vitest coverage

Metric Covered Total Coverage
Statements 40615 60024 67.66%
Branches 22831 37830 60.35%
Functions 9022 12915 69.85%
Lines 29220 43472 67.21%

View full coverage run

marked v15's single-tilde strikethrough ignored GFM flanking rules and
could close on a `~` inside a code span, so "~7 percent vs ~12 percent"
rendered as strikethrough. Upgrade marked to ^18.2.0 (flanking fix landed
in 17.0.2) in tui, coding-agent and dashboard, and replace the HTML
export's vendored marked v15.0.4 with a verbatim copy of marked 18.2.0's
lib/marked.umd.js.

Add regression tests on every markdown surface (TUI, dashboard transcript,
HTML export, buddy speech bubble), a drift guard that pins the vendored
export bundle to the installed marked package, and share the export
template harness between the image and markdown tests.
@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

The full plan is implemented. Every markdown surface now follows GitHub's GFM strikethrough rules.

Changes

  • Dependency upgrade: marked changes from ^15.0.12 to ^18.2.0 in packages/tui, packages/coding-agent and packages/dashboard. The lockfile change is small: one hoisted marked 18.2.0.
  • HTML export: the vendored vendor/marked.min.js (v15.0.4) is replaced by vendor/marked.umd.js, a verbatim copy of marked 18.2.0's lib/marked.umd.js. export-html/index.ts now reads the new file. A .gitattributes -text entry keeps git from normalising its line endings, so it stays byte-identical to the npm copy.
  • No renderer code changes were needed. The TUI Markdown, the dashboard transcript.tsx, buddy-component.ts and template.js are untouched.

Tests

Each new strikethrough regression test was checked against marked v15 (or the old vendored v15.0.4 bundle): it fails there and passes on v18. The buddy test is the exception; its v15 failure was confirmed by simulating its token handling against v15, not by running it.

  • TUI (packages/tui/test/markdown.test.ts): a table-driven "Strikethrough (GitHub GFM parity)" block covering every row of the issue table plus a ~single~ b. It uses a marker theme for exact boundaries and adds real-theme checks for the strikethrough escape code. There is also a new "Spacing after HTML blocks" test for the v18 trailing-blank change.

  • Dashboard: a new test/client/markdown-strikethrough.test.tsx covers MarkdownBody for every table row, and Transcript for the reported example in both thinking and assistant text. In screens.test.tsx, the HTML-comment separator test now checks that separator-split thinking renders as two paragraphs, identical to the same text with no separator. It no longer pins marked's newline output.

  • HTML export: a new test/export-html-markdown.test.ts takes the marked bundle out of a real exported file and runs it the way a browser would. It then renders through the real template renderEntry() after the template's own marked.use(...) config has run. It covers user, assistant, thinking, branch-summary and custom-message surfaces, and every table row. Two further checks:

    • the exported HTML contains the vendored bundle unchanged;
    • a drift guard compares the vendored bundle byte-for-byte with the installed marked/lib/marked.umd.js, and its failure message gives the re-vendor cp command.

    The template harness moved into a shared test/export-html-template-harness.ts, which the image tests now use too. It can optionally run the real marked config.

  • Buddy speech bubble (buddy-component.test.ts): ~ characters and the code span now survive. v15 used to drop the opening ~ and break the code span.

Verification

  • npm run build, npm run check and the full npm test all pass; the pre-commit hook run reported 7421 passed. npm run build leaves package-lock.json untouched.
  • npm ls --all passes, npm install --package-lock-only changes nothing, and verify-workspace-links is OK.
  • The dashboard README screenshots regenerated byte-identical, so nothing needed committing.
  • Manual: an --export made with the built CLI and loaded in headless Chromium inlines marked v18.2.0. It shows no false strikethrough, keeps <code>~</code> intact, still strikes 7 and 10, real strike and single strike, and logs no page errors. The built TUI Markdown renders the reported example correctly.

Commit: b0fcd5b


Progress tracked by mach6

@m-aebrer
m-aebrer marked this pull request as ready for review November 12, 2026 21:33
@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Unverified Review Candidates — Pending Assessment

Review round: 1
Reviewed commit: b0fcd5b

These are unverified candidates. Severity reflects reviewer confidence; do not treat any item as a merge blocker until the assessment comment is posted.

Critical

Finding 1 — Numeric character references now become raw terminal control characters in the TUI and the buddy bubble (code-reviewer 100, error-auditor 88)

  • packages/tui/src/components/markdown.ts (renderInlineTokens text/default branches ~497–566, renderListItem text branch ~641–647); packages/coding-agent/src/modes/interactive/components/buddy-component.ts (text token handling ~388–404). The cause is the upgrade itself (marked ^18.2.0 in packages/tui/package.json).
  • Since marked 18.0.14 the lexer decodes &#NNN; / &#xHH; inside text tokens. The unchanged TUI renderer writes token.text straight to the terminal. Probes with the real Markdown component:
    • v15: "before &#27;[2J after" → before &#27;[2J after (literal)
    • v18: "before &#27;[2J after" → before \u001b[2J after (clears the screen in headless xterm)
    • v18: "osc &#27;]52;c;aGVsbG8=&#7; end" → osc \u001b]52;c;aGVsbG8=\u0007 end (OSC 52 clipboard write; wrapTextWithAnsi passes it through as zero-width)
    • v18: cr&#13;cr → raw CR; tab&#9;tab → raw TAB; &#155; → C1 CSI. The same decoding applies in headings, list items, table cells, link text and bold/italic.
  • Raw ESC bytes in model text were already unfiltered before this PR. What is new is a plain-ASCII route: quoted web content, or a prompt-injected instruction to repeat a string, now reaches the terminal as control sequences. Code spans are not decoded.
  • Suggested fix: strip C0 (except \n), DEL, C1 and bidi override characters from lexer-decoded text before styling, in the TUI Markdown and buddy paths, and add regression tests. Pinning to >=17.0.2 <18.0.14 would also avoid it, as a stopgap.

Important

Finding 2 — A bare & renders as literal &amp; in the TUI, the buddy bubble and the HTML export when its text run contains a numeric reference (error-auditor 95)

  • Same files as finding 1, plus packages/coding-agent/src/core/export-html/template.js (text(token) override ~1523–1525).
  • Since marked 18.1.1 the lexer HTML-encodes a bare & in any text run that also contains a numeric reference, and returns escaped: false.
    • TUI v15: "Q&A &#8212; R&D" → Q&A &#8212; R&D
    • TUI v18: "Q&A &#8212; R&D" → Q&amp;A — R&amp;D. Also "it&#39;s fine & dandy" → it's fine &amp; dandy, and "Tom &#38; Jerry" → Tom &amp; Jerry.
    • Export v18: <p>Q&amp;amp;A — R&amp;amp;D</p> (the browser shows Q&amp;A — R&amp;D). The text override escapes the text a second time.
    • The dashboard is unaffected; it displays Q&A — R&D.
  • Suggested fix: decode marked's entity output in the TUI and buddy text paths before styling. In the export, stop double-escaping, either by dropping the text override or by not re-escaping text that marked has already encoded. Add regression cases.

Finding 3 — Indented code blocks gain a spurious trailing blank row in the TUI (code-reviewer 100)

  • packages/tui/src/components/markdown.ts (block code case ~351–365 and the renderListItem code branch ~652–670).
  • marked 18 keeps the terminating newline in indented code's token.text, and split("\n") (or the highlighter) turns it into an extra row.
    • " code\n" → v15 ["```", " code", "```"]
    • " code\n" → v18 ["```", " code", "", "```"]
  • Fenced blocks are unaffected. The same thing happens for indented code inside list items.

Finding 4 — Link reference definitions now add visible blank rows in the TUI (code-reviewer 100)

  • packages/tui/src/components/markdown.ts (space case ~471–481).
  • marked 18 separates the blank lines around a def token into space tokens. The renderer ignores the def but renders each space.
    • "[ref]: /url\n\n[ref]" → v15 ["ref (/url)"], v18 ["", "ref (/url)"]
    • "before\n\n[ref]: /url\n\nafter" → v15 ["before", "", "after"], v18 ["before", "", "", "after"]

Finding 5 — TUI list tests never exercise the marked 17 loose-list and task-list token shapes (test-reviewer 82)

  • packages/tui/src/components/markdown.ts:632–686 (renderListItem); tests in packages/tui/test/markdown.test.ts.
  • With renderListItem instrumented, the whole markdown suite only ever passes it text and list item tokens. Two token shapes are never reached:
    • the v17 checkbox token, which renders as nothing only because of the unknown-token fallback;
    • loose-list paragraph tokens.
  • Mutation check: making the paragraph branch swallow its content still passes all 663 TUI tests, even though loose lists then render as empty bullets.
  • Suggested tests:
    • - [ ] todo\n- [x] done → ["- todo", "- done"]
    • - a\n\n- b → ["- a", "- b"]
    • - a\n\n more\n\n- b
    • - [ ] a\n\n- [x] b

Suggestions

Finding 6 — The shared harness exposes renderImageTag, which no test uses (simplifier 88)

  • packages/coding-agent/test/export-html-template-harness.ts (interface and injected return). This dead member was carried over from the old inline harness.

Finding 7 — The export markdown test couples its case tables by array index (simplifier 83)

  • packages/coding-agent/test/export-html-markdown.test.ts: SURFACES[0], SURFACES[1], CASES[0], CASES[4] and a repeated "~~real strike~~ and ~single strike~" literal. Named constants or builders would make the intent explicit.

Finding 8 — The assistant-text surface is tested twice, and two assertions are implied by the exact match (simplifier 85)

  • packages/coding-agent/test/export-html-markdown.test.ts:157–174.
    • The per-surface loop repeats the assistant-text cases that the CASES loop already covers.
    • not.toContain("<del>") and toContain("<code>~</code>") are implied by the toBe(CASES[0].html) that follows them.

Finding 9 — Pre-existing, not introduced by this PR: $ patterns in the export's String.replace inlining

  • packages/coding-agent/src/core/export-html/index.ts:165–175 uses string replacements, so $$ and $& patterns in the inlined text are interpreted:
    • template.js:1348 $${totalCost…} loses its $ in the exported Cost display.
    • highlight.min.js's $& alters one grammar regex (already noted in the plan).
  • The new marked bundle contains only $1 and is unaffected; the verbatim-inlining test guards it.

Finding 10 — Pre-existing, not introduced by this PR: copy-binary-assets does not copy template.css or template.js

  • packages/coding-agent/package.json copy-binary-assets copies only template.html and vendor/*.js into dist/export-html/. HTML export from the bun binary would plausibly fail with ENOENT. This was found by reading the script; no binary build was run.

Strengths

  • The strikethrough fix works through every real renderer. Every issue-table row matches GitHub's actual GFM API output; the completeness checker POSTed all seven rows to api.github.com/markdown.
  • Regression tests fail on a revert to marked 15 on every surface (TUI 5, dashboard 6, export 9, buddy 1), and pass on 18.2.0.
  • The export test runs the real inlined bundle in a vm context and the real template.js marked.use(...) config. The harness markers fail loudly if they are missing or duplicated.
  • The byte-for-byte drift guard gives a clear cp remediation. The .gitattributes -text entry keeps it robust against EOL normalization.
  • Lockfile discipline holds: a single hoisted 18.2.0, npm ls --all passes, the lock-only install is a no-op, and the build leaves the lockfile untouched. No stale marked.min.js references are tracked, and both copy globs ship marked.umd.js.
  • The export gains real fixes beyond strikethrough. Loose lists no longer double-escape bold text or emit an escaped <input>. v18 is also far faster on pathological emphasis input (25.9 s → 15 ms on a *b × 20k).

Agents run: code-reviewer, error-auditor, test-reviewer, completeness-checker (no gaps found), simplifier


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Findings: #578 (comment)

Round 1: independent-assessor, with parent adjudication. Every factual claim below was re-checked with probes that run the real TUI Markdown component on marked 15.0.12 and on 18.2.0. The export claims were checked with the real vendored bundle and the template.js config.

Mechanism behind findings 1 and 2: marked 18's inline text tokenizer changed in two steps:

  • From 18.0.14 it decodes numeric character references (&#NNN;, &#xHH;) in a text run.
  • From 18.1.1 it also encodes a bare & in that same run as &amp;.

marked's own HTML renderer accounts for this, so the dashboard is unaffected. dreb's TUI and buddy renderers write token.text out unchanged, and the export's text override escapes it a second time.

Classifications

Finding Classification Reasoning
1 — Numeric refs become raw terminal control characters (TUI, buddy) merge blocker Factual: Confirmed. "before &#27;[2J after" stays literal on v15; on v18 it becomes before \u001b[2J after. &#27;]52;c;…&#7; decodes to an OSC 52 clipboard write, and wrapTextWithAnsi / visibleWidth pass it through as zero-width. This affects headings, bold, list items, table cells and link text; code spans are never decoded. Scope: The PR's upgrade introduces this regression. The plan says to fix any real incompatibility in the affected renderer. Practical: Assistant text, thinking, summaries and buddy speech reach these renderers with only .trim() applied. Raw ESC bytes were already unfiltered before this PR. The new problem is a plain-ASCII route: quoted fetched content, or a prompt-injected instruction to repeat a string, now reaches the terminal as CSI (screen clear, hidden text) or OSC 52 (clipboard write). Elsewhere, dreb deliberately strips control output from untrusted text (render-utils.ts, bash-execution.ts, suggest-next.ts).
2 — A bare & renders as &amp; when its run contains a numeric ref (TUI, buddy, export) merge blocker Factual: Confirmed. In the TUI on v18, "Q&A &#8212; R&D" → Q&amp;A — R&amp;D and "Tom &#38; Jerry" → Tom &amp; Jerry. The export produces <p>Q&amp;amp;A — R&amp;amp;D</p> because template.js:1523 re-escapes the text. The dashboard is correct. Scope: A regression introduced by this PR on three surfaces, and a break from the GitHub parity the PR targets (GitHub shows Q&A). Practical: The trigger is uncommon but real. The harm is visible text corruption, including in shareable export files. The fix shares a site with finding 1: handling marked 18's new text-token contract means dealing with both the decoding and the re-encoding.
3 — Indented code blocks gain a trailing blank row (TUI) merge blocker Factual: Confirmed. " code\n" renders as ["```"," code","```"] on v15 and ["```"," code","","```"] on v18. v18 keeps the terminating \n in indented code token text. Both the split("\n") path and the real theme's highlightCode turn it into an extra row, and the same happens for multi-line indented code inside list items. No test covers indented code. Scope: Issue 576 names this exact upgrade risk ("v18: trailing blank lines are trimmed from block tokens, which may affect TUI block spacing"). The plan's directive covers it: "If the implementation turns up a real incompatibility, fix it in that renderer and add a test." Practical: A visible rendering defect inside code fences on the primary surface, introduced by this PR. Indented code does appear in model output, for example in quoted or nested markdown. The fix is one line plus a test.
4 — Link reference definitions add visible blank rows (TUI) merge blocker Factual: Confirmed. "[ref]: /url\n\n[ref]" → ["","ref (/url)"], and "before\n\n[ref]: /url\n\nafter" → ["before","","","after"]. v18 emits the blank after a def as its own space token, and the renderer ignores def but renders space. Scope: The same v18 block-spacing risk that issue 576 names, and the same plan directive. Practical: This is the weakest blocker: link-reference definitions are rare in model output, and the effect is a stray or doubled gap. It is still a PR-introduced regression in the same render loop as finding 3. The repo's Completeness Rule says to fix bugs found during the work rather than ship them.
5 — TUI list tests never exercise the v17 checkbox and loose-list token shapes useful follow-up Factual: Confirmed as a coverage gap. No test covers - [ ] or a loose list. Mutating the paragraph branch to swallow content still passes all 663 TUI tests. Scope / Practical: No current bug: probes show v18 renders tight and loose task lists the same as v15, and correctly. Missing tests do not block a merge on their own. These four tests are cheap and pin the v17 token-shape risk the issue named, so they can go in with the block-spacing fixes.
6 — The harness exposes renderImageTag, which no test uses useful follow-up Factual: Confirmed. It appears only at export-html-template-harness.ts:20/87. It was carried over from the old inline harness into the new shared file. Practical: No behaviour impact. Removing it is a one-line change that can be bundled with the fixes.
7 — The export test couples its case tables by array index nitpick True (SURFACES[0], CASES[0], CASES[4], a repeated literal), but stylistic only. The tests pass and are readable.
8 — The assistant surface is tested twice, with implied assertions nitpick True: the CASES loop already covers assistant text, and the toBe(...) exact match implies the not.toContain("<del>") and toContain("<code>~</code>") assertions before it. The redundancy is harmless.
9 — $ patterns in the export's String.replace inlining deferred Factual: Confirmed pre-existing. template.js:1348 $${totalCost…} is byte-identical on the merge base, and $$ collapsing to $ means the exported Cost display loses its $. The highlight.js $& problem is also pre-existing. The new marked bundle contains only the inert $1, and the verbatim-inlining test guards it. Scope: This PR does not change it. It is a real bug and should get its own issue.
10 — copy-binary-assets misses template.css and template.js deferred Factual: Confirmed pre-existing and identical on the merge base. getExportTemplateDir() points bun binaries at <bin>/export-html, where generateHtml reads both files, so /export from a compiled binary would hit ENOENT. Scope: Not changed by this PR; both copy globs cover the renamed vendor file. It is a real packaging bug and should get its own issue.

Action Plan

  1. Findings 1 and 2 (one fix): handle marked 18's new text-token contract.
    • TUI Markdown (renderInlineTokens text and default branches, renderListItem text fallback, block default branch) and buddy bubble (buddy-component.ts text and default branches): before styling, decode the entities marked now emits (&amp;, &lt;, &gt;, &quot;, &#39;). Then strip C0 control characters (except \n), DEL, C1 (U+0080–U+009F) and bidi override/isolate characters. This also closes the existing raw-ESC gap.
    • Export (template.js text override): stop re-escaping &. Escape only < and >, which mirrors marked's default no-double-encode escape.
    • Acceptance evidence:
      • TUI and buddy tests showing &#27;[2J, &#27;]52;c;aGVsbG8=&#7;, &#13; and &#155; produce no control bytes in rendered output.
      • Tom &#38; Jerry → Tom & Jerry and Q&A &#8212; R&D → Q&A — R&D in the TUI and buddy.
      • An export test where Q&A &#8212; R&D renders <p>Q&amp;A — R&amp;D</p>.
      • Existing suites stay green.
    • Pinning marked to >=17.0.2 <18.0.14 would also avoid finding 1, but it is a fragile stopgap; prefer the sanitizer.
  2. Finding 3: strip the single trailing newline from indented code token text, in both the block code case and the renderListItem code branch. Test " code\n" → ["```"," code","```"], plus the indented-code-in-list shape.
  3. Finding 4: stop rendering the space token that follows a def token, in the same render loop. Test "[ref]: /url\n\n[ref]" → ["ref (/url)"] and "before\n\n[ref]: /url\n\nafter" → ["before","","after"].

The useful follow-ups (finding 5's four list-token-shape tests and finding 6's dead harness member) are cheap and can go in the same implementation pass, but they do not block the merge.


Assessment by mach6

… HTML export

- Strip terminal control characters from markdown source and from text tokens
  after marked decodes numeric character references (&#27; etc.), and undo
  marked's &amp; encoding of bare ampersands (TUI Markdown + buddy bubble)
- Drop the export template's text renderer override so text is escaped once
- Do not render the terminating newline of indented code blocks as a row
- Drop link reference definitions together with their blank-line separator
@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Fixed the four merge blockers from the round 1 assessment: findings 1, 2, 3 and 4. Every new regression test fails on the previous commit and passes on this one.

Findings 1 and 2: marked 18's text-token contract

  • TUI Markdown (packages/tui/src/components/markdown.ts) has two new exported helpers:
    • sanitizeTerminalText() runs on the markdown source before lexing. It turns CR/CRLF into LF and tabs into 3 spaces. It strips C0 controls other than newline, DEL, C1 controls and bidi embedding/override/isolate characters. Raw control characters can no longer reach the terminal from any token type, including code spans, code blocks, inline HTML and link URLs. That also closes the existing raw-ESC gap.
    • markedTextToTerminal() runs on inline text tokens. It turns marked's &amp; back into &, then strips control characters again, because &#27; and similar references have been decoded by that point.
  • Buddy speech bubble: uses the same helpers, applied before lexing and to text tokens.
  • HTML export (template.js):
    • Removed the text renderer override and its now-dead escapeHtmlTags helper. marked's default text renderer escapes once without double-encoding, so Q&A &#8212; R&D shows as Q&A — R&D.
    • Side effect: inline formatting inside tight list items now renders. It used to show as literal **bold**; this was a pre-existing bug caused by the same override, and a test now pins the fix.
    • Quotes in text are now written as &quot;, which looks the same in a browser. The reported-example test's expected HTML is updated to match.

Finding 3

Indented code blocks no longer turn their terminating newline into an extra empty row. This applies both at the top level and inside list items, with or without highlightCode.

Finding 4

def tokens and the space token marked attaches to each one are dropped before rendering, both at the top level and inside blockquotes. Link reference definitions no longer add blank rows.

Tests

  • TUI:
    • Decoded controls: CSI, OSC 52, hex SGR, C1, DEL, bidi, CR and tab. Checked in headings, bold, list items, table cells, links, quotes and strikethrough.
    • Raw controls in every token type.
    • Code spans keep references literal.
    • Ampersand cases, including in headings, lists and tables.
    • Indented code at the top level, in lists and with highlighting.
    • Link reference definitions at the top level, consecutive, after a heading and inside a blockquote.
  • Buddy: decoded controls, raw controls and ampersands.
  • Export:
    • On every surface, & is not double-escaped next to numeric references.
    • Text is escaped once.
    • Inline formatting renders in tight lists.

Verification

  • npm run build passes and leaves package-lock.json unchanged.
  • npm run check passes.
  • npm test passes; the pre-commit run reported 7457 passed.
  • I rendered all 102 repository .md files through the TUI. Output matches marked 15 except for the intended blank line after HTML blocks, which is already pinned by a test.
  • In a real dreb --export opened in headless Chromium, ampersands are correct, list formatting renders, and there are no page errors.
  • Added a short note about control-character stripping to packages/tui/README.md and packages/coding-agent/docs/tui.md.

Pre-existing issue found during the fix (not changed here)

The HTML export passes raw HTML in messages through unchanged. For example, x <img src=x onerror=alert(1)> y is emitted verbatim. The export has no sanitizer and no CSP, so an exported file can run script from message content. This was already the case before this PR, and the PR does not change it. It should be a separate issue, along with deferred findings 9 and 10.

Commit: 8c34d46


Progress tracked by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Unverified Review Candidates — Pending Assessment

Review round: 2
Reviewed commit: 8c34d46

These are unverified candidates. Severity reflects reviewer confidence; do not treat any item as a merge blocker until the assessment comment is posted.

Round-1 merge blockers, re-checked independently:

  • Finding 1 (control characters): fixed. A probe of the real TUI Markdown across 45 constructs (each at two widths, with soft-wrap on and off), plus the buddy bubble, found no leaked control or bidi characters.
  • Finding 2 (&amp;): fixed on the TUI, the buddy bubble and the export.
  • Finding 3 (indented code): fixed for code tokens. A related case remains, see finding 3 below.
  • Finding 4 (link reference definitions): fixed when the definition comes first or sits between paragraphs. A trailing definition still adds a row, see finding 2 below.

Critical

Finding 1 — Export: removing the text override writes some text unescaped, after an inline <code>, <kbd>, <pre> or <script> tag (code-reviewer 100, error-auditor 85, test-reviewer 88 for the missing test)

  • packages/coding-agent/src/core/export-html/template.js (marked.use config, ~1491–1525).
  • Cause: After an inline raw <code>, <kbd>, <pre> or <script> opening tag, marked's lexer marks the following text tokens escaped: true until the closing tag. marked's default renderer writes those tokens out verbatim. The removed override escaped every text token.
  • Probe: each input below was rendered with the real vendored bundle and the template config. "Base" is v15.0.4 with the old override.
Input Base output HEAD output
Wrap the guard in <code>if (i<n) return;</code> before the loop. <code>if (i&lt;n) return;</code> <code>if (i<n) return;</code>
x <code><svg/onload=alert(1)></code> <code>&lt;svg/onload=alert(1)&gt;</code> <code><svg/onload=alert(1)></code>
  • Effect in a browser: In the first case the browser drops the text after i ( n) return;). The second case ran script in headless Chromium.
  • Security impact: The attacker gains nothing new. A plain raw <img src=x onerror=…> already executes in exports on the merge base; that pre-existing passthrough was noted in the progress comment. The new route is still a text token rather than an HTML token, so a later fix that escapes HTML tokens would not close it.
  • Test gap: No export test feeds escaped: true text through the renderer.
  • Suggested fix: Add back a narrow text override that escapes </> only for leaf tokens with escaped: true and returns false for everything else. Add a regression test using the inputs above.

Important

Finding 2 — TUI: a trailing link reference definition still adds a blank row after a heading or a code block (code-reviewer 100)

  • packages/tui/src/components/markdown.ts (withoutLinkDefinitions, ~88–97).
  • Cause: The helper drops a definition and the space token after it. When the definition ends the document, the space token before it is left behind.
  • Probe (real component):
Input Base HEAD
"# H\n\n[r]: /url" ["H"] ["H", ""]
" code\n\n[r]: /url" ["```"," code","```"] ["```"," code","```",""]
  • A trailing definition after a paragraph is unchanged: it already left a trailing "" on the merge base.

Finding 3 — TUI: an indented continuation merged into a list paragraph gains an extra blank row (code-reviewer 100)

  • packages/tui/src/components/markdown.ts (renderListItem paragraph/text path, ~704–707).
  • Cause: marked 18 keeps the terminating newline on a list paragraph that has absorbed an indented continuation. codeBlockText() only normalizes code tokens.
  • Probe: "- a\n b\n\n- c": base ["- a"," b","- c"], HEAD ["- a"," b","","- c"].

Finding 4 — Buddy tests omit cases that the plan and the round-1 action plan list (completeness-checker 100)

  • packages/coding-agent/test/buddy-component.test.ts.
  • Plan deliverable 4 asks for buddy coverage of the reported example and every row of the issue table. Only about ~7 percent vs ~12 percent (see ~) is tested.
  • The round-1 acceptance evidence also lists &#13; and Tom &#38; Jerry → Tom & Jerry for buddy. Neither is tested.
  • Probes show the behaviour is correct today.

Suggestions

Finding 5 — markedTextToTerminal decodes only &amp;, not the full entity list in the round-1 action plan (completeness-checker 99)

  • packages/tui/src/components/markdown.ts:79–80.
  • The round-1 action plan listed &amp;, &lt;, &gt;, &quot; and &#39;. Input &lt; &gt; &quot; still renders literally in the TUI and the buddy bubble.
  • Note: marked 18 only re-encodes & in text runs. The probe x &#60;b&#62; y gives text token x <b> y. Literal &lt; rendered the same way on the merge base.

Finding 6 — Root and coding-agent READMEs don't mention the new terminal-control stripping (completeness-checker 98)

  • packages/tui/README.md and packages/coding-agent/docs/tui.md were updated. README.md and packages/coding-agent/README.md were not.
  • AGENTS.md asks for root README updates when capabilities change.

Finding 7 — The harness still exposes renderImageTag, which no test uses (simplifier 90)

  • Round-1 finding 6, still present: packages/coding-agent/test/export-html-template-harness.ts:20, 87.

Finding 8 — The export test couples SURFACES/CASES by array index and repeats a literal (simplifier 83)

  • Round-1 finding 7, still present: export-html-markdown.test.ts lines 123, 159, 168, 172, 186 and 192.

Finding 9 — The export test runs the assistant-text surface twice, and two assertions are implied by the exact match (simplifier 84)

  • Round-1 finding 8, still present: export-html-markdown.test.ts:157–174.

Finding 10 — The dashboard test's backtick assertion is implied by its exact-text assertion (simplifier 82)

  • packages/dashboard/test/client/markdown-strikethrough.test.tsx:73–75. textContent.trim() === text already rules out stray backticks, because no test input contains one.

Strengths

  • Every issue acceptance criterion has a test on the TUI, dashboard and export surfaces that fails on a revert.
  • Mutation testing on the TUI caught every round-1 fix path. Each mutation of the sanitizer ranges, the &amp; decode, the def filtering (top level and blockquote) and the indented-code strip failed at least one test.
  • All four buddy fix mutations were caught.
  • Ampersand handling decodes exactly one layer: &amp;amp; → &amp;.
  • The export now also fixes two existing bugs:
    • inline formatting in tight list items, which was shown as literal **b**;
    • image alt injection: ![a" onerror="alert(1)](x) used to emit a live attribute.
  • Checks passed:
    • the full npm test (7457 passed);
    • lockfile discipline and the byte-identical vendored bundle;
    • the dashboard screenshots, regenerated byte-identical.
  • The new export bundle contains no $&, $$ or </script.

Agents run: code-reviewer, error-auditor, test-reviewer (retried after the first attempt was terminated), completeness-checker, simplifier


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Findings: #578 (comment)

Round 2: independent-assessor, with parent adjudication. Every regression claim was re-checked by running the real code on the merge base and on HEAD:

  • the TUI Markdown component on marked 15.0.12 and on 18.2.0;
  • the export through the real template.js, with the v15.0.4 bundle on the merge base and the vendored v18.2.0 bundle on HEAD.

Round-1 merge blockers:

  • Finding 1 (control characters): fixed.
  • Finding 2 (&amp;): fixed on the TUI, the buddy bubble and the export.
  • Finding 3 (indented code): fixed.
  • Finding 4 (link reference definitions): fixed for both cases in its acceptance evidence. One trailing variant is left; it is round-2 finding 2 below.

Classifications

Finding Classification Reasoning
1 — Export writes escaped: true text unescaped after inline <code>/<kbd>/<pre>/<script> merge blocker Factual: Confirmed with the shipped template.js and vendored bundle. In marked, startPreScriptTag sets inRawBlock, and the text that follows becomes { text, escaped: true }. The default renderer writes those tokens out verbatim. Results on HEAD:
• Wrap the guard in <code>if (i<n) return;</code> → <code>if (i<n) return;</code>, so the browser loses n) return;.
• x <code><svg/onload=alert(1)></code> → live markup.
The merge base escapes both. Scope: A regression introduced by this PR. The approved round-1 fix said to keep a text override that escapes only < and >; the implementation removed the override instead. Practical: Code samples written with inline <code> tags are silently corrupted in shareable export files. Raw HTML already passes through on the merge base, so the attacker gains no new capability. But input that was inert on the merge base now runs, and the route is a text token, so a later fix that escapes HTML tokens would not close it.
2 — TUI: a trailing link definition adds a blank row after a heading or a code block merge blocker (low severity) Factual: Confirmed. "# H\n\n[r]: /url" gives ["H"] on the merge base and ["H",""] on HEAD. The code-block case also gains a trailing "". Token dumps explain it: v15's heading and code rules consumed the trailing blank lines, while v18 emits heading, space, def. withoutLinkDefinitions only drops the space after a def. A trailing definition after a paragraph already left a "" on the merge base, so that case is out of scope. Scope: The rest of the approved round-1 finding 4 fix, in a helper this PR adds. The plan says to fix a real incompatibility in the renderer, and AGENTS.md's Completeness Rule applies. Practical: A cosmetic but visible regression on the main surface, consistent with how round 1 treated finding 4. The fix is trivial.
3 — TUI: an indented continuation in a list paragraph gains an extra blank row merge blocker (low severity) Factual: Confirmed. "- a\n b\n\n- c" gives ["- a"," b","- c"] on the merge base and ["- a"," b","","- c"] on HEAD. The loose item's paragraph text is "a\nb\n", because v18 keeps the terminating newline. renderListItem's text and paragraph paths lack the trailing-newline normalization that codeBlockText() applies to code. It only triggers with continuations indented 6+ spaces followed by a blank line; 2-space continuations are unaffected. Scope / Practical: The same v18 block-spacing incompatibility as round-1 finding 3, introduced by this PR. It visibly breaks list spacing on the main surface, and the fix is one line.
4 — Buddy tests omit cases from the plan and the round-1 action plan useful follow-up Factual: Accurate as a coverage gap. Practical: The real BuddyComponent renders every issue-table row, &#13; and Tom &#38; Jerry correctly today. It shares the sanitizeTerminalText/markedTextToTerminal helpers, which the TUI tests cover and which survived mutation testing. The plan's testing section specified one buddy case, and it exists. Missing tests don't block a merge on their own, and no specific regression is hiding here. The two extra cases are cheap.
5 — markedTextToTerminal decodes only &amp; discarded observation The only entity marked 18 produces in text tokens is &amp;: it decodes numeric references and re-encodes a bare &. Typed &lt;, &quot; and &#39;-style named entities stay literal, exactly as on the merge base. Decoding them would change behaviour from the merge base. The round-1 list of five entities was over-specified, and its stated acceptance evidence (Tom &#38; Jerry → Tom & Jerry) is met.
6 — Root and coding-agent READMEs don't mention control-character stripping nitpick Neither README describes markdown sanitization, so neither is made inaccurate. The directly relevant docs (packages/tui/README.md, packages/coding-agent/docs/tui.md) were updated.
7 — The harness still exposes renderImageTag, which no test uses useful follow-up Confirmed. It appears only at export-html-template-harness.ts:20, 87. Dead surface in a new file. It is a two-line removal with no behaviour impact, the same classification as round 1.
8 — The export test couples SURFACES/CASES by array index nitpick True, but stylistic; the tests pass and are readable.
9 — The assistant surface is tested twice, with implied assertions nitpick True, and harmless redundancy.
10 — The dashboard backtick assertion is implied by the exact-text assertion nitpick True: it can never fail on its own. It still documents intent.

Action Plan

  1. Finding 1: restore escaping for raw-block text in the export (template.js).
    • The fix must not re-escape the escaped: true tokens marked builds internally from already-rendered HTML, such as list-item and task-list content.
    • Option A: a lexer-side walkTokens(token) { if (token.type === "text" && token.escaped) token.escaped = false; }. marked's own renderer then escapes these tokens once.
    • Option B: a leaf-only text override that returns false when token.tokens is set, and otherwise escapes </> and any bare & (no double-encoding).
    • Both options produce correct output on these probes against the vendored bundle: tight list formatting, tight and loose task lists, Q&A &#8212; R&D and strikethrough.
    • Acceptance evidence: with the real template and vendored bundle:
      • Wrap the guard in <code>if (i<n) return;</code> before the loop. renders <code>if (i&lt;n) return;</code>.
      • x <code><svg/onload=alert(1)></code> renders escaped.
      • press <kbd>Ctrl</kbd>+<kbd>C</kbd> is unchanged.
      • The existing ampersand, tight-list and strikethrough export tests stay green.
  2. Finding 2: in withoutLinkDefinitions, when a dropped def has no following space token, drop the space token before it instead.
    • Acceptance evidence: "# H\n\n[r]: /url" → ["H"] and " code\n\n[r]: /url" → ["```"," code","```"]. The existing def tests stay green.
  3. Finding 3: strip trailing newlines from list-item text/paragraph content in renderListItem before splitRenderedTextLines, the same way codeBlockText does for code.
    • Acceptance evidence: "- a\n b\n\n- c" → ["- a"," b","- c"]. The existing list suite stays green.

Useful follow-ups (finding 4's buddy &#13; and Tom &#38; Jerry pins, and finding 7's dead harness member) are cheap and can go in the same pass, but they don't block the merge. The pre-existing export issues stay deferred to separate issues: raw-HTML passthrough, the $ patterns in String.replace inlining, and copy-binary-assets.


Assessment by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Fixed the three merge blockers from the round 2 assessment: findings 1, 2 and 3. Each new regression test fails on the previous commit (8c34d46) and passes on this one.

Finding 1: export escapes text after an inline raw tag

  • Where: template.js.
  • Change: a walkTokens hook clears marked's escaped flag on lexed text tokens. Marked's own renderer then escapes that text like any other, without double-encoding.
  • Examples:
    • <code>if (i<n) return;</code> now exports as if (i&lt;n) return;.
    • <code><svg/onload=alert(1)></code> stays inert.
    • <kbd>Ctrl</kbd>+<kbd>C</kbd> is unchanged.
  • Why this approach: marked 18 sets escaped: true only for text after a raw tag. Its parser no longer creates such tokens internally from rendered HTML, so list formatting, task lists, ampersands and strikethrough render exactly as before.
  • Tests (export-html-markdown.test.ts):
    • <code>, <kbd> and <pre> cases, plus ampersands and a numeric reference inside a raw tag;
    • the <code> case on all five export surfaces.
    • With the hook disabled, 10 of the new tests fail.

Finding 2: no trailing blank row from link definitions

  • Where: packages/tui/src/components/markdown.ts.
  • Change: withoutLinkDefinitions now handles a run of consecutive definitions as one unit. If the run ends the token list, it also drops the space token before the run.
  • Examples:
    • "# H\n\n[r]: /url" → ["H"].
    • " code\n\n[r]: /url" → no trailing row.
    • The blank row between two blocks that sit around a run of definitions is kept.
  • Side effect: "para\n\n[r]: /url" ended with a blank row on the merge base and now does not.

Finding 3: no empty row after a deeply indented list continuation

  • Where: same file.
  • Change: a new withoutTrailingNewline() helper strips the trailing newline from the last inline text token of list-item text and list-item paragraphs, before rendering. In a list item, marked merges a continuation indented 6+ spaces in as indented code, keeping its terminating newline.
  • Tests: loose and ordered lists, multi-line continuations, a continuation ending in bold or a code span, and a continuation followed by a nested list.

Verification

  • npm run build passes and leaves package-lock.json unchanged.
  • npm run check passes.
  • npm test passes; the pre-commit run reported 7473 passed.
  • The built packages/tui/dist renders the finding 2 and 3 cases correctly.

Discoveries during the fix (not changed here; for the next review round)

  • Trailing blank row after some blocks. Markdown ending in blank lines after a heading, an indented code block, a table or an HTML block, with no link definition involved, now renders one trailing blank row in the TUI.
    • Example: "# H\n\n" → ["H",""]; the merge base gave ["H"].
    • Cause: marked 18 emits those trailing blank lines as a space token.
    • Assistant text is trimmed first, so it is not affected. These callers do not trim: user, custom, skill-invocation, compaction and branch-summary messages, the suggest_next summary, and the ask wizard.
  • Dashboard text after an inline raw <code> tag. Text after an inline raw <code> tag is written out raw, so if (i<n) return; displays as if (i. DOMPurify keeps it from running script. This happens identically with marked 15 on the merge base, so it is not introduced by this PR.

Commit: 1cd7ed4


Progress tracked by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Unverified Review Candidates — Pending Assessment

Review round: 3
Reviewed commit: 1cd7ed4

These are unverified candidates. Severity reflects reviewer confidence; do not treat any item as a merge blocker until the assessment comment is posted.

The full PR was reviewed against merge base e140283ae920b0ee1cf4eff85accdd152a8a3f0e. The delta from round 2's reviewed commit, 8c34d46813f69f2a616305a28a72eea058ec3b47, was supplemental fix-verification context, not the review boundary.

Previous merge blockers, independently re-checked:

  • Round 1: decoded/raw terminal controls, ampersand handling, indented-code termination, and the specified link-definition spacing cases pass at HEAD.
  • Round 2: inline raw-tag text in the export is escaped; trailing definitions after headings/code no longer add rows; "- a\n b\n\n- c" no longer adds an empty continuation row. Tight-list formatting and task checkboxes still render correctly in the export.

Critical

None reported.

Important

Finding 1 — Export: raw HTML inside list items now becomes live markup and can hide subsequent content (error-auditor, confidence 88)

  • packages/coding-agent/src/core/export-html/template.js:1494–1534 — the removed text override used to escape the raw text of list items, including their HTML tags. The current default renderer renders their nested inline HTML tokens instead.
  • With the real templates and vendored bundles:
    • - x <img src=x onerror=alert(1)> y: merge base emits &lt;img …&gt;; HEAD emits an actual <img … onerror=…> inside <li>. Tight, loose, nested, ordered, and task items reproduce it.
    • Steps:\n\n- Put the page name in the <title> element\n- Add a stylesheet link\n- Add the body content\n\nDONE-MARKER: merge base shows all three items and the final paragraph. HEAD shows only Steps: and Put the page name in the; the remaining generated markup is swallowed by the unclosed <title>.
  • Chromium probes confirmed list-item onerror fires only at HEAD. Parent DOM probes independently confirmed the three-to-one list-item reduction and missing visible final paragraph.
  • Important qualification: paragraphs already passed raw HTML through on the merge base. This is not a new attacker capability; it extends the existing passthrough to previously inert list content and introduces reachable visible content loss there.
  • Suggested fix: handle source HTML tokens safely without restoring the old text override or breaking list formatting. A global html renderer that escapes source markup is one option, but changes existing raw-tag expectations; the assessment should establish the minimally necessary scope.

Finding 2 — TUI: mixed-indentation list continuations gain an internal blank row (code-reviewer, confidence 100)

  • packages/tui/src/components/markdown.ts:117–120,717–722 — withoutTrailingNewline handles only a final text-token newline. Marked also retains the indented-code terminator when more continuation text follows, making it internal.
  • Real component comparison:
    • "- a\n b\n c\n- d": base ["- a"," b"," c","- d"]; HEAD ["- a"," b",""," c","- d"].
    • "1. a\n b\n c\n2. d": base ["1. a"," b"," c","2. d"]; HEAD adds "" before c.
  • No blank line exists in either source. The extra row survives assistant-message .trim(). Parent probes independently confirmed both comparisons.
  • Suggested fix: remove the artificial code terminator before it is merged into list text, or use equivalent source-aware normalization; do not indiscriminately delete authored internal blank lines.

Finding 3 — TUI: trailing blank lines after some block types now add a visible EOF row (code-reviewer 100; test-reviewer 82; completeness-checker 82)

  • packages/tui/src/components/markdown.ts:190–200,543–546 — the space branch renders marked 18's newly separate trailing separator even when nothing follows.
  • "# H\n\n": base ["H"]; HEAD ["H",""]. Indented code, tables, HTML blocks, and setext headings reproduce it.
  • Actual UserMessageComponent("# H\n\n"): base ["","","H",""]; HEAD ["","","H","",""]. The ask wizard similarly gains a row between a question and its options. Expanded summaries/custom messages/skill content can also pass untrimmed input.
  • Qualifications: paragraphs, lists, fences, blockquotes, and rules already rendered a trailing row on the merge base. Assistant text/thinking trim first; normal editor submission and normal suggest_next execution also trim. This is cosmetic and limited to untrimmed inputs.
  • The implementer explicitly recorded this discovery in the latest progress comment. Existing HTML-block spacing tests cover an inter-block separator, not EOF.
  • Suggested fix: decide whether EOF separators should be omitted and pin that contract without changing inter-block spacing or trimming indented-code source.

Suggestions

Finding 4 — Sanitizer tests sample ranges instead of pinning every intended control code point (test-reviewer, confidence 92)

  • packages/tui/src/components/markdown.ts:61–80; packages/tui/test/markdown.test.ts:1271–1312; packages/coding-agent/test/buddy-component.test.ts:146–158.
  • Ten of seventeen boundary/range-narrowing mutations survived: C1 DCS/OSC/APC, NUL/BS/VT/FF/SO/SI, some bidi endpoints and isolates lack input cases. No control leaks were found in current code, including exhaustive auditor probes.
  • Suggested follow-up: directly test both exported helpers against every intended forbidden code point, plus allowed newline/printable-character controls. Missing tests are not themselves evidence of a live bug.

Finding 5 — The shared harness exposes unused renderImageTag (simplifier, confidence 95)

  • packages/coding-agent/test/export-html-template-harness.ts:20,87. Only the interface and injected return mention it; no test uses it. Carried over from prior rounds.
  • Remove the unused member and returned reference.

Finding 6 — Block and list-item code rendering duplicate the same fence/highlighting skeleton (simplifier, confidence 85)

  • packages/tui/src/components/markdown.ts:422–445,724–743. Both paths now call codeBlockText but still duplicate body rendering.
  • A shared helper could reduce future drift, provided it preserves the paths' different wrapping, line expansion, and theme callback semantics.

Finding 7 — List-continuation comments allegedly describe the wrong marked mechanism (simplifier, confidence 90)

  • packages/tui/src/components/markdown.ts:111–116; packages/tui/test/markdown.test.ts:1396–1397.
  • The reviewer disputes “lexed as indented code and merged” because the final token dump contains only a paragraph/text token, and proposes describing newline retention instead.
  • This claim requires checking intermediate lexer processing, not merely the final token shape.

Finding 8 — New TUI tests repeat the same plain-render helper (simplifier, confidence 90)

  • packages/tui/test/markdown.test.ts:1147,1358–1362,1390–1394,1415–1419. Share the ANSI-stripping render helper, with configurable theme/width, if it improves readability.

Finding 9 — Export test fixtures are coupled by array index (simplifier, confidence 88)

  • packages/coding-agent/test/export-html-markdown.test.ts:140,159,168,172,186,217,228. References such as SURFACES[1] and CASES[4] could use named fixtures. Carried over from prior rounds.

Finding 10 — Export assistant cases and exact-match implications are tested redundantly (simplifier, confidence 85)

  • packages/coding-agent/test/export-html-markdown.test.ts:157–174. Assistant cases occur in both loops; exact HTML equality already implies intact <code>~</code> and no <del>. Carried over from prior rounds.

Finding 11 — A dashboard backtick assertion is implied by exact text equality (simplifier, confidence 85)

  • packages/dashboard/test/client/markdown-strikethrough.test.tsx:73–75. All expected strings lack backticks, so equality already rejects stray backticks. Transcript assertions without exact equality remain load-bearing. Carried over from round 2.

Finding 12 — Boolean string comparison loses useful failure diagnostics (simplifier, confidence 90)

  • packages/coding-agent/test/export-html-markdown.test.ts:237. expect(actual === expected).toBe(true) could be expect(actual).toBe(expected) to retain the same check with a string diff.

Finding 13 — The token.escaped guard before assigning false is redundant for marked's renderer (simplifier, confidence 82)

  • packages/coding-agent/src/core/export-html/template.js:1502–1506. Assigning escaped = false to every text token also selects the escaping path. The current guard avoids changing absent flags; whether removing it is actually clearer remains to be assessed.

Finding 14 — Consecutive-definition while loop has no effect on output (test-reviewer observation; parent confidence 100)

  • packages/tui/src/components/markdown.ts:96. Removing while (tokens[i + 1]?.type === "def") i++; survived mutation testing.
  • The parent independently enumerated all 9,841 token sequences up to length eight over def/space/other: output is identical with and without the loop. Per-definition handling already covers the consecutive case.
  • Remove the redundant loop if simplifying this helper; retain all def/separator tests.

Strengths

  • GitHub's actual GFM API matches all issue-table cases on the TUI, dashboard, and export. Buddy visible text is correct; its lack of strike styling is unchanged.
  • All previous blocker acceptance probes pass. Mutations of the new raw-tag hook, trailing-definition cleanup, list-tail cleanup, and ampersand decode are caught by regression tests.
  • Sanitizer audits found no current control-character leaks across token types, widths, wrap modes, and the buddy bubble.
  • The export hook does not double-escape entities, tight-list formatting, or task checkbox HTML; the harness uses the actual shipped template/configuration and fails loudly on marker drift.
  • Full offline tests and lint/type checks pass. The pinned lockfile is canonical, the build leaves it unchanged, workspace links are valid, and the vendored marked bundle matches installed bytes.
  • All nine dashboard screenshots regenerated byte-identical. No tracked old vendor filename remains.

Agents run: code-reviewer, error-auditor, test-reviewer, completeness-checker, simplifier. All five completed. Explicit agent routing used multiple model families; distinct roles alone were not treated as model diversity.


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Findings: #578 (comment)

Review round: 3
Reviewed commit: 1cd7ed46fa7f12b0e923871ebb9f271de3da599d

Phase two used independent-assessor, developers-advocate, and devils-advocate, all with the same candidates, actual source, full PR diff, original requests, authoritative issue/plan, and supplemental delta. The parent independently reproduced the significant base-versus-HEAD comparisons. Prior classifications were not treated as scope authority or a reason to keep small defects blocking forever.

Result: no merge blockers under the round-3 factual, scope, and practical gates. All previous blocker acceptance probes pass. The explicit strikethrough/code-span criteria, vendoring guards, and required repository checks are met. Green tests do not imply exhaustive protection against all HTML-export behavior; finding 1 below is a verified behavior change, not a false positive.

Classifications

Finding Classification Reasoning
1 — Raw HTML in export list items becomes live and can hide later content useful follow-up Factual: Confirmed. The old override escaped list items wholesale; the default renderer now handles their inline formatting and HTML. An unclosed <title> in a list item can hide the rest of that message in an exported file. Scope: This newly exposed list route is introduced by the PR; it must not be described as wholly unchanged or dismissed solely as pre-existing. The broader raw-HTML export policy already has the same problem outside lists. Practical: No new attacker capability or affected surface is introduced, and accidental list escaping was inseparable from the old broken inline renderer. Both practical-impact assessors judged this a non-blocking extension of the existing HTML-policy problem, rather than a reason to restore the faulty list renderer or mandate a new global HTML policy in this strike-parity PR. Preserve the content-loss example with that follow-up; see the counter-pressure analysis below.
2 — Mixed-indentation list continuation gains an internal blank row useful follow-up Factual: Confirmed: "- a\n b\n c\n- d" gains one internal empty row because the merged indented-code terminator is no longer at the end. Scope: Part of the identified upgrade-spacing risk, but the previous exact acceptance case is fixed. Practical: No lost text, changed nesting, safety failure, or explicit acceptance violation was demonstrated. Fixing arbitrary internal newlines risks deleting authored paragraph breaks; source-aware spacing polish is non-blocking.
3 — EOF blank row after some block types discarded observation Factual: The output change is real for headings, tables, HTML, and indented code ending with blank lines. Scope: No EOF policy was specified. Paragraphs, lists, fences, quotes, and rules already emitted this row on the base; HEAD makes these endings consistent. Practical: A single cosmetic row for untrimmed callers. Assistant text, thinking, normal editor submission, and normal suggest_next execution trim first. This does not justify another blocker or an indiscriminate source trim.
4 — Sanitizer range tests are sampled useful follow-up Factual: Some range-narrowing mutations survive because the input cases do not cover every forbidden code point. Production ranges are correct, and exhaustive renderer audits found no current leaks. Scope: Useful hardening for the exported helpers and security regression guards. Practical: No current important regression is concealed; missing tests alone do not block. A direct code-point matrix would improve future protection.
5 — Unused harness renderImageTag useful follow-up Factual: Only the harness interface and injected return reference it. Scope: Dead test surface in a new shared harness. Practical: Remove it when cleaning the harness; no runtime behavior or acceptance evidence is affected.
6 — Duplicated code-block rendering skeleton nitpick Factual: The duplication predates the PR, which adds the same normalization to both paths. Scope / Practical: The paths have different soft-wrap/line-expansion behavior. A callback abstraction is optional and must preserve theme receiver semantics; no demonstrated failure requires a refactor.
7 — Incorrect list-continuation mechanism comment false positive Factual: The comment is accurate. Marked's block lexer calls tokenizer.code, then merges the resulting code text into a preceding paragraph/text token with a.text += "\n" + r.text. The final paragraph-only dump hides that intermediate code token. Scope / Practical: No correction needed.
8 — Repeated plain-render helpers nitpick Factual: Local helpers repeat ANSI stripping/rendering, with theme differences. Scope / Practical: Readable local test setup; consolidation is stylistic, not required evidence or correctness work.
9 — Index-coupled export fixtures nitpick Factual: Positional references exist. Scope / Practical: Named fixtures could improve maintenance, but current tests select the intended cases and pass.
10 — Redundant export assistant cases/assertions nitpick Factual: Exact HTML equality implies the additional substring assertions, and assistant cases overlap. Scope / Practical: Harmless repetition that also documents intent.
11 — Dashboard backtick assertion implied by exact text nitpick Factual: True for the exact-text cases. Scope / Practical: Harmless intent documentation. Transcript checks without exact equality remain useful.
12 — Boolean string equality nitpick Factual: Direct string equality gives different diagnostics but the same pass/fail condition. Scope / Practical: A diff of a roughly 51 KB minified bundle is not necessarily better. The boolean comparison is defensible.
13 — Conditional escaped = false assignment nitpick Factual: Assigning false to every text token also selects the same renderer branch. Scope / Practical: The current guard communicates that only flagged tokens are changed and avoids adding absent properties. No behavior problem exists.
14 — Redundant consecutive-definition loop useful follow-up Factual: Per-definition handling already covers consecutive runs. Removing the while leaves identical output; parent enumeration verified 9,841 sequences. Scope: Small redundant work in the new helper. Practical: Genuine cleanup, not a shipping failure. Keep separator/definition tests if removing it.

Counter-pressure and acceptance evidence

Finding 1 received genuine disagreement, not an averaged confidence score. The independent assessor and developer's advocate found it non-blocking; the acceptance critic argued that the content-swallowing portion is material. The concrete sequence is:

  1. A model or user writes a list item naming an unescaped <title>, <script>, or <textarea> tag.
  2. The user exports the session and opens or shares the HTML.
  3. The browser parses the opening tag inside that list item. Subsequent generated markup in the same entry becomes its content; later list items, text/thinking blocks, or tool cards in that entry can disappear from view.
  4. The export parses entries separately, so the damage does not swallow subsequent session entries. Original session data, TUI rendering, and dashboard rendering remain intact. There is no sanitizer/CSP safeguard in the export; paragraphs already exposed this exact content-swallowing and event-handler behavior on the merge base.

A fix would materially preserve the visible remainder of that entry for this input; that is why it merits a concrete follow-up, not a false-positive dismissal. The non-blocking judgment rests on the existing raw-HTML interpretation policy, the lack of a new attacker capability or a list-only supported surface, and the now-correct common list-formatting behavior—not on a claim that the list change is imaginary or that finding 1 cannot cause content loss. Neither required practical-impact assessor found grounds to block this PR, and none of the explicit strike-parity acceptance criteria fails.

The acceptance critic identified useful minimal evidence for that follow-up: render tight and loose lists containing unclosed content-swallowing tags, then inspect the parsed DOM for the later items/final text. Merely asserting that the HTML string contains DONE-MARKER is insufficient: swallowed markup is still present in the string. A narrowly scoped GFM tagfilter was demonstrated in a temporary copy to preserve the existing strike, ampersand, list-formatting, checkbox, <kbd>, and raw-code-text expectations. It addresses swallowing tags, not the broader <img onerror> security problem. This is an option for the HTML-policy work, not a new mandated acceptance criterion or implementation in this review session.

For finding 2, a future normalization test must also preserve an intentionally authored internal blank line. For finding 4, exhaustive helper tests are hardening evidence; there is no current leak to repair.

Action Plan

None — no merge blockers. Do not automatically implement the useful follow-ups or start another review round. Follow-up tracking requires the requester's choice.

Counts: 0 merge blockers; 5 useful follow-ups; 7 nitpicks; 1 false positive; 1 discarded observation; 0 deferred candidates in this round. Previously recorded export HTML-policy, replacement-string inlining, and binary-asset packaging work remains separate; no issues were created during this review.

No tracked code was changed. HEAD and the remote PR SHA remained identical and the working tree stayed clean.


Assessment by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Publication preparation — v2.83.1

  • Bumped root/workspaces/plugin manifest and lockfile workspace versions to 2.83.1 on the feature branch, then built and verified the actual TUI startup banner offline.
  • Updated root README, coding-agent README, TUI README, and TUI docs for GFM strikethrough and the terminal-text helpers. Added an explicit HTML-export trust warning; no renderer behavior changed during publication.
  • Both publication commits passed lint, type checking, and the full offline pre-commit suite: 7,473 passed, 0 failed, 753 skipped. Build leaves the lockfile unchanged; workspace links are healthy.
  • Latest review assessment has no merge blockers; non-blocking observations remain recorded there. Dashboard screenshots were regenerated byte-identical during review.

Final pre-merge commit: f703e3e

Next: the final CI gate, then squash merge and tag v2.83.1. GitHub release creation and release notes remain requester checkpoints.

@m-aebrer
m-aebrer merged commit 9a942a5 into master Nov 13, 2026
4 checks passed
@m-aebrer
m-aebrer deleted the feature/issue-576-strikethrough-gfm-parity branch November 13, 2026 15:50
@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Published v2.83.1

  • Squash-merged after the final CI gate passed (lint/type checks, tests, coverage, dashboard screenshots).
  • Merge commit: 9a942a56d1c84e75c556f92b2f8657a766df98d8.
  • Tag v2.83.1 pushed on that exact merged commit; root/workspace/plugin versions match.
  • GitHub release created with requester-approved notes: https://github.com/aebrer/dreb/releases/tag/v2.83.1
  • Local checkout is clean on master; feature branch deleted. No dashboard service restart was performed.

Publication validation: built TUI banner reports 2.83.1; 7,473 offline tests passed; build leaves the lockfile unchanged; workspace links are healthy. Non-blocking limitations are recorded in the release notes and documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix false strikethrough from stray ~; match GitHub GFM rules

1 participant