Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.
fix(import): select the Mermaid block before parsing it (#269)
Cathryn Lavery2489dfda550e
diff --git a/commands/import-mermaid.md b/commands/import-mermaid.mdindex 37bb43a..0334e84 100644--- a/commands/import-mermaid.md+++ b/commands/import-mermaid.md@@ -32,7 +32,7 @@ Accepts `.mmd`, `.mermaid`, and Markdown files containing fenced `mermaid` block- `--detail` — `faithful` (≤24 nodes, zoned), `balanced` (≤12), `simplified` (≤7).- `--audience` — `engineer`, `mixed`, `executive`. Governs wording, not element count.- `--type` — force a diagram type instead of inferring it.-- `--diagram` — diagram index or `all` (one file per block).+- `--diagram` — diagram index or `all` (one file per block). An index fails only if that block fails; other blocks that cannot be parsed are listed as `unparsed` in the header. `all` fails if any block fails.- `--variant` — `light`, `dark`, or `full` editorial template.- `--output` — output base path; the extension is appended per format.diff --git a/scripts/verify-mermaid-import.py b/scripts/verify-mermaid-import.pyindex 9384486..f44e91d 100644--- a/scripts/verify-mermaid-import.py+++ b/scripts/verify-mermaid-import.py@@ -668,6 +668,49 @@ CUSTOMER ||--o{ ORDER : placesok("Markdown selection plus sequence, state, and ER grammars parse")+def check_selection_before_parse(tmp: Path) -> None:+ """A malformed block fails only when it is selected (#209)."""+ bad_first = tmp / "bad-first-block.md"+ bad_first.write_text(+ "# doc\n\n```mermaid\nflowchart LR\nA -->\n```\n\n"+ "```mermaid\nflowchart LR\nC --> D\n```\n",+ encoding="utf-8",+ )+ payload = json.loads(run_extract([str(bad_first), "--diagram", "1", "--json"]))+ if payload["diagrams_total"] != 2:+ fail(f"diagrams_total must count every block: {payload['diagrams_total']}")+ if [(item["index"], item["kind"]) for item in payload["diagrams"]] != [+ (1, "flowchart")+ ]:+ fail("--diagram 1 did not return block 1 past a malformed block 0")+ digest = run_extract([str(bad_first), "--diagram", "1"])+ for needle in (+ "2 diagram(s): [0] unparsed: malformed edge at line 5, [1] flowchart (2n/1e)",+ "## Diagram 1",+ ):+ if needle not in digest:+ fail(f"selected-block digest missing {needle!r}: {digest!r}")+ if "## Diagram 0" in digest:+ fail("an unselected malformed block was emitted as a diagram")+ for selector in ([], ["--diagram", "0"], ["--diagram", "all"]):+ expect_error([str(bad_first), *selector], "malformed edge at line 5")+ expect_error([str(bad_first), "--diagram", "9"], "no diagram with index 9 (have 0..1)")++ bad_second = tmp / "bad-second-block.md"+ bad_second.write_text(+ "```mermaid\nflowchart LR\nA --> B\n```\n\n"+ "```mermaid\npie title Pets\n```\n",+ encoding="utf-8",+ )+ default_digest = run_extract([str(bad_second)])+ if "[1] unparsed: unsupported diagram kind" not in default_digest:+ fail(f"default selection did not list the unparsed block 1: {default_digest!r}")+ if "## Diagram 0" not in default_digest:+ fail("default selection did not emit diagram 0 past a bad block 1")+ expect_error([str(bad_second), "--diagram", "1"], "unsupported diagram kind: `pie`")+ ok("--diagram selects a block before parsing it; selected bad blocks still fail")++def check_adversarial(tmp: Path) -> None:payload = json.loads(run_extract([str(ADVERSARIAL), "--json"]))diagram = payload["diagrams"][0]@@ -996,6 +1039,7 @@ def main() -> int:check_shape_and_edge_vocabulary(tmp)check_frontmatter(tmp)check_markdown_and_grammars(tmp)+ check_selection_before_parse(tmp)check_legacy_stdout_encoding(tmp)check_sequence_grammar_forms(tmp)check_adversarial(tmp)diff --git a/skills/diagram-design/references/import-mermaid.md b/skills/diagram-design/references/import-mermaid.mdindex 184a758..e3ddbb2 100644--- a/skills/diagram-design/references/import-mermaid.md+++ b/skills/diagram-design/references/import-mermaid.md@@ -22,7 +22,7 @@ The extractor parses bounded text. It **never evaluates, renders, fetches, or exSupported grammars are `flowchart` / `graph`, `sequenceDiagram`, `stateDiagram-v2`, and `erDiagram`. Flowcharts accept classic delimiters plus Mermaid v11.3+ `@{ shape: ... }` nodes, multiline Markdown labels, multidirectional links, and labeled links in both the spaced (`B-- yes -->C`) and compact (`B--yes-->C`) forms; a spaced label may be quoted (`B-- "yes, and then" -->C`) to carry commas, pipes, and other delimiters. Sequence activation suffixes and central-connection `()` markers are normalized without changing participants; quoted `participant "Name"` / `actor "Name"` declarations (with or without an `as` alias), `create participant` directives, bidirectional `<<->>` / `<<-->>` arrows, and open `->` / `-->` arrows keep their Mermaid semantics. The digest mirrors the draw.io IR: diagram list, nodes/edges/containers, depth and cycles, shapes, type candidates, budget flags, hubs, entries, terminals, unconnected nodes, collapsible groups, and tables. Mermaid has no source coordinates, so it reports `source layout: none (Mermaid is layout-free)` plus the declared direction.-- `--diagram all` selects every fenced block. Default is diagram 0.+- `--diagram N` selects one fenced block before parsing, so a malformed or unsupported block elsewhere in the file does not stop it. `--diagram all` selects every fenced block and fails if any of them fails. Default is diagram 0.- `--json` emits the full IR, including ER fields and sequence fragments.- `--max-rows N` controls digest table length; default 40.- `--out PATH` writes the digest without changing its content.@@ -93,9 +93,10 @@ The extractor reports 9 IR nodes (7 drawable plus 2 containers) and 7 edges; the## Multi-block files-Markdown is the Mermaid analogue of multi-page draw.io. The header lists every fenced block with grammar and node/edge counts.+Markdown is the Mermaid analogue of multi-page draw.io. The header lists every fenced block with grammar and node/edge counts. A block that was not selected and cannot be parsed is listed as `[N] unparsed: <reason>` instead of failing the run; select it to get the exit-2 error.- With no `--diagram`, inspect diagram 0 and ask which block if the user did not identify one.+- If the block you need fails, the others stay reachable with `--diagram N`. Report the failure verbatim and do not redraw that block.- `--diagram all` creates one independently type-selected output per block, named `<base>-<index>.html`.- Do not merge blocks onto one canvas unless asked. Adjacent blocks frequently use different grammars.diff --git a/skills/diagram-design/scripts/mermaid_extract.py b/skills/diagram-design/scripts/mermaid_extract.pyindex 86595e8..8a02537 100644--- a/skills/diagram-design/scripts/mermaid_extract.py+++ b/skills/diagram-design/scripts/mermaid_extract.py@@ -62,9 +62,12 @@ def _configure_stdout_utf8() -> None:reconfigure(encoding="utf-8", errors="strict")+class ExtractError(Exception):+ """An input the extractor refuses. `main()` reports it and exits 2."""++def _fail(message: str) -> NoReturn:- print(f"mermaid_extract: {message}", file=sys.stderr)- raise SystemExit(2)+ raise ExtractError(message)@dataclass@@ -1185,19 +1188,28 @@ def _escape_table(text: str) -> str:return _escape_markdown(text.replace("\n", " ⏎ "))+def _block_summary(block: SourceBlock, selected: list[Diagram]) -> str:+ """One header entry. A block that was not selected is parsed only to+ describe it, so a failure there is listed instead of ending the run."""+ diagram = next((item for item in selected if item.index == block.index), None)+ if diagram is None:+ try:+ diagram = parse_block(block)+ except ExtractError as error:+ return f"[{block.index}] unparsed: {_escape_markdown(str(error))}"+ return f"[{diagram.index}] {diagram.kind} ({len(diagram.nodes)}n/{len(diagram.edges)}e)"++def digest(path: Path,- diagrams: list[Diagram],+ blocks: list[SourceBlock],selected: list[Diagram],max_rows: int,) -> str:output = [f"# Mermaid IR — {path.name}", ""]output.append(- f"{len(diagrams)} diagram(s): "- + ", ".join(- f"[{diagram.index}] {diagram.kind} ({len(diagram.nodes)}n/{len(diagram.edges)}e)"- for diagram in diagrams- )+ f"{len(blocks)} diagram(s): "+ + ", ".join(_block_summary(block, selected) for block in blocks))for diagram in selected:info = analyze(diagram)@@ -1309,11 +1321,11 @@ def digest(return "\n".join(output)-def to_json(path: Path, diagrams: list[Diagram], selected: list[Diagram]) -> str:+def to_json(path: Path, blocks: list[SourceBlock], selected: list[Diagram]) -> str:return json.dumps({"source": str(path),- "diagrams_total": len(diagrams),+ "diagrams_total": len(blocks),"diagrams": [{"index": diagram.index,@@ -1335,21 +1347,30 @@ def to_json(path: Path, diagrams: list[Diagram], selected: list[Diagram]) -> str)-def select_diagrams(diagrams: list[Diagram], selector: str | None) -> list[Diagram]:+def select_blocks(blocks: list[SourceBlock], selector: str | None) -> list[SourceBlock]:+ """Pick blocks before parsing, so a bad block fails only when selected."""if selector is None:- return diagrams[:1]+ return blocks[:1]if selector == "all":- return diagrams+ return blocksif selector.isdigit():index = int(selector)- selected = [diagram for diagram in diagrams if diagram.index == index]+ selected = [block for block in blocks if block.index == index]if not selected:- _fail(f"no diagram with index {index} (have 0..{len(diagrams) - 1})")+ _fail(f"no diagram with index {index} (have 0..{len(blocks) - 1})")return selected_fail("--diagram must be an index or 'all'")def main(argv: list[str] | None = None) -> int:+ try:+ return _run(argv)+ except ExtractError as error:+ print(f"mermaid_extract: {error}", file=sys.stderr)+ raise SystemExit(2) from None+++def _run(argv: list[str] | None) -> int:parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])parser.add_argument("file", help=".mmd, .mermaid, or Markdown with mermaid fences")parser.add_argument(@@ -1371,12 +1392,11 @@ def main(argv: list[str] | None = None) -> int:if not path.is_file():_fail(f"{path}: no such file")blocks = load_blocks(path)- diagrams = [parse_block(block) for block in blocks]- selected = select_diagrams(diagrams, args.diagram)+ selected = [parse_block(block) for block in select_blocks(blocks, args.diagram)]output = (- to_json(path, diagrams, selected)+ to_json(path, blocks, selected)if args.json- else digest(path, diagrams, selected, args.max_rows)+ else digest(path, blocks, selected, args.max_rows))if args.out:try: