Skip to content

Refuse a diagram source the renderer does not read whole - #860

Closed
leaf-agent wants to merge 12 commits into
mainfrom
fix/issue-859
Closed

leaf-agent wants to merge 12 commits into
mainfrom
fix/issue-859

Conversation

@leaf-agent

@leaf-agent leaf-agent commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Beautiful Mermaid's parsers are total. Every statement they cannot read has a defined silent reading — the flowchart's consumeNode falls back to BARE_NODE_REGEX and takes the leading word, parseEdgeLine drops whatever it could not advance past, and parseStateDiagram's loop falls off the end of its last pattern — so the graph they return cannot tell a statement that was read from one that was guessed, and a host has nothing to check. That is why #859's source drew a box labelled A beside a node named second while version check --render called the page clean, and why each divergence Leaf has found has needed its own guard.

This PR opened as the fourth such guard. It now deletes all four. scripts/vendor-src/beautiful-mermaid/report-unread-text.patch is a Leaf-owned patch to upstream's parsers that keeps the text each one walked away from and exports one function answering it for a source; vendor.py applies it and bundles upstream's published src/ rather than its dist/. lf-diagram refuses on that reading alone:

refuseUnreadStatements(unreadMermaidText(source));

That is the whole widget-side rule, replacing ~90 lines of Mermaid grammar — UNSUPPORTED_DIRECTIVE, rejectCutLabel from #312, and the unclosed-label walk this branch built across four rounds. It costs no page bytes beyond the patch itself: the bundle grows 239 bytes, from 1,558,682 to 1,558,921.

It catches what a hand-written guard structurally could not. A rule stated beside the parser can only refuse divergences somebody already noticed. Two the four guards missed are now refused: A --o B, an arrowhead this renderer has no pattern for, which drew a lone A; and A-->B with no space before the arrow, which draws a single node labelled A-- and no edge — upstream lukilabs/beautiful-mermaid#140. The branch's own test listed A-->B among the sources that "stay accepted", which is the argument against the approach in one line.

