repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(mermaid): validate Pi terminal diagrams through stdin

f3cacf4a1145390f1fa35c55545940877a55271a

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

pi/agent/skills/mermaid/SKILL.md

Modified
8 8 Use Mermaid when relationships, order, states, or structure communicate more than prose.
9 9 Use prose when a diagram would only decorate the answer.
11 +For diagrams displayed inside Pi's terminal, read [Pi terminal rendering](references/pi-terminal.md) before authoring; validate with Pi's installed renderer through stdin, never temporary diagram files.
12 +For browser/HTML targets, retain their own renderer and theme contract.
11 14 ## Choose the narrowest model
13 16 - order between actors → `sequenceDiagram`

pi/agent/skills/mermaid/package.json

Added
new file mode 100644
1 +{
2 + "name": "mermaid-skill",
3 + "private": true,
4 + "type": "module",
5 + "scripts": {
6 + "test": "node --test scripts/validate-pi.test.mjs"
7 + }
8 +}

pi/agent/skills/mermaid/references/pi-terminal.md

Added
new file mode 100644
1 +# Pi terminal Mermaid
3 +Use only when diagrams will display in Pi's terminal.
4 +Browser Mermaid and exported HTML have different rendering contracts.
6 +## Authority
8 +Routine validation uses the helper; reread renderer source/docs only after upgrades or unexpected results.
10 +- Resolve installed Pi from `PI_CONTEXT_PACKAGE_JSON_PATH`; do not assume global npm paths.
11 +- Pi's transformer lives beside that manifest at `dist/modes/interactive/components/mermaid.js` in the inspected installation.
12 +- Resolve `grok-mermaid` from that manifest with Node `createRequire`; inspect its installed README for supported syntax.
13 +- Installed Pi docs are under `PI_CONTEXT_DOCS_PATH`; `settings.md` documents `markdown.mermaid`.
14 +- Paths and behavior can change with Pi upgrades; inspect again if validation disagrees with display.
16 +## Rendering contract
18 +- Pi uses `grok-mermaid` Unicode terminal art, not browser Mermaid/SVG.
19 +- Supported families: flowchart, state, class, ER, sequence.
20 +- Timeline, Gantt, and other browser diagram types are not supported by the inspected renderer.
21 +- Browser styling, HTML labels, and theme directives are not a portable terminal contract; use plain labels and Pi's theme.
22 +- Use a top-level fenced block tagged `mermaid`, outside lists and blockquotes.
23 +- Null render or width exceeding available message width → Pi silently retains source.
24 +- Nonempty renderer warnings → final response retains source and adds a warning.
25 +- Streaming may show partial art that falls back to source once finalized.
26 +- `markdown.mermaid`: `off` disables rendering, `final` waits for completion, `streaming` renders during generation.
27 +- Thinking content is not transformed.
29 +The renderer README calls warnings advisory, but Pi rejects them in final messages.
30 +Validate against Pi's final-message behavior, not merely whether partial art exists.
32 +## Layout
34 +- One claim, few nodes, short labels.
35 +- Try `TD` first for narrow screens, then measure; parallel vertical branches can be wider than `LR`.
36 +- Sequence participants also consume horizontal space.
37 +- Shorten labels or split diagrams rather than hoping Pi shrinks them; renderer computes its own width.
38 +- Terminal columns are not message columns: account for Pi padding and surrounding UI.
39 +- A tool subprocess's `stdout.columns`, `COLUMNS`, or absent TTY does not establish the live Pi viewport.
40 +- If viewport is unknown, use an explicit conservative budget (for example 40 columns), state that assumption, and report required width rather than guaranteed fit.
41 +- Passing validation does not prove semantic correctness; inspect the preview for missing edges, flattened structure, and misleading layout.
43 +## Validate without source files
45 +Validate through stdin; never create temporary files solely for diagram validation.
46 +Pass exact raw diagram contents, without Markdown fences, to [validate-pi.mjs](../scripts/validate-pi.mjs).
47 +Resolve that script relative to this skill and use its absolute path when cwd differs.
48 +No input-file option is provided.
50 +Example from the skill directory, using Nushell:
52 +```nu
53 +'flowchart TD; A["Agent"] --> B["Review"]' | ^node scripts/validate-pi.mjs --width 40
54 +```
56 +The helper is cross-platform Node `.mjs`; only stdin plumbing depends on the caller's shell.
57 +Programmatic callers can use `spawnSync(process.execPath, [scriptPath, "--width", "40"], { input: source, encoding: "utf8", shell: false })` without shell quoting or temporary files.
59 +- `--width` is mandatory and means available message columns, not terminal columns.
60 +- Output JSON contains `ok`, `requiredColumns`, `availableColumns`, and, for rendered art, `overflow`, `warnings`, and preview `lines`.
61 +- Exit `0`: fits the supplied budget with no warnings.
62 +- Exit `1`: null render, warnings, or overflow; revise diagram.
63 +- Exit `2`: invalid invocation or unavailable/broken Pi renderer; report blocker.
64 +- Missing `PI_CONTEXT_PACKAGE_JSON_PATH` or installed renderer → stop; never install a substitute or change dependencies.
65 +- Renderer resolves through `createRequire(pathToFileURL(packagePath))`, then imports a file URL; no hardcoded Unix paths or npm dependency declarations.
66 +- The skill's `package.json` is test metadata only; `npm test` uses Node's built-in test runner, without installation.
67 +- Renderer integration tests require Pi context; without it they explicitly skip, not claim renderer verification.
69 +## Verified examples
71 +Human checked these in Pi after validator measurements; only A and B rendered.
72 +Tests preserve the same inputs in [validate-pi.test.mjs](../scripts/validate-pi.test.mjs).
74 +- A: vertical Agent → Review flowchart, 10 columns, no warnings.
75 +- B: You/Agent sequence with Task/Patch messages, 18 columns, no warnings.
76 +- C: five long labels in a horizontal chain, 137 columns; too wide for the observed viewport.
77 +- D: Gantt source returned null; unsupported family.
78 +- E: `flowchart TD` followed by `A[Start --> B` drew partial art but warned about a missing closing bracket; rejected on final display.
80 +Widths describe the inspected renderer version, not stable API guarantees.
81 +Revalidate exact source after edits or renderer upgrades.

