Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): mermaid authoring feedback for agent writes (PRD-7003) (#1808)

Andrew Mikofalvyc7d7671d454f
diff --git a/.changeset/mermaid-render-warnings.md b/.changeset/mermaid-render-warnings.md
new file mode 100644
index 000000000..75a21316b
--- /dev/null
+++ b/.changeset/mermaid-render-warnings.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Agent writes now get advisory mermaid feedback, delivered on a new unified `warnings` channel. The `write`/`edit` MCP tools (and the underlying `POST /api/agent-write-md` / `POST /api/agent-patch` routes) validate every ` ```mermaid ` fence of the post-write document with the same mermaid version the editor renders with, and report parse failures as `warnings` entries (`kind: "mermaid-parse-error"` — fence locator + mermaid's line-numbered message) plus a `⚠` line in the tool response text — so the authoring agent can fix a broken diagram in the same session instead of the reader discovering the error chrome. Strictly advisory: writes land byte-faithfully regardless.
+
+The `warnings` array is the one advisory channel going forward: it also carries the existing write-integrity kinds (`content-divergence`, `disk-edit-reconciled`) on every mutating write surface (write, write-md, patch, frontmatter-patch, rollback / `restore_version`), so co-occurring advisories no longer mask one another. The single-valued `warning` field and the MCP `structuredContent.document.contentDivergence` nesting are deprecated — `warning` keeps emitting its highest-precedence integrity entry in parallel for one deprecation window; new consumers should read `warnings`.
+
+The `palette` tool's Mermaid entry now teaches the grammar sharp edges (raw `;`/`#` terminate sequence-family message text — use commas or `#59;`/`#35;`; quote flowchart labels containing punctuation), and the tool-description footer points at it.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 7420f8568..020906ae3 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -2524,6 +2524,16 @@ Homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/v
Copyright (c) Microsoft Corporation.
+### `@types/[email protected]`
+Homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-mimetype
+
+Copyright (c) Microsoft Corporation.
+
+### `@types/[email protected]`
+Homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws
+
+Copyright (c) Microsoft Corporation.
+
### `@types/[email protected]`
Homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs
@@ -2694,6 +2704,11 @@ Homepage: https://github.com/brianloveswords/buffer-crc32
Copyright (c) 2013-2024 Brian J. Brennan
+Homepage: https://github.com/evidentpoint/buffer-image-size
+
+_(LICENSE file present but no auto-extractable copyright line; refer to the package source for canonical attribution.)_
+
Homepage: https://github.com/electron-userland/electron-builder
@@ -3449,6 +3464,11 @@ Homepage: https://github.com/pshihn/hachure-fill#readme
Copyright (c) 2023 Preet Shihn
+Homepage: https://github.com/capricorn86/happy-dom
+
+Copyright (c) 2019 David Ortner (capricorn86)
+
Homepage: https://github.com/sindresorhus/has-flag
@@ -5581,6 +5601,11 @@ Homepage: https://github.com/MattiasBuelens/web-streams-polyfill#readme
Copyright (c) 2024 Mattias Buelens Copyright (c) 2016 Diwank Singh Tomer
+Homepage: https://github.com/jsdom/whatwg-mimetype
+
+_(LICENSE file present but no auto-extractable copyright line; refer to the package source for canonical attribution.)_
+
Homepage: https://github.com/chalk/wrap-ansi
@@ -5591,6 +5616,11 @@ Homepage: https://github.com/chalk/wrap-ansi
Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
+Homepage: https://github.com/websockets/ws
+
+Copyright (c) 2011 Einar Otto Stangvik <[email protected]> Copyright (c) 2013 Arnout Kazemier and contributors Copyright (c) 2016 Luigi Pinca and contributors
+
Homepage: https://github.com/websockets/ws
@@ -6264,6 +6294,11 @@ Homepage: https://github.com/motdotla/dotenv#readme
Copyright (c) 2015, Scott Motte
+Homepage: https://github.com/fb55/entities
+
+Copyright (c) Felix Böhm
+
Homepage: https://github.com/fb55/entities
diff --git a/bun.lock b/bun.lock
index 685f864ec..b4ef7650c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -365,8 +365,10 @@
"chokidar": "^5.0.0",
"diff": "^8.0.4",
"file-type": "^22.0.1",
+ "happy-dom": "^20.10.2",
"ignore": "^5.3.2",
"just-bash": "^2.14.1",
+ "mermaid": "^11.14.0",
"mrmime": "^2.0.1",
"pino": "^10.3.1",
"pino-pretty": "^13.1.3",
@@ -1779,6 +1781,8 @@
"@types/vimeo__player": ["@types/[email protected]", "", {}, "sha512-IzSzb6doT4I4uAnBHa+mBCiNtK7iAllEJjtpkX0sKY6/s1Vi+aX1134IAiPgiyFlMvFab/oZQpSeccK4r0/T2A=="],
+ "@types/whatwg-mimetype": ["@types/[email protected]", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
+
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@types/yargs": ["@types/[email protected]", "", { "dependencies": { "@types/yargs-parser": "*" } }, "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg=="],
@@ -1981,6 +1985,8 @@
"buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
+ "buffer-image-size": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],
+
"builder-util": ["[email protected]", "", { "dependencies": { "7zip-bin": "~5.2.0", "@types/debug": "^4.1.6", "app-builder-bin": "5.0.0-alpha.12", "builder-util-runtime": "9.6.0", "chalk": "^4.1.2", "cross-spawn": "^7.0.6", "debug": "^4.3.4", "fs-extra": "^10.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.0", "js-yaml": "^4.1.0", "sanitize-filename": "^1.6.3", "source-map-support": "^0.5.19", "stat-mode": "^1.0.0", "temp-file": "^3.4.0", "tiny-async-pool": "1.3.0" } }, "sha512-+eocmbdisnyb40B9nAp/KREfYLXvGagxV50KZv/Zh4aflsr1fdY9Qxs6QG1Jtx1vH5d5NQ3hIcemUi4RSlFK/Q=="],
"builder-util-runtime": ["[email protected]", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-k9V5I18PXLepLZ8jVmPzsH+gVCVZ+9aMVLyCZ0ZLOkT2KSyiBblDCCN8WxDbjOpfLGNHZqqJPBmW0HYeqxlgkQ=="],
@@ -2357,7 +2363,7 @@
"enquirer": ["[email protected]", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
- "entities": ["[email protected]", "", {}, "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA=="],
+ "entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
@@ -2611,6 +2617,8 @@
"hachure-fill": ["[email protected]", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="],
+ "happy-dom": ["[email protected]", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-5p9Sxis3eowDJKqx90QCsgbNA02XXqJ59NOHvD4V6cxp+rP4d/xOyVx7uY3hS8hiUbY1VeiFH8lbJ81AyuDVLQ=="],
+
"has-bigints": ["[email protected]", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
@@ -4093,7 +4101,7 @@
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
- "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+ "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="],
@@ -4189,6 +4197,8 @@
"@electron/windows-sign/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA=="],
+ "@hocuspocus/provider/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+
"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="],
"@inkeep/cxkit-primitives/@radix-ui/react-avatar": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-context": "1.1.1", "@radix-ui/react-primitive": "2.0.1", "@radix-ui/react-use-callback-ref": "1.1.0", "@radix-ui/react-use-layout-effect": "1.1.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-GaC7bXQZ5VgZvVvsJ5mu/AEbjYLnhhkoidOboC50Z6FFlLA03wG2ianUoH+zgDQ31/9gCF59bE4+2bBgTyMiig=="],
@@ -4449,6 +4459,8 @@
"glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
+ "happy-dom/whatwg-mimetype": ["[email protected]", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
+
"hast-util-from-html/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
"hast-util-raw/parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
@@ -4513,6 +4525,8 @@
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
+ "parse5/entities": ["[email protected]", "", {}, "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA=="],
+
"path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"playwright/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
@@ -4549,6 +4563,8 @@
"puppeteer-core/typed-query-selector": ["[email protected]", "", {}, "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA=="],
+ "puppeteer-core/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+
"rc/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"rc/strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
@@ -4775,8 +4791,12 @@
"@memlab/core/puppeteer-core/webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],
+ "@memlab/core/puppeteer-core/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+
"@memlab/e2e/puppeteer-core/webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],
+ "@memlab/e2e/puppeteer-core/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+
"@opentelemetry/instrumentation-fetch/@opentelemetry/sdk-trace-web/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.1.0", "@opentelemetry/resources": "2.1.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-uTX9FBlVQm4S2gVQO1sb5qyBLq/FPjbp+tmGoxu4tIgtYGmBYB44+KX/725RFDe30yBSaA9Ml9fqphe1hbUyLQ=="],
"@types/busboy/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
@@ -4947,6 +4967,8 @@
"puppeteer/puppeteer-core/webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],
+ "puppeteer/puppeteer-core/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
+
"read-yaml-file/js-yaml/argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-AmwWFx1m8G/a5cXkxLxTiWl+YEoWuoFLUCwqMlNuWO1tqAYITQAbCRPUkyBHv1VOFgfjVOqEj6L3u15J5ZCzTA=="],
diff --git a/packages/app/tests/integration/advisory-warnings.test.ts b/packages/app/tests/integration/advisory-warnings.test.ts
new file mode 100644
index 000000000..b1c76ef9c
--- /dev/null
+++ b/packages/app/tests/integration/advisory-warnings.test.ts
@@ -0,0 +1,187 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { AdvisoryWarning } from '@inkeep/open-knowledge-core';
+import { createTestServer, getServerState, type TestServer } from './test-harness.ts';
+
+let server: TestServer;
+
+beforeAll(async () => {
+ server = await createTestServer();
+});
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+interface WriteResponse {
+ timestamp?: string;
+ warning?: { kind?: string };
+ warnings?: AdvisoryWarning[];
+ [key: string]: unknown;
+}
+
+async function writeMd(
+ markdown: string,
+ docName: string,
+ position: 'append' | 'prepend' | 'replace' = 'replace',
+): Promise<{ status: number; body: WriteResponse }> {
+ const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ markdown, position, docName }),
+ });
+ return { status: res.status, body: (await res.json()) as WriteResponse };
+}
+
+async function patchDoc(
+ docName: string,
+ find: string,
+ replace: string,
+): Promise<{ status: number; body: WriteResponse }> {
+ const res = await fetch(`http://localhost:${server.port}/api/agent-patch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, find, replace }),
+ });
+ return { status: res.status, body: (await res.json()) as WriteResponse };
+}
+
+const uniqueDoc = (prefix: string) => `${prefix}-${crypto.randomUUID().slice(0, 8)}`;
+
+const INVALID_SEQUENCE_FENCE =
+ '# Doc\n\n```mermaid\nsequenceDiagram\n A->>B: payload + nonce; cookie cleared\n```\n';
+const VALID_FENCE = '# Doc\n\n```mermaid\ngraph LR\n A-->B\n```\n';
+
+describe('advisory warnings on POST /api/agent-write-md', () => {
+ test('an invalid mermaid fence yields a locator + line-numbered warning', async () => {
+ const docName = uniqueDoc('rw-invalid');
+ const { status, body } = await writeMd(INVALID_SEQUENCE_FENCE, docName);
+ expect(status).toBe(200);
+ expect(body.warnings).toHaveLength(1);
+ const w = body.warnings?.[0];
+ expect(w?.kind).toBe('mermaid-parse-error');
+ if (w?.kind !== 'mermaid-parse-error') throw new Error('unreachable');
+ expect(w.fenceIndex).toBe(1);
+ expect(w.fenceFirstLine).toBe('sequenceDiagram');
+ expect(w.message).toContain('Parse error');
+ expect(w.line).toBeGreaterThan(0);
+ expect(body.warning).toBeUndefined();
+ });
+
+ test('valid fences and fence-less docs carry no renderWarnings field', async () => {
+ const valid = await writeMd(VALID_FENCE, uniqueDoc('rw-valid'));
+ expect(valid.status).toBe(200);
+ expect(valid.body.warnings).toBeUndefined();
+
+ const plain = await writeMd('# Plain\n\nNo diagrams.', uniqueDoc('rw-plain'));
+ expect(plain.status).toBe(200);
+ expect(plain.body.warnings).toBeUndefined();
+ });
+
+ test('append composition is validated on the post-write state', async () => {
+ const docName = uniqueDoc('rw-append');
+ const first = await writeMd('```mermaid\ngraph LR\n A-->B', docName);
+ expect(first.body.warnings).toBeUndefined();
+
+ const second = await writeMd('\nplain prose now inside the fence', docName, 'append');
+ expect(second.status).toBe(200);
+ expect(second.body.warnings).toHaveLength(1);
+ const w = second.body.warnings?.[0];
+ expect(w?.kind === 'mermaid-parse-error' && w.fenceFirstLine).toBe('graph LR');
+ });
+
+ test('the write lands byte-faithfully regardless of warnings (advisory only)', async () => {
+ const docName = uniqueDoc('rw-faithful');
+ const { status, body } = await writeMd(INVALID_SEQUENCE_FENCE, docName);
+ expect(status).toBe(200);
+ expect(typeof body.timestamp).toBe('string');
+ const state = getServerState(server, docName);
+ expect(state?.ytext.toString()).toContain('A->>B: payload + nonce; cookie cleared');
+ expect(state?.ytext.toString()).toBe(INVALID_SEQUENCE_FENCE);
+ });
+});
+
+describe('advisory warnings on POST /api/frontmatter-patch', () => {
+ test('a reconciled out-of-band edit reaches warnings[] alongside the deprecated slot', async () => {
+ const { writeFileSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const docName = uniqueDoc('rw-fm');
+ await writeMd('---\ntitle: v1\n---\n\n# Doc\n\nbody-v1\n', docName);
+ const pollDelay = (ms: number) => new Promise((r) => setTimeout(r, ms));
+ for (let i = 0; i < 100; i++) {
+ if (getServerState(server, docName)?.ytext.toString().includes('body-v1')) break;
+ await pollDelay(20);
+ }
+ writeFileSync(
+ join(server.contentDir, `${docName}.md`),
+ '---\ntitle: v1\n---\n\n# Doc\n\nbody-v2-native\n',
+ 'utf-8',
+ );
+ const res = await fetch(`http://localhost:${server.port}/api/frontmatter-patch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, patch: { status: 'draft' } }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as WriteResponse;
+ expect(body.warning?.kind).toBe('disk-edit-reconciled');
+ expect(body.warnings?.map((w) => w.kind)).toEqual(['disk-edit-reconciled']);
+ });
+});
+
+describe('advisory co-occurrence (the unification win: no masking)', () => {
+ test('a reconciled out-of-band edit and a broken fence surface together', async () => {
+ const { writeFileSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const docName = uniqueDoc('rw-cooccur');
+ await writeMd('# V1\n\nbody-v1\n', docName);
+ const pollDelay = (ms: number) => new Promise((r) => setTimeout(r, ms));
+ for (let i = 0; i < 100; i++) {
+ if (getServerState(server, docName)?.ytext.toString().includes('body-v1')) break;
+ await pollDelay(20);
+ }
+ writeFileSync(
+ join(server.contentDir, `${docName}.md`),
+ '# V2 NATIVE OUT-OF-BAND EDIT\n\nbody-v2-native\n',
+ 'utf-8',
+ );
+ const { status, body } = await writeMd(
+ '\n```mermaid\nsequenceDiagram\n A->>B: hi; there\n```\n',
+ docName,
+ 'append',
+ );
+ expect(status).toBe(200);
+ const kinds = (body.warnings ?? []).map((w) => w.kind).sort();
+ expect(kinds).toEqual(['disk-edit-reconciled', 'mermaid-parse-error']);
+ expect(body.warning?.kind).toBe('disk-edit-reconciled');
+ });
+});
+
+describe('advisory warnings on POST /api/agent-patch', () => {
+ test('a body edit that breaks a fence yields a warning', async () => {
+ const docName = uniqueDoc('rw-patch');
+ await writeMd(VALID_FENCE, docName);
+ const { status, body } = await patchDoc(docName, 'A-->B', 'A[unclosed --> B');
+ expect(status).toBe(200);
+ expect(body.warnings).toHaveLength(1);
+ const w = body.warnings?.[0];
+ expect(w?.kind === 'mermaid-parse-error' && w.fenceFirstLine).toBe('graph LR');
+ });
+
+ test('an unrelated edit surfaces a pre-existing broken fence with its locator', async () => {
+ const docName = uniqueDoc('rw-preexisting');
+ await writeMd(`${INVALID_SEQUENCE_FENCE}\nTrailing prose paragraph.\n`, docName);
+ const { status, body } = await patchDoc(docName, 'Trailing prose', 'Edited prose');
+ expect(status).toBe(200);
+ expect(body.warnings).toHaveLength(1);
+ const w = body.warnings?.[0];
+ expect(w?.kind === 'mermaid-parse-error' && w.fenceIndex).toBe(1);
+ expect(w?.kind === 'mermaid-parse-error' && w.fenceFirstLine).toBe('sequenceDiagram');
+ });
+
+ test('an edit fixing the only broken fence clears the warning', async () => {
+ const docName = uniqueDoc('rw-fix');
+ await writeMd(INVALID_SEQUENCE_FENCE, docName);
+ const { body } = await patchDoc(docName, 'nonce; cookie cleared', 'nonce, cookie cleared');
+ expect(body.warnings).toBeUndefined();
+ });
+});
diff --git a/packages/app/tests/integration/disk-authority-reconcile.test.ts b/packages/app/tests/integration/disk-authority-reconcile.test.ts
index bc2248ffc..786b9942e 100644
--- a/packages/app/tests/integration/disk-authority-reconcile.test.ts
+++ b/packages/app/tests/integration/disk-authority-reconcile.test.ts
@@ -60,8 +60,12 @@ describe('PRD-6832 β L1: agent write reconciles a newer out-of-band disk edit',
}),
});
expect(res.status).toBe(200);
- const body = (await res.json()) as { warning?: { kind?: string } };
+ const body = (await res.json()) as {
+ warning?: { kind?: string };
+ warnings?: Array<{ kind?: string }>;
+ };
expect(body.warning?.kind).toBe('disk-edit-reconciled');
+ expect(body.warnings?.map((w) => w.kind)).toEqual(['disk-edit-reconciled']);
const after = readTestDoc(contentDir, docName);
expect(after).toContain('body-v2-native'); // out-of-band edit preserved (no clobber)
diff --git a/packages/cli/tests/e2e/cli-linux-e2e.ts b/packages/cli/tests/e2e/cli-linux-e2e.ts
index 531ec3566..9937b1371 100644
--- a/packages/cli/tests/e2e/cli-linux-e2e.ts
+++ b/packages/cli/tests/e2e/cli-linux-e2e.ts
@@ -230,6 +230,103 @@ describe(`CLI Linux e2e (${SUT_MODE} SUT)`, () => {
}
}, 60_000);
+ test('4b. bundled mermaid validator emits renderWarnings through the packed bin', async () => {
+ const transport = new StdioClientTransport({
+ command: NODE,
+ args: [H.cliPath, 'mcp'],
+ cwd: H.contentDir,
+ env: { ...process.env, ...HERMETIC_ENV } as Record<string, string>,
+ });
+ const client = new Client({ name: 'ok-e2e-mermaid', version: '0.0.0' });
+ try {
+ await client.connect(transport);
+ const writeRes = (await client.callTool({
+ name: 'write',
+ arguments: {
+ cwd: H.contentDir,
+ document: {
+ path: 'e2e/mermaid-smoke',
+ content: '# Smoke\n\n```mermaid\nsequenceDiagram\n A->>B: hi; there\n```\n',
+ },
+ },
+ })) as {
+ isError?: boolean;
+ content?: Array<{ type: string; text?: string }>;
+ structuredContent?: {
+ document?: {
+ warnings?: Array<{ kind: string; fenceIndex: number; message: string }>;
+ };
+ };
+ };
+ expect(writeRes.isError ?? false).toBe(false);
+ const warnings = writeRes.structuredContent?.document?.warnings;
+ expect(warnings, 'warnings missing from packed-bin write response').toBeDefined();
+ expect(warnings?.[0]?.kind).toBe('mermaid-parse-error');
+ expect(warnings?.[0]?.message).toContain('Parse error');
+ const text = (writeRes.content ?? []).map((c) => c.text ?? '').join('\n');
+ expect(text).toContain('⚠');
+ expect(text).toContain('will not render');
+
+ const editRes = (await client.callTool({
+ name: 'edit',
+ arguments: {
+ cwd: H.contentDir,
+ document: { path: 'e2e/mermaid-smoke', find: '# Smoke', replace: '# Smoke (edited)' },
+ },
+ })) as {
+ isError?: boolean;
+ content?: Array<{ type: string; text?: string }>;
+ structuredContent?: { document?: { warnings?: Array<{ kind: string }> } };
+ };
+ expect(editRes.isError ?? false).toBe(false);
+ expect(editRes.structuredContent?.document?.warnings?.[0]?.kind).toBe('mermaid-parse-error');
+ const editText = (editRes.content ?? []).map((c) => c.text ?? '').join('\n');
+ expect(editText).toContain('will not render');
+
+ const validRes = (await client.callTool({
+ name: 'write',
+ arguments: {
+ cwd: H.contentDir,
+ document: {
+ path: 'e2e/mermaid-smoke-valid',
+ content: '```mermaid\ngraph LR\n A-->B\n```\n',
+ },
+ },
+ })) as {
+ isError?: boolean;
+ structuredContent?: { document?: { warnings?: unknown } };
+ };
+ expect(validRes.isError ?? false).toBe(false);
+ expect(validRes.structuredContent?.document?.warnings).toBeUndefined();
+
+ const batchRes = (await client.callTool({
+ name: 'write',
+ arguments: {
+ cwd: H.contentDir,
+ documents: [
+ { path: 'e2e/mermaid-batch-ok', content: '```mermaid\ngraph LR\n A-->B\n```\n' },
+ {
+ path: 'e2e/mermaid-batch-bad',
+ content: '```mermaid\nsequenceDiagram\n A->>B: x; y\n```\n',
+ },
+ ],
+ },
+ })) as {
+ isError?: boolean;
+ structuredContent?: {
+ documents?: Array<{ docName: string; warnings?: Array<{ kind: string }> }>;
+ };
+ };
+ expect(batchRes.isError ?? false).toBe(false);
+ const batchDocs = batchRes.structuredContent?.documents ?? [];
+ expect(batchDocs).toHaveLength(2);
+ expect(batchDocs[0]?.warnings).toBeUndefined();
+ expect(batchDocs[1]?.warnings?.[0]?.kind).toBe('mermaid-parse-error');
+ } finally {
+ await client.close().catch(() => {});
+ }
+ }, 60_000);
+
test('5. file-watcher ingests an external disk write (inotify on Linux)', async () => {
const marker = `okwatchprobe${START_PORT}`;
writeFileSync(
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c4a6eead9..a5d524ce3 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -451,6 +451,9 @@ export {
ActivityBurstSchema,
type ActivityFile,
ActivityFileSchema,
+ type AdvisoryWarning,
+ AdvisoryWarningSchema,
+ AdvisoryWarningsSchema,
type AgentActivitySuccess,
AgentActivitySuccessSchema,
type AgentBurstDiffSuccess,
@@ -648,6 +651,8 @@ export {
RenamePathSuccessSchema,
type RenameRewrittenDoc,
RenameRewrittenDocSchema,
+ type RenderWarning,
+ RenderWarningSchema,
type RescueEntryFlat,
RescueEntryFlatSchema,
type RescueEntryTimeline,
diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.ts
index 600f63382..06fd094b6 100644
--- a/packages/core/src/registry/projection.ts
+++ b/packages/core/src/registry/projection.ts
@@ -188,7 +188,7 @@ export function renderInventoryFooter(): string {
const lines = lite.map((entry) => `- \`${entry.id}\` (${entry.kind}) — ${entry.description}`);
return [
'',
- "**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `palette({ components: [ids] })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader's light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",
+ '**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `palette({ components: [ids] })` with the ids you want to use. Fenced code blocks render naturally and don\'t need a fetch — including ` ```mermaid ` for diagrams (mermaid label text has sharp edges — `palette({ components: ["Mermaid"] })` lists them; parse failures come back as `warnings` entries on write/edit) and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader\'s light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.',
'',
...lines,
].join('\n');
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index 9353c2180..7a96cb9dd 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -106,11 +106,32 @@ export const WriteWarningSchema = z.discriminatedUnion('kind', [
]);
export type WriteWarning = z.infer<typeof WriteWarningSchema>;
+export const RenderWarningSchema = z
+ .object({
+ kind: z.literal('mermaid-parse-error'),
+ fenceIndex: z.number().int().positive(),
+ fenceFirstLine: z.string(),
+ message: z.string(),
+ line: z.number().int().positive().optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type RenderWarning = z.infer<typeof RenderWarningSchema>;
+
+export const AdvisoryWarningSchema = z.discriminatedUnion('kind', [
+ ContentDivergenceWarningSchema,
+ DiskEditReconciledWarningSchema,
+ RenderWarningSchema,
+]);
+export type AdvisoryWarning = z.infer<typeof AdvisoryWarningSchema>;
+
+export const AdvisoryWarningsSchema = z.array(AdvisoryWarningSchema).min(1);
+
export const AgentWriteSuccessSchema = z
.object({
timestamp: z.string().min(1),
summary: SummaryResponseFieldSchema.optional(),
warning: WriteWarningSchema.optional(),
+ warnings: AdvisoryWarningsSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type AgentWriteSuccess = z.infer<typeof AgentWriteSuccessSchema>;
@@ -123,6 +144,7 @@ export const AgentWriteMdSuccessSchema = z
hints: z.array(OrphanHintSchema).optional(),
summary: SummaryResponseFieldSchema.optional(),
warning: WriteWarningSchema.optional(),
+ warnings: AdvisoryWarningsSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type AgentWriteMdSuccess = z.infer<typeof AgentWriteMdSuccessSchema>;
@@ -134,6 +156,7 @@ export const AgentPatchSuccessSchema = z
systemSubscriberCount: z.number().int().nonnegative(),
summary: SummaryResponseFieldSchema.optional(),
warning: WriteWarningSchema.optional(),
+ warnings: AdvisoryWarningsSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type AgentPatchSuccess = z.infer<typeof AgentPatchSuccessSchema>;
@@ -166,6 +189,7 @@ export const FrontmatterPatchSuccessSchema = z
appliedKeys: z.array(z.string()),
summary: SummaryResponseFieldSchema.optional(),
warning: WriteWarningSchema.optional(),
+ warnings: AdvisoryWarningsSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type FrontmatterPatchSuccess = z.infer<typeof FrontmatterPatchSuccessSchema>;
diff --git a/packages/core/src/schemas/api/pages.ts b/packages/core/src/schemas/api/pages.ts
index 8813af26b..a826a40ae 100644
--- a/packages/core/src/schemas/api/pages.ts
+++ b/packages/core/src/schemas/api/pages.ts
@@ -1,7 +1,11 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
import { agentIdentityFields, summaryField } from './_shared.ts';
-import { ContentDivergenceWarningSchema, SummaryResponseFieldSchema } from './agent-write.ts';
+import {
+ AdvisoryWarningsSchema,
+ ContentDivergenceWarningSchema,
+ SummaryResponseFieldSchema,
+} from './agent-write.ts';
export const RenamedDocMappingSchema = z
.object({
@@ -189,6 +193,7 @@ export const RollbackSuccessSchema = z
timestamp: z.string().min(1),
summary: SummaryResponseFieldSchema.optional(),
warning: ContentDivergenceWarningSchema.optional(),
+ warnings: AdvisoryWarningsSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type RollbackSuccess = z.infer<typeof RollbackSuccessSchema>;
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index b9c9a8055..ad281a4c4 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -111,7 +111,7 @@ Call `write` / `edit` as soon as you have content. Native `Edit` / `sed` / direc
**Reach for visual structure where it aids comprehension.** Default to the right OK primitive over flat prose: a Callout (`> [!NOTE]`) for a key caveat, a ` ```mermaid ` diagram for a process or relationship, a table for options or comparisons, an `html preview` chart for numbers. **Call the `palette` MCP tool as you draft** (and `palette({ components })` for a canonical's JSX schema) — it returns copy-ready markdown-native forms, themed `html preview` embed starters, and the theme tokens, so the visual lands themed and in the content graph instead of hand-rolled. Don't decorate — use a visual only when it carries the point better than prose would. Full catalog: §Components.
-**Content-divergence warning (Site A gate).** `write` and `edit` responses may include a content-divergence warning when the converged Y.Text doesn't match the bytes the payload composed to (concurrent peer left residue, or — rare — a primitive regression). The write still landed; on this signal, re-read the doc (`exec("cat <path>")`) to see what actually converged before continuing. Single-doc shape: `structuredContent.document.contentDivergence = { kind: "content-divergence", intendedBytes, actualBytes, byteDelta, hint }` (the result nests under the `document` target key, mirroring the input). Batch shape: per-doc `structuredContent.documents[].contentDivergence` with the same fields. Distinct from the preview-attach `warning` field (`action: "attach-preview-once" | "start-ui"`), which stays at the top level — separate keys, can coexist.
+**Advisory warnings on writes.** `write` and `edit` responses may include `structuredContent.document.warnings` (batch: per-doc `structuredContent.documents[].warnings`) — advisory entries discriminated by `kind`, each also summarized as a `⚠` line in the response text. The write always landed; the entries tell you what to do next. Write-integrity kinds mean re-read the doc (`exec("cat <path>")`) before continuing: `content-divergence` (`{ kind, intendedBytes, actualBytes, byteDelta, hint }` — the converged Y.Text doesn't match what the payload composed to: concurrent peer residue, or — rare — a primitive regression) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write landed on top). The renderability kind `mermaid-parse-error` (`{ kind, fenceIndex, fenceFirstLine, message, line? }`) means that mermaid fence will not render — fix the fence and re-edit. (A deprecated single-valued `warning` field on the HTTP body mirrors the highest-precedence integrity entry for older consumers.) Distinct from the preview-attach `warning` field (`action: "attach-preview-once" | "start-ui"`), which stays at the top level — separate keys, can coexist.
To author an MDX doc (the KB renders MDX/JSX components), pass a `.mdx` path on the create: `write({ document: { path: "guides/widget.mdx", content, position: "replace" } })` lands `guides/widget.mdx`. A `.md` or extension-less path lands `.md`. An existing doc keeps its on-disk extension regardless of the suffix you pass — changing it in place isn't available via the MCP today.
@@ -156,7 +156,7 @@ OK auto-promotes markdown-native syntax into themed canonical components at pars
| --- | --- | --- |
| Callout / admonition | `> [!NOTE]` + body — 15 types (NOTE, TIP, IMPORTANT, WARNING, CAUTION, …); append `+` / `-` (`> [!NOTE]+`) to make it foldable | themed Callout |
| Collapsible section | `<details><summary>Title</summary>` … `</details>` | themed Accordion |
-| Diagram | a ` ```mermaid ` fenced block (flowchart, sequence, class, state, ER, gantt, pie) | Mermaid diagram |
+| Diagram | a ` ```mermaid ` fenced block (flowchart, sequence, class, state, ER, gantt, pie) — label-text pitfalls + escapes: `palette({ components: ["Mermaid"] })`; parse failures come back as `warnings` entries on write/edit | Mermaid diagram |
| Math | `$x$` inline, `$$…$$` block | KaTeX Math |
| Inline a doc or asset | `![[file]]` | wiki embed |
diff --git a/packages/server/package.json b/packages/server/package.json
index 733354aba..dfdd2dd9d 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -37,8 +37,10 @@
"chokidar": "^5.0.0",
"diff": "^8.0.4",
"file-type": "^22.0.1",
+ "happy-dom": "^20.10.2",
"ignore": "^5.3.2",
"just-bash": "^2.14.1",
+ "mermaid": "^11.14.0",
"mrmime": "^2.0.1",
"pino": "^10.3.1",
"pino-pretty": "^13.1.3",
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 9d59cf116..a67885763 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -248,6 +248,7 @@ import {
} from './handoff-api.ts';
import { handleHandoffDispatch } from './handoff-dispatch-api.ts';
import { findHubCandidates } from './hub-candidates.ts';
+import { validateMermaidFences } from './mermaid-validator.ts';
import {
extractPageIcon,
extractPageTitle,
@@ -3155,7 +3156,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{
timestamp,
...(summaryResponse ? { summary: summaryResponse } : {}),
- ...(agentWriteWarning ? { warning: agentWriteWarning } : {}),
+ ...(agentWriteWarning
+ ? { warning: agentWriteWarning, warnings: [agentWriteWarning] }
+ : {}),
},
{ handler: 'agent-write' },
);
@@ -3320,6 +3323,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const hints = computeOrphanHints(resolvedDocName);
+ const renderWarnings = await validateMermaidFences(
+ session.dc.document.getText('source').toString(),
+ resolvedDocName,
+ );
+
const subscriberCount = getSubscriberCount(resolvedDocName);
const systemSubscriberCount = getSystemSubscriberCount();
@@ -3331,6 +3339,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
const writeMdWarning = buildReconcileWarning(writeMdReconcile);
+ const writeMdDivergenceEntry =
+ writeDivergence !== undefined ? toContentDivergenceWarning(writeDivergence) : undefined;
+ const writeMdAdvisories = [
+ ...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),
+ ...(writeMdWarning ? [writeMdWarning] : []),
+ ...(renderWarnings ?? []),
+ ];
successResponse(
res,
200,
@@ -3341,11 +3356,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
systemSubscriberCount,
...(hints ? { hints } : {}),
...(summaryResponse ? { summary: summaryResponse } : {}),
- ...(writeDivergence !== undefined
- ? { warning: toContentDivergenceWarning(writeDivergence) }
+ ...(writeMdDivergenceEntry
+ ? { warning: writeMdDivergenceEntry }
: writeMdWarning
? { warning: writeMdWarning }
: {}),
+ ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),
},
{ handler: 'agent-write-md' },
);
@@ -3584,7 +3600,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
systemSubscriberCount,
appliedKeys,
...(summaryResponse ? { summary: summaryResponse } : {}),
- ...(fmWarning ? { warning: fmWarning } : {}),
+ ...(fmWarning ? { warning: fmWarning, warnings: [fmWarning] } : {}),
},
{ handler: 'frontmatter-patch' },
);
@@ -4624,7 +4640,19 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const { response: summaryResponse } = summaryResponseFields(normalizedSummary);
+ const renderWarnings = await validateMermaidFences(
+ session.dc.document.getText('source').toString(),
+ docName,
+ );
+
const patchWarning = buildReconcileWarning(patchReconcile);
+ const patchDivergenceEntry =
+ patchDivergence !== undefined ? toContentDivergenceWarning(patchDivergence) : undefined;
+ const patchAdvisories = [
+ ...(patchDivergenceEntry ? [patchDivergenceEntry] : []),
+ ...(patchWarning ? [patchWarning] : []),
+ ...(renderWarnings ?? []),
+ ];
successResponse(
res,
200,
@@ -4634,11 +4662,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
subscriberCount,
systemSubscriberCount,
...(summaryResponse ? { summary: summaryResponse } : {}),
- ...(patchDivergence !== undefined
- ? { warning: toContentDivergenceWarning(patchDivergence) }
+ ...(patchDivergenceEntry
+ ? { warning: patchDivergenceEntry }
: patchWarning
? { warning: patchWarning }
: {}),
+ ...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),
},
{ handler: 'agent-patch' },
);
@@ -5589,6 +5618,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
}
+ const rollbackDivergenceEntry =
+ rollbackDivergence !== undefined
+ ? toContentDivergenceWarning(rollbackDivergence)
+ : undefined;
successResponse(
res,
200,
@@ -5597,8 +5630,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
restoredFrom: commitSha,
timestamp,
...(summaryResponse ? { summary: summaryResponse } : {}),
- ...(rollbackDivergence !== undefined
- ? { warning: toContentDivergenceWarning(rollbackDivergence) }
+ ...(rollbackDivergenceEntry
+ ? { warning: rollbackDivergenceEntry, warnings: [rollbackDivergenceEntry] }
: {}),
},
{ handler: 'rollback' },
diff --git a/packages/server/src/mcp/tools/advisory-warnings.test.ts b/packages/server/src/mcp/tools/advisory-warnings.test.ts
new file mode 100644
index 000000000..1e3ca985f
--- /dev/null
+++ b/packages/server/src/mcp/tools/advisory-warnings.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, test } from 'bun:test';
+import type { RenderWarning, WriteWarning } from '@inkeep/open-knowledge-core';
+import {
+ formatAdvisoryBriefs,
+ formatAdvisoryLines,
+ formatRenderWarningsBrief,
+ formatRenderWarningsLine,
+ parseAdvisoryWarnings,
+} from './advisory-warnings.ts';
+
+function mermaidWarning(overrides: Partial<RenderWarning> = {}): RenderWarning {
+ return {
+ kind: 'mermaid-parse-error',
+ fenceIndex: 1,
+ fenceFirstLine: 'sequenceDiagram',
+ message: 'Parse error on line 2:\n...A->>B: hi; the\n--------^',
+ line: 2,
+ ...overrides,
+ };
+}
+
+const DIVERGENCE: WriteWarning = {
+ kind: 'content-divergence',
+ intendedBytes: 100,
+ actualBytes: 98,
+ byteDelta: -2,
+};
+
+const RECONCILED: WriteWarning = {
+ kind: 'disk-edit-reconciled',
+ intendedBytes: 50,
+ actualBytes: 80,
+ byteDelta: 30,
+};
+
+describe('parseAdvisoryWarnings', () => {
+ test('parses a valid mixed array and rejects absent/empty/malformed payloads', () => {
+ expect(parseAdvisoryWarnings([mermaidWarning(), DIVERGENCE, RECONCILED])).toHaveLength(3);
+ expect(parseAdvisoryWarnings(undefined)).toBeUndefined();
+ expect(parseAdvisoryWarnings([])).toBeUndefined();
+ expect(parseAdvisoryWarnings([{ kind: 'something-else' }])).toBeUndefined();
+ expect(parseAdvisoryWarnings('not-an-array')).toBeUndefined();
+ });
+
+ test('unrecognized entries drop individually, keeping recognized siblings', () => {
+ const parsed = parseAdvisoryWarnings([
+ mermaidWarning(),
+ { kind: 'future-fence-kind', payload: true },
+ DIVERGENCE,
+ ]);
+ expect(parsed).toHaveLength(2);
+ expect(parsed?.map((w) => w.kind)).toEqual(['mermaid-parse-error', 'content-divergence']);
+ });
+});
+
+describe('formatAdvisoryLines', () => {
+ test('one line per integrity entry plus one grouped render line', () => {
+ const lines = formatAdvisoryLines([
+ DIVERGENCE,
+ RECONCILED,
+ mermaidWarning(),
+ mermaidWarning({ fenceIndex: 2 }),
+ ]);
+ expect(lines).toHaveLength(3);
+ expect(lines[0]).toContain('Content divergence');
+ expect(lines[1]).toContain('reconciled');
+ expect(lines[2]).toContain('2 mermaid fences');
+ });
+
+ test('integrity-only and render-only arrays each produce their own lines', () => {
+ expect(formatAdvisoryLines([DIVERGENCE])).toHaveLength(1);
+ expect(formatAdvisoryLines([mermaidWarning()])).toHaveLength(1);
+ });
+
+ test('single render failure inlines locator, line number, and mermaid message', () => {
+ const [line] = formatAdvisoryLines([mermaidWarning()]);
+ expect(line).toContain('⚠');
+ expect(line).toContain('fence 1');
+ expect(line).toContain('sequenceDiagram');
+ expect(line).toContain('(line 2)');
+ expect(line).toContain('Parse error on line 2:');
+ expect(line).toContain('will not render');
+ });
+
+ test('empty fence body renders the (empty fence) locator, not ("")', () => {
+ const [line] = formatAdvisoryLines([mermaidWarning({ fenceFirstLine: '' })]);
+ expect(line).toContain('(empty fence)');
+ expect(line).not.toContain('("")');
+ });
+
+ test('no line number omits the (line N) qualifier', () => {
+ const [line] = formatAdvisoryLines([mermaidWarning({ line: undefined })]);
+ expect(line).toContain('fence 1');
+ expect(line).not.toContain('(line ');
+ expect(line).toContain('will not render');
+ });
+});
+
+describe('formatAdvisoryBriefs', () => {
+ test('mixed advisories produce per-family briefs', () => {
+ const briefs = formatAdvisoryBriefs([RECONCILED, mermaidWarning()]);
+ expect(briefs).toHaveLength(2);
+ expect(briefs[0]).toContain('reconciled');
+ expect(briefs[1]).toContain('1 mermaid fence will not render');
+ expect(briefs[1]).not.toContain('fences');
+ });
+
+ test('plural form for multiple render warnings', () => {
+ const briefs = formatAdvisoryBriefs([mermaidWarning(), mermaidWarning({ fenceIndex: 2 })]);
+ expect(briefs[0]).toContain('2 mermaid fences');
+ });
+});
+
+describe('render-family bounds phrasing', () => {
+ test('a full page of 10 entries reads as 10+ (server caps render entries)', () => {
+ const warnings = Array.from({ length: 10 }, (_, i) => mermaidWarning({ fenceIndex: i + 1 }));
+ expect(formatRenderWarningsLine(warnings)).toContain('10+');
+ expect(formatRenderWarningsBrief(warnings)).toContain('10+');
+ });
+});
diff --git a/packages/server/src/mcp/tools/advisory-warnings.ts b/packages/server/src/mcp/tools/advisory-warnings.ts
new file mode 100644
index 000000000..d9138b3e0
--- /dev/null
+++ b/packages/server/src/mcp/tools/advisory-warnings.ts
@@ -0,0 +1,72 @@
+import {
+ type AdvisoryWarning,
+ AdvisoryWarningSchema,
+ type RenderWarning,
+ type WriteWarning,
+} from '@inkeep/open-knowledge-core';
+
+export function parseAdvisoryWarnings(value: unknown): AdvisoryWarning[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const warnings = value.flatMap((entry) => {
+ const parsed = AdvisoryWarningSchema.safeParse(entry);
+ return parsed.success ? [parsed.data] : [];
+ });
+ return warnings.length > 0 ? warnings : undefined;
+}
+
+function integrityEntries(warnings: AdvisoryWarning[]): WriteWarning[] {
+ return warnings.filter(
+ (w): w is WriteWarning => w.kind === 'content-divergence' || w.kind === 'disk-edit-reconciled',
+ );
+}
+
+function renderEntries(warnings: AdvisoryWarning[]): RenderWarning[] {
+ return warnings.filter((w): w is RenderWarning => w.kind === 'mermaid-parse-error');
+}
+
+export function formatAdvisoryLines(warnings: AdvisoryWarning[]): string[] {
+ const lines = integrityEntries(warnings).map(formatIntegrityLine);
+ const render = renderEntries(warnings);
+ if (render.length > 0) lines.push(formatRenderWarningsLine(render));
+ return lines;
+}
+
+export function formatAdvisoryBriefs(warnings: AdvisoryWarning[]): string[] {
+ const briefs = integrityEntries(warnings).map(formatIntegrityBrief);
+ const render = renderEntries(warnings);
+ if (render.length > 0) briefs.push(formatRenderWarningsBrief(render));
+ return briefs;
+}
+
+function formatIntegrityLine(d: WriteWarning): string {
+ return d.kind === 'content-divergence'
+ ? `⚠ Content divergence: ${d.actualBytes} actual bytes vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}). ${d.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
+ : `⚠ ${d.hint ?? 'An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.'}`;
+}
+
+function formatIntegrityBrief(d: WriteWarning): string {
+ return d.kind === 'content-divergence'
+ ? `⚠ Content divergence: ${d.actualBytes} actual vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}).`
+ : '⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.';
+}
+
+export function formatRenderWarningsLine(warnings: RenderWarning[]): string {
+ const first = warnings[0];
+ if (warnings.length === 1 && first) {
+ const lineRef = first.line !== undefined ? ` (line ${first.line})` : '';
+ const locator = first.fenceFirstLine === '' ? '(empty fence)' : `("${first.fenceFirstLine}")`;
+ return `⚠ Mermaid fence ${first.fenceIndex} ${locator} will not render${lineRef}: ${firstMessageLine(first.message)} Fix the fence and re-edit.`;
+ }
+ const count = warnings.length >= 10 ? '10+' : String(warnings.length);
+ return `⚠ ${count} mermaid fences will not render — see structuredContent.document.warnings (kind "mermaid-parse-error") for per-fence errors. Fix the fences and re-edit.`;
+}
+
+export function formatRenderWarningsBrief(warnings: RenderWarning[]): string {
+ const count = warnings.length >= 10 ? '10+' : String(warnings.length);
+ return `⚠ ${count} mermaid fence${warnings.length === 1 ? '' : 's'} will not render (see warnings).`;
+}
+
+function firstMessageLine(message: string): string {
+ const line = message.split('\n', 1)[0]?.trim() ?? '';
+ return line.endsWith('.') || line.endsWith(':') ? line : `${line}.`;
+}
diff --git a/packages/server/src/mcp/tools/content-divergence.ts b/packages/server/src/mcp/tools/content-divergence.ts
deleted file mode 100644
index e483eb44b..000000000
--- a/packages/server/src/mcp/tools/content-divergence.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { WriteWarningSchema } from '@inkeep/open-knowledge-core';
-import type { z } from 'zod';
-
-export type ContentDivergence = z.infer<typeof WriteWarningSchema>;
-
-export function parseContentDivergence(warning: unknown): ContentDivergence | undefined {
- const parsed = WriteWarningSchema.safeParse(warning);
- return parsed.success ? parsed.data : undefined;
-}
-
-export function formatContentDivergenceLine(d: ContentDivergence): string {
- return d.kind === 'content-divergence'
- ? `⚠ Content divergence: ${d.actualBytes} actual bytes vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}). ${d.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
- : `⚠ ${d.hint ?? 'An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.'}`;
-}
-
-export function formatContentDivergenceBrief(d: ContentDivergence): string {
- return d.kind === 'content-divergence'
- ? `⚠ Content divergence: ${d.actualBytes} actual vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}).`
- : '⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.';
-}
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index be37b2b78..2312f9c13 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -12,7 +12,7 @@ import { mergePatch } from '../../content/frontmatter-merge.ts';
import type { TemplateFrontmatter } from '../../content/templates-write.ts';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import type { AgentIdentity } from '../agent-identity.ts';
-import { formatContentDivergenceLine, parseContentDivergence } from './content-divergence.ts';
+import { formatAdvisoryLines, parseAdvisoryWarnings } from './advisory-warnings.ts';
import { resolveWithinRoot } from './path-safety.ts';
import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
@@ -49,7 +49,7 @@ const BASE_DESCRIPTION = [
'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',
'- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, or `template` edit. Avoid secrets or PII — persisted to git history.',
'',
- 'Responses may include `structuredContent.document.contentDivergence` when the converged Y.Text doesn\'t match the bytes your edit composed to. The edit still landed; re-read the doc with `exec("cat <path>")` to see what converged.',
+ 'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).',
].join('\n');
export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
@@ -250,13 +250,13 @@ function composeWritePreviewResult(
? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
: undefined;
const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
- const contentDivergence = parseContentDivergence(result.warning);
+ const advisoryWarnings = parseAdvisoryWarnings(result.warnings);
const lines: string[] = [leadLine];
if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
if (summaryHint) lines.push(summaryHint);
- if (contentDivergence) {
- lines.push(formatContentDivergenceLine(contentDivergence));
+ if (advisoryWarnings) {
+ lines.push(...formatAdvisoryLines(advisoryWarnings));
}
const text = lines.join('\n');
if (
@@ -264,13 +264,13 @@ function composeWritePreviewResult(
!noPreviewAnywhere &&
!noPreviewOnThisDoc &&
!summaryResult &&
- !contentDivergence
+ !advisoryWarnings
) {
return textResult(text);
}
const document: Record<string, unknown> = {};
if (summaryResult) document.summary = summaryResult;
- if (contentDivergence) document.contentDivergence = contentDivergence;
+ if (advisoryWarnings) document.warnings = advisoryWarnings;
const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;
return textPlusStructured(text, nestDocResult(preview, warning, document));
}
diff --git a/packages/server/src/mcp/tools/palette.test.ts b/packages/server/src/mcp/tools/palette.test.ts
index 22c6207a0..5d243fa4d 100644
--- a/packages/server/src/mcp/tools/palette.test.ts
+++ b/packages/server/src/mcp/tools/palette.test.ts
@@ -85,6 +85,22 @@ describe('palette tool', () => {
expect(tabs?.example).toContain('<Tabs>');
});
+ test('Mermaid entry teaches the grammar sharp edges and the feedback loop', async () => {
+ const handler = captureRegistration();
+ const { structuredContent } = await handler({});
+ const mermaid = structuredContent?.components.find((c) => c.id === 'Mermaid');
+ expect(mermaid).toBeDefined();
+ expect(mermaid?.guidance).toContain('`;`');
+ expect(mermaid?.guidance).toContain('`#`');
+ expect(mermaid?.guidance).toContain('#59;');
+ expect(mermaid?.guidance).toContain('#35;');
+ expect(mermaid?.guidance).toContain('label (with) punctuation');
+ expect(mermaid?.guidance).toContain('mermaid-parse-error');
+ expect(mermaid?.example).toContain('sequenceDiagram');
+ expect(mermaid?.example).toContain('#59;');
+ expect(mermaid?.example).toContain('"Start (label with punctuation)"');
+ });
+
test('every registry-backed authoring form names a live canonical descriptor', async () => {
const handler = captureRegistration();
const { structuredContent } = await handler({});
diff --git a/packages/server/src/mcp/tools/palette.ts b/packages/server/src/mcp/tools/palette.ts
index 793e69649..5976d3e86 100644
--- a/packages/server/src/mcp/tools/palette.ts
+++ b/packages/server/src/mcp/tools/palette.ts
@@ -125,8 +125,10 @@ const AUTHORING_FORMS: readonly AuthoringFormSeed[] = [
fallbackDisplayName: 'Mermaid diagram',
description: 'Flowchart / sequence / class / state / ER / gantt / pie diagram.',
authoring: 'markdown',
- example: '```mermaid\ngraph LR\n A[Start] --> B[End]\n```',
- guidance: 'Write a ` ```mermaid ` fenced block — it renders as a themed diagram.',
+ example:
+ '```mermaid\ngraph LR\n A["Start (label with punctuation)"] --> B[End]\n```\n\n```mermaid\nsequenceDiagram\n A->>B: request queued #59; retried\n B-->>A: done\n```',
+ guidance:
+ 'Write a ` ```mermaid ` fenced block — it renders as a themed diagram. Sharp edge 1: raw `;` and `#` END message/label text in sequence-family grammars — use commas, or the entity escapes `#59;` / `#35;`. Sharp edge 2: quote flowchart labels containing punctuation (`A["label (with) punctuation"]`). Feedback: parse failures come back as `warnings` entries (kind `mermaid-parse-error`) on write/edit — fix the fence and re-edit.',
},
{
id: 'Math',
diff --git a/packages/server/src/mcp/tools/restore-version.test.ts b/packages/server/src/mcp/tools/restore-version.test.ts
index e94979177..f74d63a9d 100644
--- a/packages/server/src/mcp/tools/restore-version.test.ts
+++ b/packages/server/src/mcp/tools/restore-version.test.ts
@@ -76,7 +76,9 @@ beforeAll(() => {
if (url.pathname === '/api/rollback' && req.method === 'POST') {
return Response.json({
ok: true,
- ...(mockRollbackWarning !== undefined ? { warning: mockRollbackWarning } : {}),
+ ...(mockRollbackWarning !== undefined
+ ? { warning: mockRollbackWarning, warnings: [mockRollbackWarning] }
+ : {}),
});
}
return new Response('Not found', { status: 404 });
@@ -128,7 +130,9 @@ describe('restore_version — registration + behavior', () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ document: 'notes/x', version: SHA });
- expect(result.structuredContent?.contentDivergence).toBeDefined();
+ const warnings = result.structuredContent?.warnings as Array<{ kind: string }> | undefined;
+ expect(warnings).toHaveLength(1);
+ expect(warnings?.[0]?.kind).toBe('content-divergence');
expect(result.content[0]?.text).toContain('Content divergence');
});
diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.ts
index c1cd9c0bb..849f99f49 100644
--- a/packages/server/src/mcp/tools/restore-version.ts
+++ b/packages/server/src/mcp/tools/restore-version.ts
@@ -1,7 +1,7 @@
-import { WriteWarningSchema } from '@inkeep/open-knowledge-core';
+import { AdvisoryWarningSchema } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import type { AgentIdentity } from '../agent-identity.ts';
-import { formatContentDivergenceLine, parseContentDivergence } from './content-divergence.ts';
+import { formatAdvisoryLines, parseAdvisoryWarnings } from './advisory-warnings.ts';
import { resolvePreviewUrlForTool } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
@@ -30,7 +30,7 @@ export const DESCRIPTION = [
'- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).',
'- `summary` — Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Avoid secrets or PII — persisted to git history.',
'',
- 'A response may include `structuredContent.contentDivergence` when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.',
+ 'A response may include `structuredContent.warnings` (kind `content-divergence`) when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.',
].join('\n');
export interface RestoreVersionDeps {
@@ -63,9 +63,13 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
previewUrl: previewUrlOutputField,
previewUrlSource: previewUrlSourceField,
summary: summaryOutputSchema.optional(),
- contentDivergence: WriteWarningSchema.optional().describe(
- 'Present only when the restored Y.Text did not byte-match the target version.',
- ),
+ warnings: z
+ .array(AdvisoryWarningSchema)
+ .min(1)
+ .optional()
+ .describe(
+ 'Advisory entries (kind `content-divergence`): present only when the restored Y.Text did not byte-match the target version.',
+ ),
}),
},
async (args: { document: string; version: string; summary?: string; cwd?: string }) => {
@@ -106,7 +110,7 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
: undefined;
const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
- const contentDivergence = parseContentDivergence(result.warning);
+ const advisoryWarnings = parseAdvisoryWarnings(result.warnings);
const author = typeof versionResult.author === 'string' ? versionResult.author : undefined;
const timestamp =
@@ -116,8 +120,8 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
`Restored "${docName}" to version ${args.version.slice(0, 8)}${provenance}. The change has been applied to all connected editors.`,
];
if (summaryHint) textLines.push(summaryHint);
- if (contentDivergence) {
- textLines.push(formatContentDivergenceLine(contentDivergence));
+ if (advisoryWarnings) {
+ textLines.push(...formatAdvisoryLines(advisoryWarnings));
}
const preview = await resolvePreviewUrlForTool(
@@ -131,7 +135,7 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void
previewUrl: preview?.url ?? null,
...(preview ? { previewUrlSource: preview.source } : {}),
...(summaryResult ? { summary: summaryResult } : {}),
- ...(contentDivergence ? { contentDivergence } : {}),
+ ...(advisoryWarnings ? { warnings: advisoryWarnings } : {}),
});
},
);
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 8eabc9c0d..31b6fb576 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -1,5 +1,5 @@
import { resolve } from 'node:path';
-import { validateDocName, WriteWarningSchema } from '@inkeep/open-knowledge-core';
+import { AdvisoryWarningSchema, validateDocName } from '@inkeep/open-knowledge-core';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import type { Config } from '../../config/schema.ts';
@@ -72,9 +72,13 @@ export const previewAttachWarningField = z
export const documentResultBaseShape = {
summary: summaryOutputSchema.optional(),
- contentDivergence: WriteWarningSchema.optional().describe(
- "Present when the converged Y.Text didn't byte-match the bytes you composed, or when an out-of-band disk edit was reconciled in before your write landed.",
- ),
+ warnings: z
+ .array(AdvisoryWarningSchema)
+ .min(1)
+ .optional()
+ .describe(
+ "Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit.",
+ ),
} as const;
export function nestDocResult(
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 97c547310..c61f21ffd 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -16,10 +16,10 @@ import { resolveTemplatesAvailable } from '../../content/templates-resolver.ts';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import type { AgentIdentity } from '../agent-identity.ts';
import {
- formatContentDivergenceBrief,
- formatContentDivergenceLine,
- parseContentDivergence,
-} from './content-divergence.ts';
+ formatAdvisoryBriefs,
+ formatAdvisoryLines,
+ parseAdvisoryWarnings,
+} from './advisory-warnings.ts';
import { resolveWithinRoot } from './path-safety.ts';
import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
@@ -61,6 +61,8 @@ const BASE_DESCRIPTION = [
'- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',
'- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.',
'- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.',
+ '',
+ 'Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit).',
].join('\n');
export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
@@ -452,13 +454,13 @@ async function handleBatch(
const docOut = results.map((r) => {
if (!r.ok) return { docName: r.docName, ok: false as const, error: r.error };
const preview = resolvePreviewUrl(r.docName, { lockDir });
- const divergence = parseContentDivergence(r.raw.warning);
+ const warnings = parseAdvisoryWarnings(r.raw.warnings);
return {
docName: r.docName,
ok: true as const,
position: r.position,
...(preview ? { previewUrl: preview.url } : {}),
- ...(divergence ? { contentDivergence: divergence } : {}),
+ ...(warnings ? { warnings } : {}),
};
});
const okCount = docOut.filter((d) => d.ok).length;
@@ -470,10 +472,11 @@ async function handleBatch(
return `No change to ${spec.path} — empty ${r.position}, document unchanged.`;
}
const d = docOut[i];
- const base = `Wrote ${spec.path} (${r.position}).`;
- return d?.ok && d.contentDivergence
- ? `${base} ${formatContentDivergenceBrief(d.contentDivergence)}`
- : base;
+ const baseParts = [`Wrote ${spec.path} (${r.position}).`];
+ if (d?.ok && d.warnings) {
+ baseParts.push(...formatAdvisoryBriefs(d.warnings));
+ }
+ return baseParts.join(' ');
});
const perDocNotes = documents.flatMap((spec, i) => {
const r = results[i];
@@ -518,7 +521,7 @@ async function handleSingleDoc(
? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
: undefined;
const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
- const contentDivergence = parseContentDivergence(result.warning);
+ const advisoryWarnings = parseAdvisoryWarnings(result.warnings);
const noOpNote = emptyAppendNoOpNote(w.position, spec.content);
const lines: string[] = [
@@ -537,8 +540,8 @@ async function handleSingleDoc(
if (hint.message) lines.push(hint.message);
}
}
- if (contentDivergence) {
- lines.push(formatContentDivergenceLine(contentDivergence));
+ if (advisoryWarnings) {
+ lines.push(...formatAdvisoryLines(advisoryWarnings));
}
const text = lines.join('\n');
@@ -548,14 +551,14 @@ async function handleSingleDoc(
!noPreviewOnThisDoc &&
!hints &&
!summaryResult &&
- !contentDivergence
+ !advisoryWarnings
) {
return textResult(text);
}
const document: Record<string, unknown> = {};
if (hints) document.hints = hints;
if (summaryResult) document.summary = summaryResult;
- if (contentDivergence) document.contentDivergence = contentDivergence;
+ if (advisoryWarnings) document.warnings = advisoryWarnings;
const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;
return textPlusStructured(text, nestDocResult(preview, warning, document));
}
@@ -703,7 +706,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
documents: looseObjectArray
.optional()
.describe(
- 'Batch write: per-doc result `{ docName, ok, position?, previewUrl?, contentDivergence?, error? }`.',
+ 'Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, error? }`.',
),
previewUrl: previewUrlOutputField.optional(),
previewUrlSource: previewUrlSourceField,
diff --git a/packages/server/src/mermaid-validator.test.ts b/packages/server/src/mermaid-validator.test.ts
new file mode 100644
index 000000000..feaad509c
--- /dev/null
+++ b/packages/server/src/mermaid-validator.test.ts
@@ -0,0 +1,255 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import {
+ extractMermaidFences,
+ setMermaidImporterForTests,
+ validateMermaidFences,
+} from './mermaid-validator.ts';
+
+afterEach(() => {
+ setMermaidImporterForTests(null);
+});
+
+describe('extractMermaidFences', () => {
+ test('extracts a backtick mermaid fence with its first line', () => {
+ const fences = extractMermaidFences('intro\n\n```mermaid\ngraph LR\n A-->B\n```\n\noutro');
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.firstLine).toBe('graph LR');
+ expect(fences[0]?.body).toBe('graph LR\n A-->B');
+ });
+
+ test('extracts tilde fences and multiple fences in order', () => {
+ const fences = extractMermaidFences(
+ '~~~mermaid\npie\n "a": 1\n~~~\n\n```mermaid\nsequenceDiagram\n A->>B: x\n```',
+ );
+ expect(fences.map((f) => f.firstLine)).toEqual(['pie', 'sequenceDiagram']);
+ });
+
+ test('ignores non-mermaid fences and near-miss language tokens', () => {
+ const fences = extractMermaidFences(
+ '```ts\nconst x = 1;\n```\n\n```mermai\ngraph LR\n```\n\n```html preview\n<div/>\n```',
+ );
+ expect(fences).toHaveLength(0);
+ });
+
+ test('does not treat fence-like lines inside a code fence as openers', () => {
+ const fences = extractMermaidFences('````md\n```mermaid\nnot a real fence\n```\n````');
+ expect(fences).toHaveLength(0);
+ });
+
+ test('an unclosed fence runs to end of document (CommonMark)', () => {
+ const fences = extractMermaidFences('```mermaid\ngraph LR\n A-->B');
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.body).toBe('graph LR\n A-->B');
+ });
+
+ test('longer closing runs close shorter openers; shorter ones do not', () => {
+ const fences = extractMermaidFences('````mermaid\ngraph LR\n```\nstill body\n````');
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.body).toBe('graph LR\n```\nstill body');
+ });
+
+ test('empty fence yields an empty first line', () => {
+ const fences = extractMermaidFences('```mermaid\n```');
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.firstLine).toBe('');
+ });
+
+ test('CRLF line endings do not defeat fence boundary detection', () => {
+ const fences = extractMermaidFences('```mermaid\r\ngraph LR\r\n A-->B\r\n```\r\nafter');
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.firstLine).toBe('graph LR');
+ expect(fences[0]?.body).toBe('graph LR\r\n A-->B\r');
+ });
+});
+
+describe('validateMermaidFences — real mermaid (type sweep + globals hygiene)', () => {
+ const VALID_SAMPLES: Record<string, string> = {
+ flowchart: 'graph LR\n A["Start (quoted)"] --> B[End]',
+ sequence: 'sequenceDiagram\n A->>B: hi',
+ class: 'classDiagram\n class Animal {\n +name: string\n }',
+ state: 'stateDiagram-v2\n [*] --> Idle\n Idle --> Done',
+ er: 'erDiagram\n USER ||--o{ ORDER : places',
+ gantt: 'gantt\n title T\n section S\n task1: 2024-01-01, 3d',
+ pie: 'pie\n "a": 40\n "b": 60',
+ mindmap: 'mindmap\n root((center))\n child1',
+ journey: 'journey\n title J\n section S\n step: 5: Me',
+ timeline: 'timeline\n title H\n 2020 : event',
+ gitGraph: 'gitGraph\n commit\n branch dev\n commit',
+ quadrant:
+ 'quadrantChart\n title Q\n x-axis Low --> High\n y-axis Low --> High\n A: [0.1, 0.2]',
+ requirement: 'requirementDiagram\n requirement r1 {\n id: 1\n text: t\n }',
+ c4: 'C4Context\n title T\n Person(p, "P")',
+ sankey: 'sankey-beta\n a,b,10',
+ xychart: 'xychart-beta\n title "T"\n x-axis [a, b]\n bar [1, 2]',
+ block: 'block-beta\n a b',
+ packet: 'packet-beta\n 0-15: "field"',
+ kanban: 'kanban\n todo\n t1[task]',
+ architecture: 'architecture-beta\n group api(cloud)[API]',
+ };
+
+ test('every sampled diagram type parses without warnings', async () => {
+ for (const [name, sample] of Object.entries(VALID_SAMPLES)) {
+ const warnings = await validateMermaidFences(
+ `# Doc\n\n\`\`\`mermaid\n${sample}\n\`\`\`\n`,
+ `sweep-${name}`,
+ );
+ expect(warnings, `expected no warnings for ${name}`).toBeUndefined();
+ }
+ });
+
+ test('invalid samples produce line-numbered parse warnings', async () => {
+ const invalid: Array<[string, string, string]> = [
+ ['sequence', 'sequenceDiagram\n A->>B: hi; there', 'sequenceDiagram'],
+ ['flowchart', 'graph LR\n A[unclosed --> B', 'graph LR'],
+ ['class', 'classDiagram\n class {{{', 'classDiagram'],
+ ];
+ for (const [name, sample, firstLine] of invalid) {
+ const warnings = await validateMermaidFences(
+ `\`\`\`mermaid\n${sample}\n\`\`\``,
+ `sweep-invalid-${name}`,
+ );
+ expect(warnings, `expected a warning for ${name}`).toHaveLength(1);
+ const w = warnings?.[0];
+ expect(w?.kind).toBe('mermaid-parse-error');
+ expect(w?.fenceIndex).toBe(1);
+ expect(w?.fenceFirstLine).toBe(firstLine);
+ expect(w?.message).toContain('Parse error');
+ expect(w?.line).toBeGreaterThan(0);
+ }
+ });
+
+ test('a typo in the diagram header is a warning (it will not render)', async () => {
+ const warnings = await validateMermaidFences('```mermaid\nflowchat LR\n A-->B\n```', 'typo');
+ expect(warnings).toHaveLength(1);
+ });
+
+ test('an empty mermaid fence is a warning (no diagram type detected)', async () => {
+ const warnings = await validateMermaidFences('```mermaid\n```', 'empty-fence');
+ expect(warnings).toHaveLength(1);
+ });
+
+ test('only failing fences warn; valid siblings stay silent', async () => {
+ const warnings = await validateMermaidFences(
+ '```mermaid\ngraph LR\n A-->B\n```\n\n```mermaid\nsequenceDiagram\n A->>B: x; y\n```',
+ 'mixed',
+ );
+ expect(warnings).toHaveLength(1);
+ expect(warnings?.[0]?.fenceIndex).toBe(2);
+ expect(warnings?.[0]?.fenceFirstLine).toBe('sequenceDiagram');
+ });
+
+ test('frontmatter region is excluded from fence scanning', async () => {
+ const warnings = await validateMermaidFences(
+ '---\ntitle: t\n---\n\n```mermaid\ngraph LR\n A-->B\n```',
+ 'with-fm',
+ );
+ expect(warnings).toBeUndefined();
+ });
+
+ test('the server process keeps clean globals after validator init', async () => {
+ await validateMermaidFences('```mermaid\ngraph LR\n A-->B\n```', 'globals');
+ expect(typeof document).toBe('undefined');
+ expect(typeof window).toBe('undefined');
+ });
+
+ test('docs without mermaid fences return undefined without any work', async () => {
+ expect(
+ await validateMermaidFences('# Plain doc\n\nNo diagrams here.', 'plain'),
+ ).toBeUndefined();
+ expect(await validateMermaidFences('mentions mermaid in prose only', 'prose')).toBeUndefined();
+ });
+});
+
+describe('validateMermaidFences — containment (seamed parser)', () => {
+ test('TypeError-class throws are environment skips, not warnings', async () => {
+ setMermaidImporterForTests(async () => ({
+ parse: async () => {
+ throw new TypeError('DOMPurify.addHook is not a function');
+ },
+ }));
+ const warnings = await validateMermaidFences('```mermaid\ngraph LR\n A-->B\n```', 'env-skip');
+ expect(warnings).toBeUndefined();
+ });
+
+ test('import failure memoizes a permanent no-op (single init attempt)', async () => {
+ let attempts = 0;
+ setMermaidImporterForTests(() => {
+ attempts++;
+ return Promise.reject(new Error('platform import failure'));
+ });
+ const doc = '```mermaid\ngraph LR\n A-->B\n```';
+ expect(await validateMermaidFences(doc, 'import-fail-1')).toBeUndefined();
+ expect(await validateMermaidFences(doc, 'import-fail-2')).toBeUndefined();
+ expect(attempts).toBe(1);
+ });
+
+ test('fences over the byte cap are skipped without parsing', async () => {
+ let parsed = 0;
+ setMermaidImporterForTests(async () => ({
+ parse: async () => {
+ parsed++;
+ },
+ }));
+ const bigBody = `sequenceDiagram\n${'A'.repeat(100_001)}`;
+ const hugeFence = `\`\`\`mermaid\n${bigBody}\n\`\`\``;
+ const warnings = await validateMermaidFences(hugeFence, 'byte-cap');
+ expect(warnings).toBeUndefined();
+ expect(parsed).toBe(0);
+ });
+
+ test('fences over the line cap are skipped without parsing', async () => {
+ let parsed = 0;
+ setMermaidImporterForTests(async () => ({
+ parse: async () => {
+ parsed++;
+ },
+ }));
+ const hugeFence = `\`\`\`mermaid\ngraph LR\n${' A-->B\n'.repeat(2_100)}\`\`\``;
+ const warnings = await validateMermaidFences(hugeFence, 'line-cap');
+ expect(warnings).toBeUndefined();
+ expect(parsed).toBe(0);
+ });
+
+ test('fences beyond MAX_FENCES_PARSED (20) are not parsed', async () => {
+ let parsed = 0;
+ setMermaidImporterForTests(async () => ({
+ parse: async (body: string) => {
+ parsed++;
+ if (body.includes('INVALID')) throw new Error('Parse error on line 1: Invalid diagram');
+ },
+ }));
+ const valid = '```mermaid\ngraph LR\n A-->B\n```\n';
+ const invalid = '```mermaid\nINVALID\n```\n';
+ const warnings = await validateMermaidFences(valid.repeat(20) + invalid, 'fence-cap');
+ expect(warnings).toBeUndefined();
+ expect(parsed).toBe(20);
+ });
+
+ test('oversized fences do not consume the parse budget', async () => {
+ let parsed = 0;
+ setMermaidImporterForTests(async () => ({
+ parse: async (body: string) => {
+ parsed++;
+ if (body.includes('INVALID')) throw new Error('Parse error on line 1: Invalid');
+ },
+ }));
+ const oversized = `\`\`\`mermaid\ngraph LR\n${' A-->B\n'.repeat(2_100)}\`\`\`\n`;
+ const invalid = '```mermaid\nINVALID\n```\n';
+ const warnings = await validateMermaidFences(oversized.repeat(25) + invalid, 'budget-skip');
+ expect(warnings).toHaveLength(1);
+ expect(parsed).toBe(1);
+ });
+
+ test('warnings are bounded to 10 entries and messages to 500 chars', async () => {
+ setMermaidImporterForTests(async () => ({
+ parse: async () => {
+ throw new Error(`Parse error on line 2:\n${'x'.repeat(2_000)}`);
+ },
+ }));
+ const fence = '```mermaid\nsequenceDiagram\n A->>B: x; y\n```\n';
+ const warnings = await validateMermaidFences(fence.repeat(14), 'bounds');
+ expect(warnings).toHaveLength(10);
+ expect(warnings?.[0]?.message.length).toBeLessThanOrEqual(500);
+ expect(warnings?.[9]?.fenceIndex).toBe(10);
+ });
+});
diff --git a/packages/server/src/mermaid-validator.ts b/packages/server/src/mermaid-validator.ts
new file mode 100644
index 000000000..e1c29e11a
--- /dev/null
+++ b/packages/server/src/mermaid-validator.ts
@@ -0,0 +1,208 @@
+import { detectFmRegion, type RenderWarning } from '@inkeep/open-knowledge-core';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('mermaid-validator');
+
+const MAX_FENCE_BYTES = 100_000;
+const MAX_FENCE_LINES = 2_000;
+const MAX_FENCES_PARSED = 20;
+const TOTAL_PARSE_BUDGET_MS = 2_000;
+const MAX_WARNINGS = 10;
+const MAX_MESSAGE_CHARS = 500;
+const MAX_FIRST_LINE_CHARS = 200;
+
+interface MermaidFence {
+ firstLine: string;
+ body: string;
+}
+
+type MermaidParseApi = {
+ parse(text: string): Promise<unknown>;
+};
+
+type MermaidImporter = () => Promise<MermaidParseApi | null>;
+
+let initPromise: Promise<MermaidParseApi | null> | null = null;
+let importerOverride: MermaidImporter | null = null;
+
+export function setMermaidImporterForTests(importer: MermaidImporter | null): void {
+ importerOverride = importer;
+ initPromise = null;
+}
+
+export function extractMermaidFences(body: string): MermaidFence[] {
+ const fences: MermaidFence[] = [];
+ const lines = body.split('\n');
+ const fenceLine = (line: string) => (line.endsWith('\r') ? line.slice(0, -1) : line);
+ let i = 0;
+ while (i < lines.length) {
+ const line = fenceLine(lines[i] ?? '');
+ const open = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);
+ if (!open) {
+ i++;
+ continue;
+ }
+ const marker = open[1] ?? '';
+ const fenceChar = marker[0] ?? '`';
+ if (fenceChar === '`' && line.slice(line.indexOf(marker) + marker.length).includes('`')) {
+ i++;
+ continue;
+ }
+ const lang = open[2] ?? '';
+ const closeRe = new RegExp(`^ {0,3}\\${fenceChar}{${marker.length},}[ \t]*$`);
+ const bodyLines: string[] = [];
+ let j = i + 1;
+ while (j < lines.length && !closeRe.test(fenceLine(lines[j] ?? ''))) {
+ bodyLines.push(lines[j] ?? '');
+ j++;
+ }
+ if (lang === 'mermaid') {
+ const body = bodyLines.join('\n');
+ const firstLine = (bodyLines.find((l) => l.trim().length > 0)?.trim() ?? '').slice(
+ 0,
+ MAX_FIRST_LINE_CHARS,
+ );
+ fences.push({ firstLine, body });
+ }
+ i = j + 1;
+ }
+ return fences;
+}
+
+async function initMermaid(): Promise<MermaidParseApi | null> {
+ if (importerOverride) return importerOverride();
+ const { Window } = await import('happy-dom');
+ const win = new Window({ url: 'http://localhost/' });
+ const overrides: Record<string, unknown> = {
+ window: win,
+ document: win.document,
+ navigator: win.navigator,
+ location: win.location,
+ DOMParser: win.DOMParser,
+ Element: win.Element,
+ Node: win.Node,
+ SVGElement: win.SVGElement,
+ HTMLElement: win.HTMLElement,
+ MutationObserver: win.MutationObserver,
+ };
+ const saved = new Map<string, PropertyDescriptor | undefined>();
+ try {
+ for (const [key, value] of Object.entries(overrides)) {
+ saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
+ Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });
+ }
+ const mermaid = (await import('mermaid')).default;
+ mermaid.initialize({
+ startOnLoad: false,
+ securityLevel: 'strict',
+ suppressErrorRendering: true,
+ });
+ await mermaid.parse('graph LR\n A-->B');
+ return mermaid;
+ } finally {
+ for (const [key, desc] of saved) {
+ if (desc) {
+ Object.defineProperty(globalThis, key, desc);
+ } else {
+ delete (globalThis as Record<string, unknown>)[key];
+ }
+ }
+ }
+}
+
+function getMermaid(docName: string): Promise<MermaidParseApi | null> {
+ initPromise ??= initMermaid().catch((err) => {
+ log.warn(
+ { err, 'doc.name': docName },
+ 'mermaid validator unavailable — render validation disabled for this process',
+ );
+ return null;
+ });
+ return initPromise;
+}
+
+function extractLineNumber(message: string): number | undefined {
+ const match = message.match(/Parse error on line (\d+)/);
+ if (!match?.[1]) return undefined;
+ const line = Number(match[1]);
+ return Number.isSafeInteger(line) && line > 0 ? line : undefined;
+}
+
+export async function validateMermaidFences(
+ ytextSnapshot: string,
+ docName: string,
+): Promise<RenderWarning[] | undefined> {
+ try {
+ if (!ytextSnapshot.includes('mermaid')) return undefined;
+ const { body } = detectFmRegion(ytextSnapshot);
+ const fences = extractMermaidFences(body);
+ if (fences.length === 0) return undefined;
+
+ const initStartedAt = performance.now();
+ const mermaid = await getMermaid(docName);
+ if (mermaid === null) return undefined;
+ const parseStartedAt = performance.now();
+
+ const warnings: RenderWarning[] = [];
+ let parsed = 0;
+ for (let i = 0; i < fences.length && warnings.length < MAX_WARNINGS; i++) {
+ if (parsed >= MAX_FENCES_PARSED) break;
+ if (performance.now() - parseStartedAt > TOTAL_PARSE_BUDGET_MS) {
+ log.debug(
+ { 'doc.name': docName, skippedFrom: i + 1, fences: fences.length },
+ 'mermaid validation budget exceeded — remaining fences skipped',
+ );
+ break;
+ }
+ const fence = fences[i];
+ if (fence === undefined) continue;
+ if (fence.body.length > MAX_FENCE_BYTES || fence.body.split('\n').length > MAX_FENCE_LINES) {
+ log.debug(
+ { 'doc.name': docName, fenceIndex: i + 1 },
+ 'mermaid fence over validation caps — skipped',
+ );
+ continue;
+ }
+ try {
+ parsed++;
+ await mermaid.parse(fence.body);
+ } catch (err) {
+ if (err instanceof TypeError) {
+ log.debug(
+ { err, 'doc.name': docName, fenceIndex: i + 1 },
+ 'mermaid validation skipped fence — environment failure',
+ );
+ continue;
+ }
+ const rawMessage = err instanceof Error ? err.message : String(err);
+ const message = rawMessage.slice(0, MAX_MESSAGE_CHARS);
+ const line = extractLineNumber(rawMessage);
+ warnings.push({
+ kind: 'mermaid-parse-error',
+ fenceIndex: i + 1,
+ fenceFirstLine: fence.firstLine,
+ message,
+ ...(line !== undefined ? { line } : {}),
+ });
+ }
+ }
+ const durationMs = Math.round(performance.now() - initStartedAt);
+ if (warnings.length === 0) {
+ if (durationMs > 250) {
+ log.debug(
+ { 'doc.name': docName, durationMs, fences: fences.length },
+ 'mermaid validation slow (no warnings)',
+ );
+ }
+ return undefined;
+ }
+ log.debug(
+ { 'doc.name': docName, count: warnings.length, durationMs },
+ 'mermaid render warnings emitted',
+ );
+ return warnings;
+ } catch (err) {
+ log.warn({ err, 'doc.name': docName }, 'mermaid validation errored unexpectedly — skipped');
+ return undefined;
+ }
+}
diff --git a/packages/server/src/mermaid-version-alignment.test.ts b/packages/server/src/mermaid-version-alignment.test.ts
new file mode 100644
index 000000000..4eccc1afd
--- /dev/null
+++ b/packages/server/src/mermaid-version-alignment.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+test('server and app declare the identical mermaid range', () => {
+ const serverPkg = JSON.parse(readFileSync(join(import.meta.dir, '../package.json'), 'utf8')) as {
+ dependencies?: Record<string, string>;
+ };
+ const appPkg = JSON.parse(
+ readFileSync(join(import.meta.dir, '../../app/package.json'), 'utf8'),
+ ) as { dependencies?: Record<string, string> };
+
+ const serverRange = serverPkg.dependencies?.mermaid;
+ const appRange = appPkg.dependencies?.mermaid;
+ expect(serverRange).toBeDefined();
+ expect(appRange).toBeDefined();
+ expect(serverRange).toBe(appRange as string);
+});