What it does not catch is a parser reading too much. The instrumentation sits at every point a parser gives up, which accounts for under-reading and not for its mirror: a parser that reads past a statement leaves nothing over, so unreadMermaidText returns an empty list and the page draws the part that was read. A[/a/] --> B[\b\] under flowchart LR draws one box labelled a/] --> B[\b, with B and the edge gone — a slanted shape's label runs to the next closer matching its opener wherever that falls, and four of the twenty-five ordered pairs of this renderer's five bracket shapes do it. No lf-diagram body in examples/, docs/, skills/ or tests/ uses a slanted shape, so nothing shipped is affected. The fix is to anchor those patterns so a label cannot span an arrow, which changes what a statement reads as — the one thing the patch's header promises it does not do — so references/authoring-evidence.md, the widget comment and the test docstring name the limit instead, with the one-node-per-line form that renders both.

The patch is marked as a patch, not absorbed as a fork. It is a unified diff against upstream's source with a header saying what it changes and when it goes away, applied at build time. A pin that moves the lines it names fails the build rather than the page — vendor.py uses patch --batch --forward, not git apply, because git apply resolves paths against an enclosing repository's root and would quietly apply nothing where a host builds inside one. When a release carries the reading, the patch file and one name in vendor.py's entry go away and lf-diagram keeps calling unreadMermaidText. Nothing about Mermaid's grammar lives in Leaf in the meantime.

The reading covers the flowchart and state-diagram parsers, which is where every divergence Leaf has found lives. The four other grammars this renderer reads — sequence, class, ER, xychart — still drop or guess at a statement their parser cannot read and draw the rest, with nothing reporting it; unreadMermaidText returns an empty list for those and references/authoring-evidence.md says so. That narrows one thing the deleted guards did cover, because UNSUPPORTED_DIRECTIVE matched over the raw source with no header check: click, accTitle and accDescr were refused in every grammar and are now refused in a flowchart only, plus click in a stateDiagram. In a class diagram accTitle: Checkout flow draws a box named accTitle; in a stateDiagram the state parser reads it as one of its own id : label statements and draws a loose state labelled Checkout flow; in a sequence, ER or XY source it is dropped. Keeping that refusal would mean a regex back in the widget, which is the code this PR exists to delete, so the reference names the loss instead. Widening to them is an addition to this patch rather than a second design, against the same export and the same widget call, but they do not cost the same: sequence and xychart are one unread.push at the end of a loop, the ER parser gives up a second time inside an entity body, and inside a class body nothing gives up at all — the member reader splits whatever it is given into a member, so ~~bogus~~ draws as ~ ~bogus~~. That last one is BARE_NODE_REGEX in the member position, so reaching it means changing that fallback rather than pushing at it. scripts/CLAUDE.md and the widget comment say which is which.

What this still does not settle is the error's usefulness. The refusal names the text the renderer stopped at — the renderer does not read this, and would draw the diagram without it: "["first line" — where the deleted guard could say "carry a second line inside the label with <br/>". That guidance moved to references/authoring-evidence.md, where an author reads it before writing rather than after being refused. The trade is deliberate: a general, always-correct refusal plus authored guidance, rather than a grammar in the widget that is helpful about the three cases it knows and silent about the rest.

Closes #859, and supersedes the guard #312 added.

Verification

test_a_source_the_renderer_does_not_read_whole_is_refused in tests/test_render_pages.py replaces the three diagram-refusal tests, because there is now one rule rather than three. It holds fourteen refusals, each asserted on the exact leftover the parser reports:

refused leftover
click / accTitle / accDescr directives A href "https://example.com" "Open", : Checkout flow, {
cut label, cut diamond, cut pipe edge label (#312) "] --> B[plain], "} --> B[plain], "| B
label split across lines, in all four places Mermaid carries label text, plus the subgraph title (#859) ["first line, [first line, "], |"carries, -- carries, >first line
unsupported arrowhead --o B
spaceless arrow >B

and fourteen controls that must keep rendering: the <br/> form, A[5" pipe], A[call foo(bar], A>call foo(bar], A -- pay(cash --> B, A -- "a\|b" --> B, A[["names: list[str]"]], A -->\|"list[str]"\| B, subgraph S["Stage [1]"], a commented-out line, click/accTitle/accDescr as node ids, classDef/style/linkStyle, A & B --> C & D, and a composite state body.

Replaying unreadMermaidText over every lf-diagram body in examples/, docs/, skills/ and tests/ — 92 extracted — reports leftovers for exactly the 12 refusal fixtures those tests own and nothing else. No shipped diagram in examples/, docs/ or skills/ changes, including the five stateDiagram bodies the state-parser instrumentation newly reads.

uv run pytest tests/test_render_pages.py --run-nightly is green (54 passed, down from 56 because three tests became one). tests/test_render_startup.py and tests/test_interact_layer.py, which assert on the bundle's lazy load and its presence in a vendored page, are green on their diagram and package selections. Two consecutive scripts/vendor.py beautiful-mermaid runs produce the same bytes, so the bundle still reproduces from the script. Pre-commit passes over every changed file. PR CI is the authority on the everyday suite.

The patch itself is excluded from pre-commit's hooks, for the reason examples/pr-walkthrough.patch already is: trailing-whitespace trims the leading space off a unified diff's blank context lines, which edits the patch rather than its whitespace.

Beautiful Mermaid has no statement continuation, so a label split across
two lines is read as a bare id plus a fresh statement, silently. The widget
now refuses that source, and the refusal reaches version check --render
through the existing fail-soft reading.

Closes #859

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard reads two of Mermaid's three label forms, and the omission cuts both ways.

A node label opens on a shape delimiter and a pipe edge label on a pipe, but the --/-./== edge-text form — the parser's own /^(<)?(--|-\.|==)\s+(.+?)\s+(-->|---|\.->|-\.-|==>|===)/, in the bundled beautiful-mermaid.esm.js beside the shape table the comment quotes — is not a label the walk knows.

It refuses two sources that render today. A -- pay(cash --> B draws an edge labelled pay(cash; the walk reads pay( as an opening, finds no ) on the line, and throws. A -- "a|b" --> B draws a|b and is refused on the unpaired pipe. Both are the case this PR deliberately keeps renderable for node labels — A[call foo(bar] and A[5" pipe] are two of its four controls — in the one form where there is no closed label to walk past.

And it passes the bug it is against. A -- first / second --> B renders a node A, a node second, and an edge between them: the reported symptom exactly, silent, with no refusal. The dotted and thick variants behave the same.

The rule the guard states is that a label closes on the line that opens it, so the edge-text label belongs in the walk on the same terms: open on --/-./== followed by whitespace, close on the terminator the parser accepts for that opener. That removes both false refusals and adds the three split edge-label shapes to what is caught. I'm pushing that to this branch, with the two refused sources added as controls and a split edge label added as a refusal fixture.

Evidence

Each source rendered directly through the vendored renderer (renderMermaidSVG, no Leaf guard), reading the <text> content out of the SVG:

source renders today as
flowchart LR\n A -- pay(cash --> B ["pay(cash", "A", "B"]
flowchart LR\n A -- "a|b" --> B ["a|b", "A", "B"]
flowchart LR\n A -- first\nsecond --> B ["A", "second", "B"]

Replaying the amended guard over every lf-diagram body in the tree — 85 of them — still refuses only this PR's four new fixtures, so no shipped diagram changes either way.

The guard read a node's shape delimiter and an edge's pipes as label
openings and nothing else, so the text a link carries between `--`, `-.`
or `==` and its terminator was outside the walk. That cut both ways: an
unpaired delimiter inside one read as an opening with no closer, refusing
`A -- pay(cash --> B` and `A -- "a|b" --> B`, which render today; and a
link label split across two lines opened nothing, so the statement the
guard exists to refuse passed it.

Open on a link that is followed by whitespace — the parser's own
condition for reading text rather than an arrow — and close on the
terminator set it accepts for that opener. The closers become patterns
rather than single characters, which the link's `-->|---|.->|-.-|==>|===`
needs and the other two forms read unchanged.

The two refused sources join the test's controls, and a split link label
joins its refusals.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rejectUnclosedLabel runs ahead of rejectCutLabel, so it now answers a source the older guard already diagnosed, and answers it wrong. A -->|"a|b"| B is one line with no split label. The walk opens on the edge label's pipe and closes it at the inner one — which is the parser's own reading, (?:\|([^|]*)\|)? — then takes the trailing | as a second opening with no closer. So the author is now told "a label must close on the line that opens it … carry a second line inside the label with <br/> or \n", where before this branch they were told "a label cannot hold |, the delimiter that closes its own shape". <br/> does not help them; dropping the pipe does. The PR added A -- "a|b" --> B as a control precisely because a pipe inside label text is a case worth keeping right, and this is that same content in the other edge-label form.

Ordering is the whole fix. rejectCutLabel needs both quotes on one line (/"([^"\n]*)"([\])}|>/\\]*)/g), so it stays silent on all five split-label fixtures and speaks first only where it holds the accurate answer. I'm pushing the swap, with the pipe form added to the cut-label test's refusals.

Separately, the new comment justifies the graph/flowchart gate with "a state, class, or ER body opens a brace on one line and closes it on another". This bundle reads two grammars, not four: it exports renderMermaidSVG alone, dispatches on /^stateDiagram(-v2)?\s*$/i, and otherwise requires ^(?:graph|flowchart)\s+(TD|TB|LR|BT|RL)\s*$. A class or ER body throws Invalid mermaid header rather than rendering, so the gate is right for the state body and for nothing else. Narrowing that sentence in the same push.

What the walk still misses, for whoever takes the layer above

The PR names the layer it does not reach — Leaf mirroring Mermaid's grammar one divergence at a time — and this is the evidence for where that costs. The walk models label grammar, while the silent fault is the parser's bare-id fallback swallowing any statement it cannot read. So an unsupported arrowhead lands on both sides of the guard: A --o B still falls to that fallback and draws a lone A with no refusal, and A -- text --o B is refused with the label message even though its fault is the arrowhead. Neither is supported by this bundle — its flowchart arrow set is -->|-.->|==>|---|-\.-|=== and the edge-text terminators are -->|---|.->|-.-|==>|===, with --o/--x reaching only the class-diagram code the bundle never dispatches. A guard written against the fallback rather than against labels would cover both, and every future divergence, from one table.

Replaying the guard over the 89 lf-diagram bodies in examples/, docs/, skills/, and tests/ refuses only this PR's five fixtures, so no shipped diagram moves either way.

`A -->|"a|b"| B` is one line holding a pipe the edge label cannot carry,
and the cut guard has said so since #312. The label walk ran ahead of it
and reached the trailing pipe first, so the author was told to carry a
second line with `<br/>` when their label was already on one line. Run
the cut guard first: it needs both quotes on one line, so it stays silent
on every split-label source and speaks only where it holds the answer.

The walk's comment also named class and ER bodies among the grammars the
`graph`/`flowchart` gate protects. This renderer reads two grammars —
`stateDiagram` and the flowchart — and throws `Invalid mermaid header`
on anything else.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The walk reads three of the renderer's four label openers. The asymmetric shape is the fourth, and the omission costs the same two ways the first round's did.

Beautiful Mermaid's node table has a non-bracket shape beside the ones the walk knows — /^([\w-]+)>(.+?)\]/ in the bundled beautiful-mermaid.esm.js, sitting between A[\text/] and A{{hex}}. LABEL_OPENING's shape class is [[({], so a > never opens a label.

It refuses a source that renders today. A>call foo(bar] --> B[plain] draws a node labelled call foo(bar pointing at plain. The walk does not see A> open anything, so it reads foo( as the opening, finds no ) on the line, and refuses. That is the case this PR keeps renderable everywhere else — A[call foo(bar] and A -- pay(cash --> B are two of its controls — failing in the one shape whose closed label is not walked past.

And it passes the bug it is against. A>first line / second line] --> B[plain] renders a node A beside a node second: #859's symptom exactly, silent, no refusal.

One opener closes both. A > opens a label wherever it is not an arrowhead, and -, . and = are the characters every arrow in this bundle's set puts before one — so (?<![-.=])> separates A>flag] from A[x]-->B[y], and ] closes it. Adding > to the shape class instead would not work: [\w-]* spans the - in A-->B, so the id would swallow the arrow shaft and take its head as a shape. I'm pushing that to this branch, with the refused source added as a control and the split asymmetric label added as a refusal fixture.

Evidence

Each source rendered directly through the vendored renderer (renderMermaidSVG, no Leaf guard), reading the <text> content out of the SVG:

source renders today as
flowchart LR\n A>call foo(bar] --> B[plain] ["call foo(bar", "plain"]
flowchart LR\n A>flag] --> B[plain] ["flag", "plain"]
flowchart LR\n A>first line\nsecond line] --> B[plain] ["A", "second"]

Replaying the amended guard over every lf-diagram body in the tree — 87 with this PR's fixtures — refuses only this PR's six, and the five the branch already refused are unchanged. A-->B, A[x]-->B[y] and A-B>flag] --> C stay accepted, so the new opener adds no false refusal on the spaceless arrow forms.

Beautiful Mermaid's node table has one shape that does not open on a
bracket: `/^([\w-]+)>(.+?)\]/` draws `A>flag]`. The walk's shape class was
`[[({]`, so a `>` opened nothing, and the omission cost both ways the walk
is there to prevent. `A>call foo(bar] --> B[plain]` renders a node labelled
`call foo(bar`, and the walk refused it because `foo(` was the first opening
it recognised — the same false refusal `A[call foo(bar]` and
`A -- pay(cash --> B` are controls against. `A>first` cut across two lines
rendered a node `A` beside a node `second`, silently, which is the fault
this branch is against.

A `>` opens a label wherever it is not an arrowhead, and `-`, `.` and `=`
are the characters every arrow in this bundle's set puts before one, so
`(?<![-.=])>` is the opener and `]` closes it. Adding `>` to the shape class
instead would read `A-->B` as a shape: `[\w-]*` spans the shaft and leaves
the head as the delimiter.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment's justification for the FLOWCHART_HEADER gate is false, and it was true before this branch narrowed it.

This bundle dispatches on the first line to six grammars, not two. _Fn returns xychart, sequence, class, er, or flowchart, and only the last of those reaches the stateDiagram-versus-flowchart split the comment describes; renderMermaidSVG's own switch has a case for each. Rendered directly through the vendored bundle, classDiagram, erDiagram, sequenceDiagram and xychart-beta bodies all produce SVG. The reference paragraph this PR edits says the same thing in its first sentence — "Use lf-diagram for flows, state machines, sequences, class relationships, ER schemas, and small XY plots". Commit e461e2d replaced "a state, class, or ER body" with "a stateDiagram body — the one other grammar this renderer reads", which is the sentence that is wrong.

The gate itself is right: the walk models flowchart label grammar and every other grammar is skipped. But the comment is the only stated reason the gate exists, so the next reader deciding whether to widen it — or writing the guard for the next divergence this layer refuses one at a time — works from an inventory missing four grammars. The PR body carries the claim too, and a squash lands that body as main's commit message.

The reference sentence inherits the same scope error. "Every statement ends at the newline, so a label is single-line and one that does not close on the line that opens it is refused" sits in the paragraph covering all six grammars, while the refusal is gated on graph/flowchart. An author writing class Order { on one line and } on the next reads a prohibition the widget does not enforce.

Pushing both corrections and the PR-body fix.

How the dispatch reads

In skills/leaf/packages/diagram/vendor/beautiful-mermaid.esm.js, the entry point takes the diagram type before any header check:

function _Fn(m){let T=m.trim().split(/[\n;]/)[0]?.trim().toLowerCase()??"";
  return /^xychart(-beta)?\b/.test(T)?"xychart"
    :/^sequencediagram\s*$/.test(T)?"sequence"
    :/^classdiagram\s*$/.test(T)?"class"
    :/^erdiagram\s*$/.test(T)?"er":"flowchart"}

and XFn — exported as renderMermaidSVG — switches on it, with zPn's /^stateDiagram(-v2)?\s*$/i test reached only in the default branch. Rendering each body and reading the <text> content out of the SVG:

source renders as
classDiagram\n class Order {\n +int id\n }\n Order --> Item ["Order", "+ id: int", "Item"]
erDiagram\n CUSTOMER ||--o{ ORDER : places ["CUSTOMER", "(no attributes)", "ORDER", "(no attributes)", "places"]
sequenceDiagram\n Alice->>Bob: hi ["hi", "Alice", "Bob"]
xychart-beta\n title "T"\n bar [1, 2, 3] ["1", "2", "3", …]

The comment justified the `graph`/`flowchart` gate with "a `stateDiagram`
body — the one other grammar this renderer reads". The bundle takes its
grammar from the first line before any header check: `_Fn` returns
`xychart`, `sequence`, `class` or `er`, and only its `flowchart` fallback
reaches the `stateDiagram`-versus-flowchart split. `classDiagram`,
`erDiagram`, `sequenceDiagram` and `xychart-beta` bodies all render.
`references/authoring-evidence.md` says so in the same paragraph this
branch edits — `lf-diagram` is for "flows, state machines, sequences,
class relationships, ER schemas, and small XY plots" — so the comment was
the one place claiming otherwise, and it is the only stated reason the
gate exists.

The reference sentence carried the same scope error: "Every statement ends
at the newline" sits in the paragraph covering all six grammars, while the
refusal is gated on `graph` and `flowchart`, so a `class Order {` block
read as forbidden something the widget does not refuse.

Comment and prose only; the walk is unchanged.
@max-sixty

Copy link
Copy Markdown
Owner

Is there no way to compute whether a diagram is valid? Do we need to create our own regex?

This is exactly the sort of code that I would like to avoid having in Leaf itself...

@leaf-agent

Copy link
Copy Markdown
Collaborator Author

Yes, it is computable, and you're right that the computation doesn't belong here.

Why nothing computes it today. Beautiful Mermaid's flowchart parser is total. consumeNode falls back to BARE_NODE_REGEX = /^([\w-]+)/, and parseEdgeLine simply breaks when it can't advance, so every unreadable line has a defined silent reading and the returned MermaidGraph cannot tell a statement that was read from one that was guessed. That is why each divergence has needed its own guard: from outside, there is nothing to test.

The parser does compute the fact, though. parseEdgeLine walks a line left-to-right carrying remaining, and at the three points where it gives up it drops that leftover on the floor. The leftover is the whole validity signal — text the renderer never read.

What it would take. Upstream already exports parseMermaid publicly (it's in dist/index.d.ts); our vendor entry re-exports only renderMermaidSVG, at scripts/vendor.py:282. So if the parser reported its leftovers, the entire Leaf side is one more name in that entry plus:

const { unread } = parseMermaid(source);
if (unread.length) throw new Error(`the renderer did not read: "${unread[0]}"`);

That replaces all three guards in lf-diagram.js — UNSUPPORTED_DIRECTIVE, rejectCutLabel from #312, and this PR's rejectUnclosedLabel — with one rule, and costs no bytes: parseMermaid is already inside the 1.5MB bundle, just not exported.

Measured, not assumed. I patched a copy of upstream src/parser.ts — five touched lines, pushing remaining at the three points it gives up — bundled it with esbuild and ran it:

source leftover reported
the six line-split shapes this PR refuses all six
#312's cut label, and the cut edge label both
click / accTitle / accDescr all three
A --o B — the unsupported-arrowhead class this PR says it does not reach yes
ten flowchart controls that must keep rendering (A[5" pipe], A[call foo(bar], A -- pay(cash --> B, A[["names: list[str]"]], subgraph S["Stage [1]"], the <br/> form, …) none

It also catches one we ship broken. A-->B, with no space before the arrow. [\w-]+ eats the hyphens, so against the bundle on main today that draws a single box labelled A--, no edge, no error:

$ node -e 'import(".../beautiful-mermaid.esm.js").then(...)'
data-ids: [ 'A--' ]
text:     [ 'A--' ]

That's upstream lukilabs/beautiful-mermaid#140. This PR's test lists A-->B among the sources that "stay accepted" — it does render, wrongly. No amount of label grammar would have found it, which is the argument against the approach in one line: a hand-written guard can only refuse the divergences someone already noticed, and here it enshrined one of them as a control.

So I don't think this should merge. The fix is five lines in the parser, not ninety in the widget.

What I can't do on my own. Beautiful Mermaid is MIT and takes outside PRs freely — a dozen are open, and TEXT_ARROW_REGEX in its own source credits one — but it publishes no contributing policy, no bot files issues there, and nothing on its CI runs a coding agent — which is the bar my scope rule wants before I post in someone else's repo unasked. So I'd like your word on one of:

  1. File it upstream — an issue, or an issue plus the patch as a PR, with the evidence above.
  2. Standing permission — I record in running-tend that I may file upstream in a dependency we vendor without asking each time, and go ahead now.

Either way #859 stays open until the fix lands. If you want something in the meantime, the honest option is a Leaf-owned patch applied during the bundle build — scripts/vendor-src/pierre/ is already that shape — rather than a grammar in the widget; it's five lines that delete themselves when upstream takes them. I'd rather wait than ship either, but that's your call.

Corpus replay

Over every lf-diagram body in examples/, docs/, skills/ and tests/ — 87, the same set the PR description counts — the leftover check flags 12. Every one is a refusal fixture in tests/test_render_pages.py: the nine the two label guards own, plus the click, accTitle and accDescr fixtures. 61 parse with nothing left over, and 14 never reach the flowchart parser at all (sequenceDiagram, classDiagram, erDiagram, xychart-beta, pie, gantt). No shipped diagram in examples/, docs/ or skills/ is affected.

The patch, against [email protected] src/parser.ts:

-  if (!firstGroup || firstGroup.ids.length === 0) return
+  if (!firstGroup || firstGroup.ids.length === 0) { UNREAD.push(remaining); return }
...
-      if (!textMatch) break
+      if (!textMatch) { UNREAD.push(remaining); break }
...
-    if (!nextGroup || nextGroup.ids.length === 0) break
+    if (!nextGroup || nextGroup.ids.length === 0) { UNREAD.push(remaining); break }

I instrumented the flowchart parser only. A shipped version would hang the array off the graph rather than a module global, and the state-diagram parser gives up in the same shapes.

@max-sixty

Copy link
Copy Markdown
Owner

Can we vendor it here, mark it as such; and then we're not maintaining it?

The four guards this replaces each refused one divergence from Mermaid proper
that somebody had noticed — the unsupported directives, a label cut at its own
closer, a label split across two lines, and the two false refusals the split-label
walk introduced on the way. Each one restated a rule Leaf does not own, and the
next divergence stayed silent: `A --o B` drew a lone node, and `A-->B` — upstream
lukilabs/beautiful-mermaid#140 — drew one node named `A--` while the branch's own
test listed it as a source that renders.

The parser is the only thing that knows what it read, and it was throwing that
away. `scripts/vendor-src/beautiful-mermaid/report-unread-text.patch` has it keep
the leftovers at the four points it gives up, and exports one function that
answers them for a source; `vendor.py` applies it and bundles upstream's published
`src/` rather than its `dist/`. The widget refuses on that reading alone and drops
90 lines of grammar.

The patch is Leaf's, stated as a patch so it stays upstream's code with a named
change to it: a pin that moves the lines it names fails the build, and a release
that carries the reading deletes it.

`.pre-commit-config.yaml` excludes `scripts/vendor-src/*.patch` from the hooks for
the reason `examples/pr-walkthrough.patch` is already excluded — trailing-whitespace
trims the leading space off a unified diff's blank context lines, which edits the
patch rather than its whitespace.

The three diagram-refusal tests become one, because there is now one rule. It
covers the fourteen refusals — the twelve those tests held plus the arrowhead and
the spaceless arrow — and fourteen controls, each asserted on the text the renderer
stopped at.
@leaf-agent leaf-agent changed the title Refuse a diagram label that does not close on the line that opens it Refuse a diagram source the renderer does not read whole Sep 19, 2026
@leaf-agent

Copy link
Copy Markdown
Collaborator Author

Yes — done, and it's better than what I offered. Pushed as dd687ace; the PR title and description are rewritten around it.

The patch is scripts/vendor-src/beautiful-mermaid/report-unread-text.patch: a unified diff against upstream's own source, with a header saying what it changes and when it goes away, applied at build time by vendor.py (which now bundles upstream's published src/ rather than its dist/). Leaf's side is one call — refuseUnreadStatements(unreadMermaidText(source)) — and all four grammar guards are deleted, rejectCutLabel from #312 included. So there is no Mermaid grammar left in Leaf to maintain: a pin that moves the lines the patch names fails the build rather than the page, and a release that carries the reading deletes the patch file and one name in vendor.py's entry.

Two divergences none of the guards knew about are now refused: A --o B, and A-->B with no space before the arrow — the one this branch's own test listed as a source that renders, which upstream has open as beautiful-mermaid#140.

One thing worth your eye before merging, since it is a real loss. The refusal now names the text the renderer stopped at rather than diagnosing it: an author who split a label across two lines gets the renderer does not read this, and would draw the diagram without it: "["first line" where the deleted guard said "carry a second line inside the label with <br/>". I moved that guidance into references/authoring-evidence.md, so an author meets it while writing rather than after being refused, and I'd rather have the always-correct refusal than a widget that is articulate about three cases and silent about the rest — but it is a trade, not a free win.

I still have no permission to file upstream, so the patch stays Leaf's for now. Say the word and I'll open the issue and the PR there with the evidence.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

authoring-evidence.md now tells page authors that the widget refuses any source this renderer would read only part of. That holds for two of the six grammars the same paragraph advertises.

unreadMermaidText returns [] unless detectDiagramType(decoded) === 'flowchart', so a sequence, class, ER, or XY source is never checked — and those parsers drop what they cannot read exactly as the flowchart parser does. Rendered through the vendored bundle on this branch:

source drawn unreadMermaidText
erDiagram with ORDER ~~bogus~~ SHIPMENT : ships CUSTOMER, ORDER — LINE_ITEM and SHIPMENT absent []
classDiagram with note for Order "hello" Order, Item — no note []
sequenceDiagram with Bob ~> Dave: what Alice, Bob — Dave absent []

That is #859's symptom in four grammars, and the sentence this PR deleted is the one that covered it: "A malformed statement the renderer does not recognise can still render as a node or only in part, and version check --render reports renderer failures, not that partial output, so look at each flowchart once." An author writing an ER schema now reads that version check --render reports the statement, and it does not.

The scope is the right one to ship — the remaining four parsers are one graph.unread.push each now that the patch, the export, and the widget call all exist, so this leaves that problem easier than it found it. What it cannot do is claim them. The widget comment reads the same way: "a Leaf-owned patch to upstream's parsers … that records the text each one walked away from" is the whole set, where the patch file's own header says "flowcharts and state diagrams" and is right.

Pushing both corrections — the reference scoped to the two grammars the reading covers with the partial-drawing warning kept for the other four, and the widget comment narrowed to match its patch.

Verification

uv run pytest tests/test_render_pages.py::test_a_source_the_renderer_does_not_read_whole_is_refused -q -n0 passes on the merged tree, as does -k diagram over that file (5 passed).

Replaying unreadMermaidText over the lf-diagram bodies in examples/, docs/ and skills/ reports leftovers for none of them, so no shipped page changes.

State-diagram coverage is real and new: note right of Idle: waiting, classDef/class, and state X <<fork>> each report their line, and each was silently dropped before. A composite-state body reports nothing.

The patch instruments the flowchart and state-diagram parsers, and `unreadMermaidText` returns an empty list for every other diagram type. The reference told authors the widget refuses any source the renderer reads only part of, and deleted the sentence that had covered the four grammars it does not reach: a sequence, class, ER or xychart source still drops a statement its parser cannot read and draws the rest, with nothing reporting it. Scope that claim, restore the warning for those four, and narrow the same over-reach in the widget comment, `vendor.py`'s docstring, and `scripts/CLAUDE.md`.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR's opening paragraph is the right frame for this, and the estimate this commit scopes onto the remaining four parsers contradicts it. "Every statement they cannot read has a defined silent reading — the flowchart's consumeNode falls back to BARE_NODE_REGEX and takes the leading word" is exactly why a push at a give-up point is the instrument that works. Two of those four parsers have no such point.

The class parser guesses where the flowchart parser gives up. Its member reader returns null only for an empty line; for anything else it strips a leading visibility character, tries /^(.+?)\(([^)]*)\)(?:\s*(.+))?$/, and otherwise splits on whitespace and returns a member built from the pieces. So a line inside a class X { … } body is never left unread — it is drawn. class Order { ~~bogus~~ / +int id } with an Order --> Item edge renders ["Order", "~ ~bogus~~", "+ id: int", "Item"]. That is BARE_NODE_REGEX in the member position, and reaching it is a change to that fallback, not a push at a point that gives up.

The ER parser gives up in two places, not one. Its attribute reader returns null for any line that isn't /^(\S+)\s+(\S+)(?:\s+(.+))?$/, and the entity-body branch continues on that null before the loop end is ever reached. ORDER { bogus / string name } drops bogus and draws the rest. Sequence and xychart are the one-push shape the sentence describes; class and ER are not.

The cost lands on whoever takes the widening, and on page authors. scripts/CLAUDE.md is the instruction file for exactly that task and now sizes the class parser as a push. And references/authoring-evidence.md inherits the same model — "its parser drops a statement it cannot read and draws the rest … simply missing from the drawing" sends an author looking for an absence, where the class case is a present-but-garbled member they have to recognise as wrong.

Pushing the corrections to all three, and to the PR body, which a squash lands as main's commit message.

Evidence

Rendered through the vendored bundle on this branch, reading unreadMermaidText and the <text> content of the SVG:

source unreadMermaidText drawn
classDiagram / class Order { / ~~bogus~~ / +int id / } / Order --> Item [] ["Order", "~ ~bogus~~", "+ id: int", "Item"]
erDiagram / ORDER { / bogus / string name / } / ORDER ||--o{ LINE : has [] ["ORDER", "string", "name", "LINE", "(no attributes)", "has"] — identical to the same source without bogus

The two grammars the patch does reach hold up on the same probe. In a flowchart, A[x] --> B[y] extra reports ["extra"], click A "http://e" reports its argument, A --o B reports ["--o B"]; in a stateDiagram, note right of A: waiting and state fork_state <<fork>> each report their line, and blank lines, %% comments, classDef/style/linkStyle and a subgraph direction report nothing. pie and gantt throw the same Invalid mermaid header from unreadMermaidText as from renderMermaidSVG, so the refusal path for those is unchanged.

The scope note put the remaining four parsers on one footing: "the same
`unread.push` at the point it gives up". That holds for sequence and xychart,
whose loops drop an unreadable line at the end. The ER parser gives up a second
time inside an entity body, where an attribute line that is not `type name` is
dropped before the loop end is reached. And inside a `class` body nothing gives
up at all: the member reader returns null only for an empty line and otherwise
splits whatever it was given into a member, so `~~bogus~~` draws as `~ ~bogus~~`
rather than going unread. That is the flowchart's `BARE_NODE_REGEX` in the
member position — the shape this patch exists to answer — so reaching it is a
change to the fallback, not a push at a point that gives up.

State that in `scripts/CLAUDE.md` and the widget comment, where the next reader
sizes the work. In `references/authoring-evidence.md` the same model sent an
author looking for an absence: correct it to say that a class or ER body has to
be read for what it drew, not only checked for what is missing.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reading is gated on the source detecting as a flowchart; the directive guard it replaces was not gated at all, so this narrows a refusal in the other four grammars without saying so.

UNSUPPORTED_DIRECTIVE matched /m over the raw source with no header check, so click X, accTitle: and accDescr were refused whatever the first line said. unreadMermaidText returns [] unless detectDiagramType answers flowchart, so in a classDiagram those lines now reach the class parser — and its inline-attribute pattern /^(\S+?)\s*:\s*(.+)$/ reads one as a class of its own. Rendered through this branch's bundle:

source unreadMermaidText drawn
classDiagram / accTitle: Checkout flow / A --> B [] ["accTitle", "flow: Checkout", "A", "B"]
classDiagram / accDescr: some text / A --> B [] ["accDescr", "text: some", "A", "B"]
the same in erDiagram, sequenceDiagram, xychart-beta [] directive dropped, rest drawn

A box labelled with its own keyword, silently — the symptom the deleted comment named, in the grammar the old regex happened to cover.

The scope is still the right one to ship, and the remedy is not a regex back in the widget: that is the code this PR exists to delete. What is missing is the claim. The PR body's only stated cost is the refusal's wording, and a squash lands that body as main's commit message. references/authoring-evidence.md has the same gap from the author's side — its model for the other four grammars is a statement "missing from the drawing", plus a member inside a class body "drawn however the parser managed to split it". A top-level directive that invents a whole class is neither, so an author checking a class source is sent looking for an absence.

Pushing both corrections.

Verified, and what this pass refuted

Every other claim the branch makes about the vendored parsers holds, checked against upstream [email protected] src/:

  • The class parser's parseMember returns null only for an empty trimmed line, so nothing inside a class body gives up — scripts/CLAUDE.md and the widget comment are right that reaching it means changing the fallback.
  • The ER parser's parseAttribute returns null on any line that isn't /^(\S+)\s+(\S+)(?:\s+(.+))?$/, and the entity-body branch continues past it before the loop end — the second give-up point, as stated.
  • sequence/parser.ts and xychart/parser.ts are each one flat loop of continues falling off the end — one push, as stated.
  • The build does fail on pin drift rather than the page: patch -p1 --batch --forward exits 1 both on re-application and on a moved context line, and run() passes check=True.
  • unreadMermaidText calls parseMermaid(decodeXML(text)), which is exactly what renderMermaidSVG's flowchart branch does, so the checked reading and the drawn one cannot diverge. Empty mermaid diagram and Invalid mermaid header now raise from the check rather than the render, with the same message into the same failSoft.

Moving the check behind loadRenderer() means a refused diagram now pays the 1.5MB import first. That is inherent — the parser is the checker — and not worth working around.

`UNSUPPORTED_DIRECTIVE` matched over the raw source with no header check, so
`click`, `accTitle` and `accDescr` were refused whatever the first line said.
The reading that replaced it is gated on the source detecting as a flowchart, so
those directives now reach the other four parsers — and a class diagram reads
`accTitle: Checkout flow` through its inline-attribute pattern and draws a box
named `accTitle` carrying a member, which is the box-labelled-with-its-own-keyword
symptom the deleted guard was written against.

Restoring the refusal would put a regex back in the widget, which is the code
this change exists to delete. So name it instead, in the paragraph an author
reads before writing: the directives are a flowchart and `stateDiagram` rule,
and a class or ER source has to be read for what it drew rather than only
checked for what is missing.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reading instruments every point where a parser gives up. That is a complete account of under-reading and no account of the opposite: a parser that reads past a statement leaves nothing over, so unreadMermaidText returns [], the widget accepts, and the page draws the part that was read — #859's symptom, in the grammar this branch says is covered.

A[/a/] --> B[\b\] under flowchart LR draws one box, labelled a/] --> B[\b. B and the edge are gone, and nothing is reported anywhere. A slanted shape's label runs to the next closer matching its opener wherever that falls, so a [/… or [\… opener followed later on the same line by the matching \] or /] swallows everything between — four of the twenty-five ordered pairs of this renderer's five bracket shapes. Two paragraphs above the claim in authoring-evidence.md, "Flowcharts accept Mermaid's classic node shapes" is what sends an author there.

Three places state the claim without that limit, and I'm pushing the scoping to each:

  • references/authoring-evidence.md — "refuses any source this renderer would read only part of" becomes the reading it actually is, a source whose parser stopped reading, with the over-read case and its one-node-per-line workaround named where an author meets it rather than after a refusal that never comes.
  • packages/diagram/widgets/lf-diagram.js — "every statement the checked parsers saw was read whole" becomes "no parser gave up", and says that catching the mirror case is a change to those shape patterns rather than another push at a give-up point.
  • test_a_source_the_renderer_does_not_read_whole_is_refused — the docstring claims the whole of it in its first line.

Two things I am deliberately not doing. No fixture for the over-read: asserting today's one-box drawing would pin the bug rather than a behaviour. And no fix — anchoring the parallelogram pattern so its label cannot span an arrow is a few regexes in upstream's source, but the patch's own header promises "No statement reads differently and no drawing changes", and an over-read fix breaks that, changes drawings, and rebuilds the bundle. Whether the patch is a reporting patch or a correcting one is the design call you already weighed once in this thread, so it stays with you.

Second correction in the same push. accTitle: and accDescr: are not refused in a stateDiagram, where 73c4aa2 says they are. The state parser reads either as its own id : label statement, so accTitle: Checkout flow draws a loose state labelled Checkout flow and unreadMermaidText returns []. Only click is refused there. UNSUPPORTED_DIRECTIVE caught all three in every grammar, so this is the narrowing the PR body already names for class diagrams, one grammar further in — and the state-diagram case is the worse of the two to meet, because the phantom box carries the title the author wrote rather than the keyword.

Everything else on the branch holds on this pass: no stale reference to the four deleted guards, the notices file is built from the node_modules manifests rather than the bundle so building from src/ does not touch it, and pytest tests/test_render_pages.py -k diagram -n0 plus the refusal test itself are green with the prose corrections applied.

The over-read, measured

Each source rendered through the vendored bundle on this branch, reading data-id and <text> out of the SVG beside unreadMermaidText:

source unreadMermaidText ids drawn label on A
A[/a/] --> B[/b/] [] A, B /a/
A[/a/] --> B[\b\] [] A a/] --> B[\b
A[/a/] --> B[/b\] [] A a/] --> B[/b
A[\a\] --> B[/b/] [] A a\] --> B[/b
A[\a\] --> B[\b/] [] A a\] --> B[\b
A[/a/] --> B[\b\] --> C[c] [] A, C a/] --> B[\b

The other nineteen pairs draw both nodes. The trigger is an opener this renderer does not implement as a shape: [/…/] and [\…\] fall through to the plain rectangle pattern and keep their slashes as label text — A[/a/] --> B[/b/] above draws a box labelled /a/ — so the parallelogram patterns, [/…\] and [\…/], are free to match from that opener across the arrow to a later node's closer. Declaring the node on a line of its own and putting the bare id in the edge renders both: A[/a/] / B[\b\] / A --> B draws /a/ and \b\.

Nothing shipped is affected — no lf-diagram body in examples/, docs/, skills/ or tests/ uses a slanted shape.

The directive matrix
header directive unreadMermaidText drawn
flowchart LR accTitle: Checkout flow [": Checkout flow"] refused
flowchart LR accDescr: some text [": some text"] refused
flowchart LR click A "http://e" ["A \"http://e\""] refused
stateDiagram-v2 accTitle: Checkout flow [] Checkout flow, Idle
stateDiagram-v2 accDescr: some text [] some text, Idle
stateDiagram-v2 click A "http://e" ["click A \"http://e\""] refused

The state node's data-id is accTitle, so it is the id : label reading, not a dropped line.

`unreadMermaidText` is instrumented at every point a parser gives up, which
accounts for under-reading and not for its mirror. A parser that reads past a
statement leaves nothing over, so the reference, the widget comment and the test
docstring each promised a refusal the reading cannot make: `A[/a/] --> B[\b\]`
draws one box labelled `a/] --> B[\b`, with `B` and the edge gone and an empty
reading, because a slanted shape's label runs to the next closer matching its
opener wherever that falls. Say what the reading is — no parser gave up — and
name the over-read where an author meets it, with the one-node-per-line form
that renders both.

No fixture for it: asserting today's one-box drawing pins the bug rather than a
behaviour. Anchoring the parallelogram patterns so a label cannot span an arrow
is the fix, and it changes what a statement reads as, which the patch's header
promises it does not do.

The directive sentence was wrong the same way. `accTitle:` and `accDescr:` are
not refused in a `stateDiagram`: the state parser reads either as its own
`id : label` statement and draws a loose state labelled with the text after the
colon, `data-id` and all. Only `click` is refused there.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A --> B; draws exactly the diagram the author wrote, and the widget now refuses the page.

The flowchart parser treats a trailing semicolon as end of statement and ignores it, so the two sources render byte-identically — flowchart LR / A[Start] --> B[End] and the same line with a ; both produce the same 2,723-byte SVG. But the ; is what parseEdgeLine is holding in remaining when its loop stops advancing, so the patch pushes it, unreadMermaidText answers [";"], and the widget throws the renderer does not read this, and would draw the diagram without it: ";" — where the diagram without it is the right diagram. version check --render fails a page whose drawing is complete and correct, and the message names a character the author cannot act on. That also falsifies the body's "a general, always-correct refusal", which a squash lands as main's commit message.

None of the 79 lf-diagram Mermaid bodies in the tree carries a trailing ;, so nothing shipped breaks. It is about the next page: the semicolon is Mermaid's own statement terminator, and an agent writing from Mermaid's documentation rather than from this subset writes one.

Two ways out, and choosing between them is the question you already raised on this thread:

  • Read it. A trailing ; in a flowchart is already read-and-discarded, so the patch consumes it where the line is normalized. No drawing changes and no statement reads differently, which is exactly what the patch header promises — but it is one more line of Mermaid grammar in Leaf's patch.
  • Refuse it and say so. This renderer implements no semicolon anywhere: in a stateDiagram, [*] --> A; leaves the whole line unread and draws nothing at all. A uniform refusal is coherent, and then authoring-evidence.md has to name the terminator among what is refused and the test needs it as a fixture — it currently has it as neither.

I am not pushing either one. The first adds grammar to the patch you asked Leaf not to own, and the second decides that a correct drawing may be refused; that is your call, not the reviewer's.

Two corrections I am pushing to this branch:

  • The patch's own doc comment still carries the claim da8bcc34 corrected everywhere else. unreadMermaidText's JSDoc says "An empty list means every statement was read whole" — the sentence that commit replaced in the widget comment, the reference and the test docstring, left standing in the fourth place, which is the export's contract and the text that goes upstream if the patch ever does. Rewritten to "no parser gave up", at the same line count so the hunk still applies — verified with patch -p1 --batch --forward --dry-run against [email protected]. esbuild strips the comment, so the bundle is unchanged and needs no rebuild.
  • A stateDiagram now refuses classDef, class and style, and nothing says so. Only parseFlowchart matches those three; parseStateDiagram has no pattern for them, so they fall through to the new graph.unread.push(line). Two paragraphs above the refusal sentence, authoring-evidence.md tells an author to "Use classDef only for nodes that need to stand apart from that baseline" with no grammar caveat — so following the reference now takes a state-diagram page down. The PR body's narrowing paragraph names the three directives; this is a fourth, and the reference now names it.
Measured against this branch's bundle

Each source through the vendored beautiful-mermaid.esm.js at da8bcc34, reading data-id out of the SVG beside unreadMermaidText:

source unreadMermaidText drawn
flowchart LR / A[Start] --> B[End] [] A, B
flowchart LR / A[Start] --> B[End]; [";"] A, B — same SVG, byte for byte
flowchart LR / A[Start] --> B[End]; / B --> C[Done]; [";", ";"] A, B, C
stateDiagram-v2 / [*] --> A; ["[*] --> A;"] nothing
flowchart LR / A --> B / classDef hot fill:… / class A hot [] A, B
stateDiagram-v2 / [*] --> A / classDef hot fill:… / class A hot ["classDef hot fill:…", "class A hot"] _start, A
stateDiagram-v2 / [*] --> A / style A fill:#f00 ["style A fill:#f00"] _start, A

The corpus sweep: 79 lf-diagram bodies across examples/, docs/, skills/ and tests/ open on a Mermaid header, and none has a line ending in ;.

Everything else on this head holds. The head commit's three prose corrections are each true against the bundle — A[/a/] --> B[\b\] reports [] and draws one node labelled a/] --> B[\b, the one-node-per-line form draws both, and a stateDiagram refuses click while reading accTitle: and accDescr: as id : label statements. run() passes check=True, so a patch that stops applying fails the build as the docstring says. No stale reference to the four deleted guards survives anywhere in the tree.

Two claims the last commit left standing. `unreadMermaidText`'s doc comment is
the fourth place saying an empty list means every statement was read whole, and
the one that is the function's contract — the text a reader of the patch works
from, and the text that goes upstream if the patch ever does. It says what the
other three now say: no parser gave up.

And `classDef`, `class` and `style` are refused in a `stateDiagram`. Only
`parseFlowchart` matches them; the state parser has no pattern for any of the
three, so each falls through to the new push. The reference tells an author to
style with `classDef` two paragraphs above the refusal sentence, with no grammar
caveat, so following it took a state-diagram page down with nothing to read.

The comment is stripped from the bundle, so neither needs a rebuild; the hunk
keeps its line count and still applies to [email protected].
max-sixty added a commit to max-sixty/tend that referenced this pull request Sep 21, 2026
… human author (#1366)

A review of a PR with no human author pushes every fix it can
articulate, and each push queues another full review of the merged tree
from a fresh context. A fresh pass over a whole PR usually finds
something, so nothing ends the loop except a pass that finds nothing or
a fix small enough for the trivial-increment path.
max-sixty/leaf#860 ran nine finding rounds this
way at $4–7 each. Every session read the earlier reviews and knew the
round count, and used it only to dedup.

Step 9 of `review` now gives the session that context rather than a
count to enforce. The bar for another fix rises with each round: one
adjustment is often fine, and after a couple only a significant problem
(one that would do harm if the PR merged as it stands) earns a push.
When the rounds are thrashing, the session holds its own view of the
change with less confidence, leans the way the project leans, and says
in the review that the approach is what's in question.

Two supporting edits. "The only bar for deferring is that no defensible
default exists" becomes "Having to choose is a reason to defer only
when…", so the sentence still answers the "more than one valid form"
excuse without reading as an override of the rising bar. And the
**Self-authored PRs** paragraph, which a session reads when deciding
what to raise, points at **Push fixes** for which findings still earn a
push and which still go in the review. It names the section without
restating the bar, so a finding a maintainer should weigh is posted on a
late round even though it isn't pushed.

No behavioural eval ran; the skill tests and pre-commit pass.

> _This was written by Claude Code on behalf of max-sixty_

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
max-sixty added a commit that referenced this pull request Sep 21, 2026
Beautiful Mermaid's parsers are total: a statement they cannot read
still gets a reading, so a source the renderer only partly understands
draws a plausible, wrong diagram and reports nothing. `lf-diagram`
answered that with hand-written guards, each a slice of Mermaid grammar
kept beside the parser it second-guessed, and each refusing only the
divergence someone had already noticed (#312, #859, and the rounds on
#860).

Both libraries already describe what they found: official Mermaid in its
diagram database, Beautiful Mermaid in the `data-*` attributes of the
SVG it drew. `lf-diagram-fidelity.js` reads both into one shape and
reports where they differ, so Leaf holds the mapping between two
vocabularies and no grammar. It covers all six diagram types, and
because it compares against what was drawn it also catches a parser that
read too much.

Official Mermaid is too heavy for a reader's page, so the comparison
runs only in `version check --render`. `registerRenderCheck` is the
general form: a widget registers a check, the render gate alone calls
it, and what it finds arrives as that widget failing soft.
`mermaid-reader.esm.js` is official Mermaid 12.0.0 cut to the parts that
read (2.9MB, the undrawn dependencies aliased away in
`scripts/vendor.py`); it travels in the page directory beside the
renderer it answers for, and no reader's browser fetches it.

The contract for a diagram is now "valid Mermaid that Beautiful Mermaid
draws faithfully". Sources Mermaid refuses are refused even where the
renderer happened to draw them, unquoted parentheses in a label above
all; quoting the label is the fix. The same holds where Mermaid reads
less than the author meant: a line opening with `click` is a click
directive to it, so a node cannot be named `click`, which the deleted
guard had carved an exception for. A page never put through the render
gate draws whatever the renderer made of its source.

On a corpus of 59 misdrawn and 88 faithful sources measured before
building this, the comparison refused 54 of the 59 and falsely refused 1
of the 88.

## Where to look

- `skills/leaf/packages/diagram/widgets/lf-diagram-fidelity.js` — the
two readings and their comparison.
- `skills/leaf/assets/runtime/render-check.js`,
`render-checks/widgets.js`, `render_gate/readings.py` — the render-check
primitive and where the gate runs it.
- `skills/leaf/packages/diagram/widgets/lf-diagram.js` —
`UNSUPPORTED_DIRECTIVE` and `rejectCutLabel` are deleted; the widget
registers `checkDrawing`.
- `scripts/vendor.py` — the `mermaid-reader` bundle.
- `tests/test_render_gate.py` — one gate test over thirteen misdrawn
sources and ten faithful controls replaces the two browser tests for the
deleted guards.
- `examples/security-boundary.html` was itself misdrawn: a transition
named `S0` before `state "S0 · Gate passed" as S0` declared it, so the
box was labelled `S0`. The declarations now come first.

## Validation

- `uv run pytest tests/test_render_gate.py tests/test_render_pages.py -q
-n 4`: 164 passed, 1 failed —
`test_a_written_comment_keeps_its_originating_agent`, which fails the
same way on the merge-base `39d9cad0`.
- `uv run pytest tests -q`: 1212 passed. `npm run test:runtime`: 32
passed. `pre-commit run --all-files` clean.
- `version check --render` over the 21-page `examples/` corpus is clean
after the `security-boundary` fix.

Supersedes #860. Closes #859.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
@max-sixty

Copy link
Copy Markdown
Owner

Superseded by #899, which replaces the hand-written guards with a comparison against Mermaid's own reading of the source and deletes the code this PR extends.

This was written by Claude Code on behalf of max-sixty

@max-sixty max-sixty closed this Sep 21, 2026
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.

A quoted flowchart label spanning two lines renders as the node id plus a stray node, and version check --render passes it

2 participants