pi/agent/skills/mermaid/scripts/validate-pi.mjs

Added
new file mode 100644
1 +import { createRequire } from "node:module";
2 +import { isAbsolute } from "node:path";
3 +import { pathToFileURL } from "node:url";
5 +const usage = "Usage: pipe raw Mermaid through stdin to node validate-pi.mjs --width <available-columns>";
7 +async function main() {
8 + const args = process.argv.slice(2);
9 + if (args.length === 1 && args[0] === "--help") {
10 + console.log(usage);
11 + return;
12 + }
13 + if (
14 + args.length !== 2 ||
15 + args[0] !== "--width" ||
16 + !/^\d+$/.test(args[1]) ||
17 + !Number.isSafeInteger(Number(args[1])) ||
18 + Number(args[1]) < 1
19 + ) {
20 + throw new Error(usage);
21 + }
22 + const availableColumns = Number(args[1]);
23 + if (process.stdin.isTTY) throw new Error("Pipe raw Mermaid source through stdin; file arguments are unsupported.");
25 + const packagePath = process.env.PI_CONTEXT_PACKAGE_JSON_PATH;
26 + if (!packagePath || !isAbsolute(packagePath)) {
27 + throw new Error("PI_CONTEXT_PACKAGE_JSON_PATH must identify the installed Pi package.json by absolute path.");
28 + }
29 + const require = createRequire(pathToFileURL(packagePath));
30 + let renderer;
31 + try {
32 + renderer = await import(pathToFileURL(require.resolve("grok-mermaid")).href);
33 + } catch (error) {
34 + throw new Error(`Cannot load Pi's installed grok-mermaid (${error.code ?? "load failure"}); do not install a substitute.`);
35 + }
36 + if (typeof renderer.render !== "function") throw new Error("Pi renderer no longer exposes render(); inspect its installed API.");
38 + process.stdin.setEncoding("utf8");
39 + let source = "";
40 + for await (const chunk of process.stdin) source += chunk;
41 + const art = renderer.render(source);
42 + if (!art) {
43 + console.log(JSON.stringify({
44 + ok: false,
45 + reason: "Renderer returned null: empty, unsupported, invalid, or oversized diagram.",
46 + availableColumns,
47 + requiredColumns: null,
48 + }));
49 + process.exitCode = 1;
50 + return;
51 + }
52 + const ok = art.warnings.length === 0 && art.width <= availableColumns;
53 + console.log(JSON.stringify({
54 + ok,
55 + availableColumns,
56 + requiredColumns: art.width,
57 + overflow: art.width > availableColumns,
58 + warnings: art.warnings,
59 + lines: art.plain,
60 + }));
61 + if (!ok) process.exitCode = 1;
64 +main().catch((error) => {
65 + console.error(error.message);
66 + process.exitCode = 2;
67 +});

pi/agent/skills/mermaid/scripts/validate-pi.test.mjs

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { spawnSync } from "node:child_process";
3 +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4 +import { tmpdir } from "node:os";
5 +import { join } from "node:path";
6 +import { fileURLToPath } from "node:url";
7 +import { describe, test } from "node:test";
9 +const script = fileURLToPath(new URL("./validate-pi.mjs", import.meta.url));
10 +const installedPackage = process.env.PI_CONTEXT_PACKAGE_JSON_PATH;
11 +const examples = {
12 + A: 'flowchart TD\n A["Agent"] --> B["Review"]',
13 + B: 'sequenceDiagram\n participant H as You\n participant A as Agent\n H->>A: Task\n A-->>H: Patch',
14 + C: 'flowchart LR\n A["Prepare environment"] --> B["Run agent assignment"] --> C["Collect test evidence"] --> D["Review proposed changes"] --> E["Integrate accepted revision"]',
15 + D: 'gantt\n title Agent work\n dateFormat YYYY-MM-DD\n section Work\n Review :2026-01-01, 1d',
16 + E: 'flowchart TD\n A[Start --> B',
17 +};
19 +function invoke(source = examples.A, args = ["--width", "48"], options = {}) {
20 + const result = spawnSync(process.execPath, [script, ...args], {
21 + input: source,
22 + encoding: "utf8",
23 + timeout: 10_000,
24 + ...options,
25 + });
26 + assert.ifError(result.error);
27 + assert.equal(result.signal, null);
28 + return result;
31 +function withoutPi() {
32 + const env = { ...process.env };
33 + delete env.PI_CONTEXT_PACKAGE_JSON_PATH;
34 + return env;
37 +test("help requires neither Pi nor source", () => {
38 + const result = invoke("", ["--help"], { env: withoutPi() });
39 + assert.equal(result.status, 0);
40 + assert.match(result.stdout, /--width/);
41 +});
43 +test("requires explicit positive integer width; rejects file arguments", () => {
44 + for (const args of [[], ["--width", "0"], ["--width", "-1"], ["--width", "1.5"], ["--width", "abc"], ["--width", "9007199254740992"], ["--width", "48", "diagram.mmd"]]) {
45 + const result = invoke("", args, { env: withoutPi() });
46 + assert.equal(result.status, 2);
47 + assert.match(result.stderr, /Usage:/);
48 + }
49 +});
51 +test("missing Pi context fails explicitly without fallback", () => {
52 + const result = invoke(examples.A, undefined, { env: withoutPi() });
53 + assert.equal(result.status, 2);
54 + assert.match(result.stderr, /PI_CONTEXT_PACKAGE_JSON_PATH/);
55 +});
57 +test("relative Pi package path is rejected", () => {
58 + const result = invoke(examples.A, undefined, { env: { ...withoutPi(), PI_CONTEXT_PACKAGE_JSON_PATH: "package.json" } });
59 + assert.equal(result.status, 2);
60 + assert.match(result.stderr, /absolute path/);
61 +});
63 +test("missing Pi renderer fails without installing dependencies", () => {
64 + const root = mkdtempSync(join(tmpdir(), "mermaid-pi-missing-"));
65 + try {
66 + const manifest = join(root, "package.json");
67 + writeFileSync(manifest, "{}");
68 + const result = invoke(examples.A, undefined, { cwd: root, env: { ...withoutPi(), PI_CONTEXT_PACKAGE_JSON_PATH: manifest } });
69 + assert.equal(result.status, 2);
70 + assert.match(result.stderr, /Cannot load Pi's installed grok-mermaid/);
71 + assert.deepEqual(readdirSync(root), ["package.json"]);
72 + } finally {
73 + rmSync(root, { recursive: true, force: true });
74 + }
75 +});
77 +describe("installed Pi renderer", { skip: !installedPackage && "PI_CONTEXT_PACKAGE_JSON_PATH is needed for renderer integration tests" }, () => {
78 + for (const name of ["A", "B"]) {
79 + test(`${name}: narrow diagram passes with preview`, () => {
80 + const result = invoke(examples[name]);
81 + assert.equal(result.status, 0, result.stderr);
82 + const report = JSON.parse(result.stdout);
83 + assert.equal(report.ok, true);
84 + assert.deepEqual(report.warnings, []);
85 + assert.equal(report.overflow, false);
86 + assert.ok(report.lines.length > 0);
87 + });
88 + }
89 + test("C: wide diagram fails width budget", () => {
90 + const result = invoke(examples.C);
91 + assert.equal(result.status, 1, result.stderr);
92 + const report = JSON.parse(result.stdout);
93 + assert.equal(report.ok, false);
94 + assert.equal(report.overflow, true);
95 + assert.ok(report.requiredColumns > 48);
96 + });
97 + test("D: unsupported diagram fails", () => {
98 + const result = invoke(examples.D);
99 + assert.equal(result.status, 1, result.stderr);
100 + assert.equal(JSON.parse(result.stdout).requiredColumns, null);
101 + });
102 + test("E: warnings fail even when the partial drawing fits", () => {
103 + const result = invoke(examples.E);
104 + assert.equal(result.status, 1, result.stderr);
105 + const report = JSON.parse(result.stdout);
106 + assert.equal(report.ok, false);
107 + assert.equal(report.overflow, false);
108 + assert.ok(report.warnings.length > 0);
109 + });
110 + test("empty stdin fails", () => {
111 + const result = invoke("");
112 + assert.equal(result.status, 1, result.stderr);
113 + assert.equal(JSON.parse(result.stdout).ok, false);
114 + });
115 + test("exact width fits; one column less fails", () => {
116 + const width = JSON.parse(invoke().stdout).requiredColumns;
117 + assert.equal(invoke(examples.A, ["--width", String(width)]).status, 0);
118 + assert.equal(invoke(examples.A, ["--width", String(width - 1)]).status, 1);
119 + });
120 + test("stdin validation from a Unicode/space cwd creates no files", () => {
121 + const root = mkdtempSync(join(tmpdir(), "mermaid pi #é-"));
122 + try {
123 + const result = invoke(examples.A, undefined, { cwd: root });
124 + assert.equal(result.status, 0, result.stderr);
125 + assert.deepEqual(readdirSync(root), []);
126 + } finally {
127 + rmSync(root, { recursive: true, force: true });
129 + });
130 +});