Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): edit standalone .mmd/.mermaid files (#2526)
Andrew Mikofalvyad44115f646a
diff --git a/.changeset/mermaid-file-editing.md b/.changeset/mermaid-file-editing.mdnew file mode 100644index 000000000..b4be27d7e--- /dev/null+++ b/.changeset/mermaid-file-editing.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Standalone Mermaid files (`.mmd` / `.mermaid`) are now editable, matching the WYSIWYG editing you already get for ` ```mermaid ` code fences inside a document. Opening one of these files shows the same rendered diagram — click a flowchart node/edge label, a sequence message, or a participant to edit it in place — and the toolbar's source toggle now opens an editable source view (with Mermaid syntax highlighting) instead of a read-only one. Edits autosave to the file and sync live, since these files are now backed by the same real-time collaboration and undo as every other document.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 0bff7b104..2530f0519 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -44,14 +44,14 @@{"name": "main app bundle (gzipped)","path": "dist/assets/index-*.js",- "limit": "460 kB",+ "limit": "462 kB","gzip": true,"running": false},{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "3.06 MB",+ "limit": "3.07 MB","gzip": true,"running": false},diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex 97927a99d..fc819e458 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -34,7 +34,7 @@* (invalidate + nav), or (c) Activity eviction from the MRU mount list.*/-import { isManagedArtifactDocName } from '@inkeep/open-knowledge-core';+import { isManagedArtifactDocName, isMermaidDocFile } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Loader2, RefreshCw } from 'lucide-react';import {@@ -74,6 +74,13 @@ const ManagedArtifactProperties = lazy(async () => ({default: (await import('./ManagedArtifactProperties')).ManagedArtifactProperties,}));+// Standalone Mermaid doc editor (diagram + editable source). Lazy so the mermaid+// renderer + `codemirror-lang-mermaid` grammar stay out of the first-load bundle+// for projects without any `.mmd`/`.mermaid` files.+const MermaidDocEditor = lazy(async () => ({+ default: (await import('./MermaidDocEditor')).MermaidDocEditor,+}));+/*** Large-doc threshold in Y.Text characters. Above this, the non-active editor* is defer-mounted on cold load instead of pre-mounting both per@@ -424,7 +431,10 @@ function EditorActivityPoolInner({isSourceMode={isSourceMode}editorPlaceholder={editorPlaceholder}isNewDoc={- !loading && !pages.has(entry.docName) && !isManagedArtifactDocName(entry.docName)+ !loading &&+ !pages.has(entry.docName) &&+ !isManagedArtifactDocName(entry.docName) &&+ !isMermaidDocFile(entry.docName)}previousDocName={previousDocName}onNavigateBack={onNavigateBack}@@ -746,6 +756,9 @@ function ActivityEntry({// when the per-doc lifecycle Y.Map changes.const lifecycleStatus = useLifecycleStatus(entry.docName);const isConflict = lifecycleStatus === 'conflict';+ // Standalone Mermaid docs (`.mmd`/`.mermaid`) render a dedicated diagram+source+ // editor instead of the markdown dual-editor (they are Y.Text-only, no bridge).+ const isMermaid = isMermaidDocFile(entry.docName);// Per-Activity portal target for <EditorContent>. Stable DOM element// exclusively owned by THIS ActivityEntry — `useState` with a lazy@@ -985,6 +998,17 @@ function ActivityEntry({not boundaries). Y.Doc identity is unchanged acrossthe swap, so Y.Text content + undo history survive. */<DiffViewBoundary docName={entry.docName} provider={entry.provider} />+ ) : isMermaid ? (+ /* Standalone Mermaid doc: dedicated diagram (wysiwyg) + editable+ source editor, both bound to this doc's Y.Text('source').+ Swaps the editor CHILDREN inside the same DocumentBoundary+ (like the conflict branch above) so the precedent #18(b)+ hybrid render tree + Y.Doc identity are preserved. */+ <MermaidDocEditor+ docName={entry.docName}+ provider={entry.provider}+ isSourceMode={isSourceMode}+ />) : (/* Dual-editor mount with size-gated defer for large docs. Smalldocs render both (pre-mount-both default — mode swap staysdiff --git a/packages/app/src/components/MermaidDocEditor.test.ts b/packages/app/src/components/MermaidDocEditor.test.tsnew file mode 100644index 000000000..356dddb98--- /dev/null+++ b/packages/app/src/components/MermaidDocEditor.test.ts@@ -0,0 +1,113 @@+/**+ * `replaceYText` splices new content into an existing `Y.Text` using the+ * smallest edit that spans the change — the prefix/suffix shrink is the+ * primary WYSIWYG write path (`commitChart → replaceYText`) so its+ * boundary logic needs targeted coverage. A bug in the `start` /+ * `endCur` / `endNext` interactions would produce incorrect splices,+ * manifesting as corrupted diagram labels after a click-edit.+ */++import { describe, expect, test } from 'bun:test';+import * as Y from 'yjs';+import { replaceYText } from './MermaidDocEditor.tsx';++function makeYText(initial: string): { doc: Y.Doc; ytext: Y.Text; events: Y.YTextEvent[] } {+ const doc = new Y.Doc();+ const ytext = doc.getText('source');+ ytext.insert(0, initial);+ const events: Y.YTextEvent[] = [];+ ytext.observe((ev) => events.push(ev));+ return { doc, ytext, events };+}++describe('replaceYText', () => {+ test('identical strings — no-op (no event fires)', () => {+ const { ytext, events } = makeYText('graph LR\n A --> B\n');+ replaceYText(ytext, 'graph LR\n A --> B\n');+ expect(ytext.toString()).toBe('graph LR\n A --> B\n');+ expect(events.length).toBe(0);+ });++ test('prefix-only change splices at the start, preserves the trailing suffix', () => {+ const { ytext, events } = makeYText('OldPrefix middle suffix');+ replaceYText(ytext, 'NewPrefix middle suffix');+ expect(ytext.toString()).toBe('NewPrefix middle suffix');+ // Exactly one splice — the prefix region.+ expect(events.length).toBe(1);+ });++ test('suffix-only change splices at the end, preserves the leading prefix', () => {+ const { ytext, events } = makeYText('prefix middle OldSuffix');+ replaceYText(ytext, 'prefix middle NewSuffix');+ expect(ytext.toString()).toBe('prefix middle NewSuffix');+ expect(events.length).toBe(1);+ });++ test('middle change splices only the differing interior', () => {+ const { ytext } = makeYText('prefix OLD suffix');+ replaceYText(ytext, 'prefix NEW suffix');+ expect(ytext.toString()).toBe('prefix NEW suffix');+ });++ test('complete replacement splices the whole doc', () => {+ const { ytext } = makeYText('graph LR\n A --> B');+ replaceYText(ytext, 'sequenceDiagram\n A->>B: hi');+ expect(ytext.toString()).toBe('sequenceDiagram\n A->>B: hi');+ });++ test('empty → content inserts the whole string', () => {+ const { ytext } = makeYText('');+ replaceYText(ytext, 'graph LR\n A --> B');+ expect(ytext.toString()).toBe('graph LR\n A --> B');+ });++ test('content → empty deletes the whole string', () => {+ const { ytext } = makeYText('graph LR\n A --> B');+ replaceYText(ytext, '');+ expect(ytext.toString()).toBe('');+ });++ test('overlapping prefix/suffix (identical surrounding text) locates the middle change', () => {+ // The classic diff-boundary trap: prefix/suffix common runs meet in+ // the middle. If the algorithm shrinks suffix too aggressively, it+ // will delete or insert the wrong characters.+ const { ytext } = makeYText('abcXabc');+ replaceYText(ytext, 'abcYabc');+ expect(ytext.toString()).toBe('abcYabc');+ });++ test('insertion in a symmetrical repeat preserves both ends', () => {+ const { ytext } = makeYText('abcabc');+ replaceYText(ytext, 'abcZabc');+ expect(ytext.toString()).toBe('abcZabc');+ });++ test('single-character change at the boundary between prefix + suffix', () => {+ const { ytext } = makeYText('aaXaa');+ replaceYText(ytext, 'aaYaa');+ expect(ytext.toString()).toBe('aaYaa');+ });++ test('multi-line mermaid label rewrite (real WYSIWYG shape)', () => {+ // What the WYSIWYG click-edit actually produces: replace one node+ // label mid-chart, everything else unchanged.+ const before = 'graph LR\n Shopper --> Storefront\n Storefront --> Cart\n';+ const after = 'graph LR\n Buyer --> Storefront\n Storefront --> Cart\n';+ const { ytext } = makeYText(before);+ replaceYText(ytext, after);+ expect(ytext.toString()).toBe(after);+ });++ test('splice runs inside a Y.Doc transaction so cursors + peers see one update', () => {+ const doc = new Y.Doc();+ const ytext = doc.getText('source');+ ytext.insert(0, 'prefix OLD suffix');+ let transactionCount = 0;+ doc.on('afterTransaction', () => {+ transactionCount += 1;+ });+ replaceYText(ytext, 'prefix NEW suffix');+ expect(transactionCount).toBe(1);+ expect(ytext.toString()).toBe('prefix NEW suffix');+ });+});diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsxnew file mode 100644index 000000000..fb5158ac2--- /dev/null+++ b/packages/app/src/components/MermaidDocEditor.tsx@@ -0,0 +1,210 @@+/**+ * Editor for a standalone Mermaid doc (`.mmd` / `.mermaid`). These are real+ * Y.Text('source')-only CRDT docs (the markdown bridge is gated off server-side+ * — see `isMermaidDoc`), so both panes bind to the same `Y.Text` and stay in+ * sync live:+ *+ * - Diagram (wysiwyg) mode → the editor's `<MermaidView>` with an `editBinding`+ * that splices click-to-edit label changes back into `Y.Text` — exact parity+ * with codefenced ` ```mermaid ` editing.+ * - Source mode → an editable CodeMirror bound to the same `Y.Text` via+ * `yCollab`, with real Mermaid syntax highlighting (`codemirror-lang-mermaid`,+ * already in the editor bundle) on the shared `propEditorHighlight` style.+ *+ * Driven by the global `isSourceMode` (the toolbar's wysiwyg/source toggle):+ * for a diagram doc, "wysiwyg" == the rendered, editable diagram — consistent+ * with the app's rendered-vs-raw mental model, so no bespoke toggle is needed.+ *+ * Mounted by `EditorActivityPool` inside the doc's `DocumentBoundary` (peer to+ * the conflict `DiffViewBoundary` branch), so `provider` is sync-gated and the+ * precedent #18(b) hybrid render tree is preserved.+ */++import { syntaxHighlighting } from '@codemirror/language';+import { EditorState } from '@codemirror/state';+import { EditorView } from '@codemirror/view';+import type { HocuspocusProvider } from '@hocuspocus/provider';+import { useLingui } from '@lingui/react/macro';+import { basicDarkInit, basicLightInit } from '@uiw/codemirror-theme-basic';+import { basicSetup } from 'codemirror';+import { mermaid } from 'codemirror-lang-mermaid';+import { useTheme } from 'next-themes';+import { useEffect, useRef, useState } from 'react';+import { yCollab } from 'y-codemirror.next';+import * as Y from 'yjs';+import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';+import { type MermaidSourceBinding, MermaidView } from '@/editor/components/Mermaid';++const darkTheme = basicDarkInit({+ settings: { background: 'var(--background)', gutterBackground: 'var(--muted)' },+});+const lightTheme = basicLightInit({+ settings: { background: 'var(--background)', gutterBackground: 'var(--muted)' },+});++/**+ * Replace `Y.Text` content with `next` using the smallest edit that spans the+ * change — keep the common prefix/suffix so `yCollab` peers, cursors, and the+ * undo manager see a targeted splice rather than a whole-document churn.+ */+export function replaceYText(ytext: Y.Text, next: string, origin?: unknown): void {+ const current = ytext.toString();+ if (current === next) return;+ let start = 0;+ const minLen = Math.min(current.length, next.length);+ while (start < minLen && current[start] === next[start]) start += 1;+ let endCur = current.length;+ let endNext = next.length;+ while (endCur > start && endNext > start && current[endCur - 1] === next[endNext - 1]) {+ endCur -= 1;+ endNext -= 1;+ }+ const apply = () => {+ if (endCur > start) ytext.delete(start, endCur - start);+ if (endNext > start) ytext.insert(start, next.slice(start, endNext));+ };+ const doc = ytext.doc;+ if (doc) doc.transact(apply, origin);+ else apply();+}++/**+ * Editable CodeMirror bound to the Mermaid doc's `Y.Text('source')`. The+ * shared `undoManager` is passed to `yCollab` so source-pane typing and+ * diagram-mode label edits share a single undo stack — Ctrl/Cmd+Z in+ * either mode walks through the merged history.+ */+function MermaidSourcePane({+ ytext,+ provider,+ undoManager,+}: {+ ytext: Y.Text;+ provider: HocuspocusProvider;+ undoManager: Y.UndoManager;+}) {+ const containerRef = useRef<HTMLDivElement>(null);+ const { resolvedTheme } = useTheme();++ useEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const theme = resolvedTheme === 'dark' ? darkTheme : lightTheme;+ const view = new EditorView({+ state: EditorState.create({+ doc: ytext.toString(),+ extensions: [+ basicSetup,+ yCollab(ytext, provider.awareness, { undoManager }),+ mermaid(),+ syntaxHighlighting(propEditorHighlight),+ EditorView.lineWrapping,+ EditorView.theme({ '&': { height: '100%' } }),+ theme,+ ],+ }),+ parent: el,+ });+ return () => view.destroy();+ // Rebuild only on doc identity / theme change — yCollab keeps content synced.+ }, [ytext, provider, resolvedTheme, undoManager]);++ return <div ref={containerRef} className="h-full min-h-0 overflow-auto" />;+}++/**+ * Stable transaction origin for diagram-mode label commits. Y.UndoManager+ * only tracks edits whose origin is in `trackedOrigins`; the shared+ * manager below adds this symbol so click-to-edit rewrites become undo+ * steps like any other. Undefined origins would drop off the stack.+ */+const MERMAID_DIAGRAM_EDIT_ORIGIN = Symbol('mermaid-diagram-edit');++export function MermaidDocEditor({+ provider,+ isSourceMode,+}: {+ docName: string;+ provider: HocuspocusProvider;+ isSourceMode: boolean;+}) {+ const { t } = useLingui();+ const ytext = provider.document.getText('source');++ // Live source for the diagram — a label edit committed through the binding (or+ // a source-pane keystroke) mutates `Y.Text`, and this observer re-renders the+ // diagram from the new bytes.+ const [source, setSource] = useState(() => ytext.toString());+ useEffect(() => {+ const sync = () => setSource(ytext.toString());+ ytext.observe(sync);+ sync();+ return () => ytext.unobserve(sync);+ }, [ytext]);++ // Shared UndoManager on the Y.Text — tracks both diagram-mode commits+ // (via MERMAID_DIAGRAM_EDIT_ORIGIN) and source-pane typing (yCollab+ // adds its own sync-conf origin internally via `addTrackedOrigin`).+ // Ctrl/Cmd+Z in either mode walks through the merged stack.+ // The Y.UndoManager listens on the Y.Doc via `afterTransactionHandler`.+ // Don't call `.destroy()` in a StrictMode/HMR cleanup cycle — the same+ // useState instance is re-used on the second effect run, and destroying+ // it silently unhooks the handler so subsequent commits are dropped+ // (visible as an empty undo stack after every edit). The UM is torn+ // down naturally when the Y.Doc is disposed on unmount.+ const [undoManager] = useState(+ () => new Y.UndoManager(ytext, { trackedOrigins: new Set([MERMAID_DIAGRAM_EDIT_ORIGIN]) }),+ );++ const editBinding: MermaidSourceBinding = {+ canEdit: true,+ getChart: () => ytext.toString(),+ commitChart: (next) => replaceYText(ytext, next, MERMAID_DIAGRAM_EDIT_ORIGIN),+ };++ // Diagram-mode keyboard shortcut — Cmd/Ctrl+Z / Cmd/Ctrl+Shift+Z drive+ // the shared UndoManager. Wired at the window level (rather than on+ // the wrapper div) so the shortcut fires without needing focus on the+ // diagram surface itself — SVG has no natural focus target the user+ // clicks into. Source mode's keybinding is owned by yCollab's own+ // y-undomanager keymap (already active while the CodeMirror view has+ // focus, so it wins over this listener when the source pane is open).+ useEffect(() => {+ if (isSourceMode) return;+ const onKey = (e: KeyboardEvent) => {+ const mod = e.metaKey || e.ctrlKey;+ if (!mod || e.key.toLowerCase() !== 'z') return;+ // If the user is typing in an input overlay (label editor) or any+ // contenteditable, let the platform undo handle that input instead.+ const target = e.target;+ if (target instanceof HTMLElement) {+ const tag = target.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable) return;+ }+ e.preventDefault();+ if (e.shiftKey) undoManager.redo();+ else undoManager.undo();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isSourceMode, undoManager]);++ return (+ <main+ className="flex h-full min-h-0 flex-col bg-background"+ aria-label={t`Mermaid diagram`}+ data-mermaid-doc-editor=""+ data-mermaid-doc-editor-mode={isSourceMode ? 'source' : 'diagram'}+ >+ <div className="min-h-0 flex-1 overflow-hidden">+ {isSourceMode ? (+ <MermaidSourcePane ytext={ytext} provider={provider} undoManager={undoManager} />+ ) : (+ <div className="flex h-full min-h-0 flex-col p-3">+ <MermaidView chart={source} editBinding={editBinding} className="min-h-0 flex-1" />+ </div>+ )}+ </div>+ </main>+ );+}diff --git a/packages/app/src/components/file-tree-adapter.ts b/packages/app/src/components/file-tree-adapter.tsindex 2a25f2a2a..6d632337a 100644--- a/packages/app/src/components/file-tree-adapter.ts+++ b/packages/app/src/components/file-tree-adapter.ts@@ -1,4 +1,5 @@import {+ isMermaidDocFile,mediaKindForSidebarAssetExtension,type UploadAssetSuccess,} from '@inkeep/open-knowledge-core';@@ -27,7 +28,10 @@ export function docNameToTreePath(docName: string,docExt: string = DEFAULT_TREE_EXTENSION,): string {- if (TREE_EXTENSION_PATTERN.test(docName)) return docName;+ // A Mermaid docName already carries its `.mmd`/`.mermaid` extension (it IS the+ // filename), so it maps to the tree path verbatim — appending `.md` would+ // point at a nonexistent file and break tree-highlight matching.+ if (TREE_EXTENSION_PATTERN.test(docName) || isMermaidDocFile(docName)) return docName;return `${docName}${docExt}`;}diff --git a/packages/app/src/components/file-tree-selection.test.ts b/packages/app/src/components/file-tree-selection.test.tsindex eba531f87..b346b1198 100644--- a/packages/app/src/components/file-tree-selection.test.ts+++ b/packages/app/src/components/file-tree-selection.test.ts@@ -253,3 +253,20 @@ describe('resolveFileTreeSelectionAction', () => {});});});++describe('resolveFileTreeSelectionAction — Mermaid assets', () => {+ test('routes a mermaid asset row to document navigation (not the asset hash)', () => {+ expect(+ resolveFileTreeSelectionAction('assets/flow.mmd', [+ {+ kind: 'asset',+ path: 'assets/flow.mmd',+ assetExt: '.mmd',+ mediaKind: 'mermaid',+ size: 0,+ modified: '',+ },+ ]),+ ).toEqual({ kind: 'document', path: 'assets/flow.mmd' });+ });+});diff --git a/packages/app/src/components/file-tree-selection.ts b/packages/app/src/components/file-tree-selection.tsindex 1a1567e5f..4967c66e8 100644--- a/packages/app/src/components/file-tree-selection.ts+++ b/packages/app/src/components/file-tree-selection.ts@@ -95,6 +95,12 @@ export function resolveFileTreeSelectionAction(return { kind: 'document', path: documentDocName };}if (entry && isAssetEntry(entry)) {+ // Mermaid files (`.mmd`/`.mermaid`) are served as assets but open as editable+ // CRDT docs, not the read-only asset viewer. Their docName IS the asset path+ // (extension retained), so route the selection as a document.+ if (entry.mediaKind === 'mermaid') {+ return { kind: 'document', path: entry.path };+ }return {kind: 'asset',path: entry.path,diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex 9910bb6c0..451e77281 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -510,3 +510,25 @@ describe('downgradeFolderIndexForHashNav', () => {expect(downgradeFolderIndexForHashNav(missing)).toBe(missing);});});++describe('resolveNavigationTarget — Mermaid docs', () => {+ test('resolves a .mmd / .mermaid path to a doc target even when absent from pages', () => {+ // Mermaid docs are served as assets (never in the markdown page set) but+ // open as editable CRDT docs — the docName retains its extension.+ const pages = new Set<string>();+ expect(resolveNavigationTarget('assets/flow.mmd', { pages })).toEqual({+ kind: 'doc',+ target: 'assets/flow.mmd',+ docName: 'assets/flow.mmd',+ });+ expect(resolveNavigationTarget('diagrams/seq.mermaid', { pages })).toEqual({+ kind: 'doc',+ target: 'diagrams/seq.mermaid',+ docName: 'diagrams/seq.mermaid',+ });+ });++ test('a trailing-slash (folder) form is not treated as a Mermaid doc', () => {+ expect(resolveNavigationTarget('assets/flow.mmd/', { pages: new Set() }).kind).not.toBe('doc');+ });+});diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex e87656b41..7f5ff82ad 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -3,6 +3,7 @@ import {type InlineAssetMediaKind,isDocumentOverOpenByteLimit,isManagedArtifactDocName,+ isMermaidDocFile,managedArtifactDocNameFromContentTarget,parseGlobalSkillBundleDoc,parseManagedArtifactName,@@ -191,6 +192,14 @@ export function resolveNavigationTarget(if (!normalizedTarget) {return { kind: 'missing', target: normalizedTarget };}+ // Standalone Mermaid docs (`assets/flow.mmd`) retain their extension in the+ // docName and live OUTSIDE the markdown `pages` set — the membership checks+ // below would mark them 'missing'. Resolve directly as a doc target (mirrors+ // the managed-artifact early return above) so tree-open / hash nav opens the+ // editable Mermaid doc editor rather than the read-only asset viewer.+ if (!expectsFolder && isMermaidDocFile(normalizedTarget)) {+ return { kind: 'doc', target: normalizedTarget, docName: normalizedTarget };+ }const extensionlessTarget = extensionlessTargetPath(target);if (!expectsFolder && options.pages.has(normalizedTarget)) {diff --git a/packages/app/src/editor/components/Mermaid.dom.test.tsx b/packages/app/src/editor/components/Mermaid.dom.test.tsxindex 88502bdf1..514288ba2 100644--- a/packages/app/src/editor/components/Mermaid.dom.test.tsx+++ b/packages/app/src/editor/components/Mermaid.dom.test.tsx@@ -282,3 +282,30 @@ describe('MermaidView controls', () => {expect(screen.queryByRole('button', { name: 'Zoom in' })).toBeNull();});});++describe('MermaidView editBinding (standalone .mmd path)', () => {+ test('renders an editable diagram with no JSX host when an editBinding is supplied', async () => {+ // The standalone `.mmd` doc path passes an `editBinding` and mounts OUTSIDE+ // any JsxComponentHost. The editable effect (canEdit=true) must run without a+ // host and without throwing; the diagram still renders its toolbar.+ let committed: string | null = null;+ render(+ <TooltipProvider>+ <MermaidView+ chart="graph TD; A-->B;"+ editBinding={{+ canEdit: true,+ getChart: () => 'graph TD; A-->B;',+ commitChart: (next) => {+ committed = next;+ },+ }}+ />+ </TooltipProvider>,+ );+ await waitForPanzoomInstance();+ expect(screen.getByRole('toolbar')).toBeDefined();+ // No label interaction happened, so the binding was not invoked.+ expect(committed).toBeNull();+ });+});diff --git a/packages/app/src/editor/components/Mermaid.test.tsx b/packages/app/src/editor/components/Mermaid.test.tsxindex e6f2cabd7..600873a05 100644--- a/packages/app/src/editor/components/Mermaid.test.tsx+++ b/packages/app/src/editor/components/Mermaid.test.tsx@@ -344,10 +344,18 @@ describe('rewriteSequenceParticipant', () => {expect(out).toContain('Author->>Bob: hi');});- test('bare + display with whitespace forces quoted alias', () => {+ test('bare + display with whitespace stays unquoted (mermaid reads alias to end of line)', () => {const src = 'sequenceDiagram\n participant Author\n';const out = rewriteSequenceParticipant(src, 'Author', 'Alice Smith');- expect(out).toContain('participant Author as "Alice Smith"');+ expect(out).toContain('participant Author as Alice Smith');+ expect(out).not.toContain('"Alice Smith"');+ });++ test('bare + display with a mermaid-syntactic char forces quoted alias', () => {+ const src = 'sequenceDiagram\n participant Author\n';+ const out = rewriteSequenceParticipant(src, 'Author', 'Users[team]');+ // `[` is a mermaid-syntactic delimiter → quote wraps.+ expect(out).toContain('participant Author as "Users[team]"');});test('aliased quoted `X as "Display"` replaces in place', () => {@@ -357,11 +365,41 @@ describe('rewriteSequenceParticipant', () => {expect(out).toContain('A->>Bob: hi');});- test('aliased unquoted `X as Display` replaces in place, adds quotes for special chars', () => {+ test('aliased unquoted `X as Display` — whitespace-only content stays unquoted (mermaid reads alias to end of line)', () => {const src = 'sequenceDiagram\n participant A as Author\n';const out = rewriteSequenceParticipant(src, 'Author', 'Two Words');- // Two words → quotes required.- expect(out).toContain('participant A as "Two Words"');+ // Whitespace is safe inside a participant alias — no wrapping quotes.+ expect(out).toContain('participant A as Two Words');+ expect(out).not.toContain('"Two Words"');+ });++ test('aliased unquoted → quotes only when the new display contains mermaid-syntactic chars', () => {+ const src = 'sequenceDiagram\n participant A as Author\n';+ const out = rewriteSequenceParticipant(src, 'Author', 'Users[team]');+ // `[` is a mermaid-syntactic delimiter → quote.+ expect(out).toContain('participant A as "Users[team]"');+ });++ test('aliased unquoted collapses back to bare when new display equals the id', () => {+ const src = 'sequenceDiagram\n participant Editor as EditorX\n';+ const out = rewriteSequenceParticipant(src, 'EditorX', 'Editor');+ // No redundant `Editor as Editor` — collapse to bare form.+ expect(out).toContain('participant Editor');+ expect(out).not.toContain('as Editor');+ });++ test('aliased quoted collapses back to bare when new display equals the id', () => {+ const src = 'sequenceDiagram\n participant Editor as "EditorX"\n';+ const out = rewriteSequenceParticipant(src, 'EditorX', 'Editor');+ expect(out).toContain('participant Editor');+ expect(out).not.toContain('as');+ });++ test('bare participant → space-in-alias stays unquoted', () => {+ const src = 'sequenceDiagram\n participant Author\n Author->>Bob: hi\n';+ const out = rewriteSequenceParticipant(src, 'Author', 'Author S');+ expect(out).toContain('participant Author as Author S');+ expect(out).not.toContain('"Author S"');});test('actor keyword also supported', () => {diff --git a/packages/app/src/editor/components/Mermaid.tsx b/packages/app/src/editor/components/Mermaid.tsxindex acceee9c6..92bf4d9d1 100644--- a/packages/app/src/editor/components/Mermaid.tsx+++ b/packages/app/src/editor/components/Mermaid.tsx@@ -93,9 +93,29 @@ import { useJsxComponentHost } from './jsx-host-context.tsx';// and no production code path can thread them to this component (the// promoter emits `{chart}` only). Re-adding either to this interface would// create a parallel render-side surface that nothing reaches.+/**+ * Read/write binding for the chart source that backs inline WYSIWYG editing.+ * Decouples `MermaidView` from its edit host so the SAME label-splice machinery+ * serves two surfaces: a codefenced ` ```mermaid ` fence (source lives on a+ * TipTap `jsxComponent` node) and a standalone `.mmd` doc (source is a CRDT+ * `Y.Text`). `getChart` is read live at commit time (never closure-captured) so+ * a concurrent peer edit between click and commit doesn't desync.+ */+export interface MermaidSourceBinding {+ canEdit: boolean;+ getChart: () => string;+ commitChart: (next: string) => void;+}+interface MermaidProps {chart?: string;className?: string;+ /**+ * When provided, inline editing writes back through this binding instead of+ * the JSX-component host (the standalone `.mmd` doc path). Absent for+ * codefenced fences, which derive the binding from `useJsxComponentHost()`.+ */+ editBinding?: MermaidSourceBinding;}interface RenderState {@@ -560,35 +580,47 @@ export function rewriteSequenceParticipant(const kw = '(?:participant|actor)';- // Aliased, quoted: `participant Id as "Display"`- const rQuoted = new RegExp(`^([ \\t]*${kw}[ \\t]+\\S+[ \\t]+as[ \\t]+")${esc}(")`, 'gm');- const mQuoted = findMatch(rQuoted, (m) => `${m[1]}${escapedNew}${m[2]}`);+ // Aliased, quoted: `participant Id as "Display"`. If the new display+ // equals the id, collapse back to bare so we don't leave a redundant+ // `X as X` in the source.+ const rQuoted = new RegExp(+ `^([ \\t]*${kw}[ \\t]+)(\\S+)([ \\t]+as[ \\t]+")${esc}(")([ \\t]*)$`,+ 'gm',+ );+ const mQuoted = findMatch(rQuoted, (m) => {+ const idToken = m[2];+ if (newDisplay === idToken) return `${m[1]}${idToken}${m[5]}`;+ return `${m[1]}${idToken}${m[3]}${escapedNew}${m[4]}${m[5]}`;+ });if (mQuoted)return source.slice(0, mQuoted.range[0]) + mQuoted.replacement + source.slice(mQuoted.range[1]);- // Aliased, unquoted: `participant Id as Display`- const rUnquoted = new RegExp(`^([ \\t]*${kw}[ \\t]+\\S+[ \\t]+as[ \\t]+)${esc}([ \\t]*)$`, 'gm');+ // Aliased, unquoted: `participant Id as Display`. Same collapse rule+ // as the quoted variant when the new display matches the id.+ const rUnquoted = new RegExp(+ `^([ \\t]*${kw}[ \\t]+)(\\S+)([ \\t]+as[ \\t]+)${esc}([ \\t]*)$`,+ 'gm',+ );const mUnquoted = findMatch(rUnquoted, (m) => {- const needsQuote = /[\s"#|;<>&]/.test(newDisplay);- const rendered = needsQuote ? `"${escapedNew}"` : newDisplay;- return `${m[1]}${rendered}${m[2]}`;+ const idToken = m[2];+ if (newDisplay === idToken) return `${m[1]}${idToken}${m[4]}`;+ const rendered = labelNeedsQuoting(newDisplay) ? `"${escapedNew}"` : newDisplay;+ return `${m[1]}${idToken}${m[3]}${rendered}${m[4]}`;});if (mUnquoted)return (source.slice(0, mUnquoted.range[0]) + mUnquoted.replacement + source.slice(mUnquoted.range[1]));- // Bare: `participant Display` — must PRESERVE the id (Display is- // used as an id elsewhere in the chart via `Display->>Other`), so- // add an `as "New"` alias instead of overwriting.+ // Bare: `participant Display` — the display IS the id, referenced+ // elsewhere via `Display->>Other`, so preserve it and add an+ // `as "New"` alias instead of overwriting. Quoting rule unified with+ // the aliased variants: whitespace is safe in a participant alias+ // (mermaid reads the alias to end of line), so only quote when the+ // new label contains an actual mermaid-syntactic delimiter.const rBare = new RegExp(`^([ \\t]*${kw}[ \\t]+)${esc}([ \\t]*)$`, 'gm');const mBare = findMatch(rBare, (m) => {- // Unquoted-alias when the new display is a simple identifier- // (letters/digits/underscore, no whitespace or mermaid-syntactic- // chars). Otherwise wrap in quotes. Mermaid renders literal quotes- // when they're used unnecessarily, so keep the source clean.- const needsQuote = /[^\w]/.test(newDisplay);- const rendered = needsQuote ? `"${escapedNew}"` : newDisplay;+ const rendered = labelNeedsQuoting(newDisplay) ? `"${escapedNew}"` : newDisplay;return `${m[1]}${currentDisplay}${m[2]} as ${rendered}`;});if (mBare)@@ -717,7 +749,7 @@ export function findSequenceBlockConditionInSource(return null;}-export function MermaidView({ chart = '', className }: MermaidProps) {+export function MermaidView({ chart = '', className, editBinding }: MermaidProps) {const reactId = useId();const renderId = `mermaid-${reactId.replaceAll(':', '_')}`;const [state, setState] = useState<RenderState>({ status: 'idle', svg: '', error: '' });@@ -741,7 +773,9 @@ export function MermaidView({ chart = '', className }: MermaidProps) {return () => observer.disconnect();}, []);const host = useJsxComponentHost();- const canEdit = host?.editor.isEditable ?? false;+ // An explicit `editBinding` (standalone `.mmd` doc) wins; otherwise editing is+ // gated on the JSX host being editable (codefenced fence).+ const canEdit = editBinding ? editBinding.canEdit : (host?.editor.isEditable ?? false);const containerRef = useRef<HTMLDivElement>(null);// `useJsxComponentHost()` returns a fresh object literal on every// parent render (JsxComponentView constructs `{editor, getPos, ...}`@@ -757,6 +791,14 @@ export function MermaidView({ chart = '', className }: MermaidProps) {useLayoutEffect(() => {hostRef.current = host;}, [host]);+ // Same ref treatment for the optional standalone binding: the parent may+ // hand a fresh object each render, so read it live through the ref inside+ // handlers to keep the edit-session effect deps (`[state.status, canEdit]`)+ // stable.+ const editBindingRef = useRef(editBinding);+ useLayoutEffect(() => {+ editBindingRef.current = editBinding;+ }, [editBinding]);// Tracks the currently-editing label so we can tear it down cleanly// when the SVG re-renders (or component unmounts) mid-edit.const editSessionRef = useRef<{ cleanup: () => void } | null>(null);@@ -813,7 +855,28 @@ export function MermaidView({ chart = '', className }: MermaidProps) {// handler effect below so the same helper owns both the widened// hit-testing and the delegated click routing.- function commitLabelChangeGeneric(target: EditTarget, newLabel: string): void {+ // Read the current chart source live at call time. Standalone binding wins;+ // otherwise read the JSX-host `jsxComponent` node's `chart` prop.+ function readChartSource(): string | null {+ const binding = editBindingRef.current;+ if (binding) return binding.getChart();+ const h = hostRef.current;+ if (!h) return null;+ const pos = h.getPos();+ if (typeof pos !== 'number') return null;+ const node = h.editor.state.doc.nodeAt(pos);+ if (!node || node.type.name !== 'jsxComponent') return null;+ return ((node.attrs.props as Record<string, unknown>)?.chart as string) ?? '';+ }++ // Write the new chart source back. Standalone binding wins; otherwise+ // dispatch one `setNodeMarkup` on the JSX-host `jsxComponent` node.+ function commitChartSource(newChart: string): void {+ const binding = editBindingRef.current;+ if (binding) {+ binding.commitChart(newChart);+ return;+ }const h = hostRef.current;if (!h) return;const pos = h.getPos();@@ -821,17 +884,6 @@ export function MermaidView({ chart = '', className }: MermaidProps) {const node = h.editor.state.doc.nodeAt(pos);if (!node || node.type.name !== 'jsxComponent') return;const currentProps = (node.attrs.props as Record<string, unknown>) ?? {};- const chartNow = (currentProps.chart as string) ?? '';- // Prefer applyRewrite (participant paths); otherwise fall back- // to locate + spliceNewLabel.- let newChart: string | null = null;- if (target.applyRewrite) {- newChart = target.applyRewrite(chartNow, newLabel);- } else if (target.locate) {- const match = target.locate(chartNow);- if (match) newChart = spliceNewLabel(chartNow, match, newLabel);- }- if (newChart === null) return;// `setNodeMarkup` throws `RangeError` when `pos` has been// invalidated by a concurrent CRDT update between `getPos()` and// dispatch. That's a benign miss (the user's next mount resyncs@@ -850,6 +902,22 @@ export function MermaidView({ chart = '', className }: MermaidProps) {}}+ function commitLabelChangeGeneric(target: EditTarget, newLabel: string): void {+ const chartNow = readChartSource();+ if (chartNow === null) return;+ // Prefer applyRewrite (participant paths); otherwise fall back+ // to locate + spliceNewLabel.+ let newChart: string | null = null;+ if (target.applyRewrite) {+ newChart = target.applyRewrite(chartNow, newLabel);+ } else if (target.locate) {+ const match = target.locate(chartNow);+ if (match) newChart = spliceNewLabel(chartNow, match, newLabel);+ }+ if (newChart === null) return;+ commitChartSource(newChart);+ }+interface EditTarget {labelSpan: HTMLElement;// The SVG element (rect/polygon/path...) whose stroke we widen to@@ -888,13 +956,8 @@ export function MermaidView({ chart = '', className }: MermaidProps) {function tryEnterEditWithTarget(target: EditTarget, event: MouseEvent): boolean {const { labelSpan, outlineShape } = target;- const h = hostRef.current;- if (!h) return false;- const pos = h.getPos();- if (typeof pos !== 'number') return false;- const pmNode = h.editor.state.doc.nodeAt(pos);- if (!pmNode || pmNode.type.name !== 'jsxComponent') return false;- const currentChart = ((pmNode.attrs.props as Record<string, unknown>)?.chart as string) ?? '';+ const currentChart = readChartSource();+ if (currentChart === null) return false;const currentLabel = target.sourceLabel ?? (labelSpan.textContent ?? '').trim();if (!currentLabel) return false;const rewriteHit = target.applyRewrite?.(currentChart, currentLabel);diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex ca26c2bfa..326b567ed 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -818,6 +818,16 @@padding-bottom: var(--ask-composer-height, 0px);}+/* Standalone Mermaid docs render OUTSIDE `.editor-doc-scroll` — a diagram ++ source pane, not a ProseMirror/CM scroll surface — so the inset above never+ reaches them. Reserve the composer height on the whole editor so a full-page+ panzoom diagram (which does not scroll) and the source pane's last lines clear+ the floating card. The var is 0 when the composer is collapsed/hidden, so the+ space is reclaimed with no class to fall out of sync. */+[data-mermaid-doc-editor] {+ padding-bottom: var(--ask-composer-height, 0px);+}+/* Conflict-mode DiffView scroller: same composer inset so the last hunks (andtheir inline Accept/Reject controls) can scroll clear of the floatingcomposer. The content-side padding rule lives next to thediff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex f56307b6e..5ddd785b2 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -380,6 +380,7 @@"8Jm2EP": ["Toggle heading levels 1 through 6."],"8OGgNM": ["Open or close visual-editor find."],"8OxKZy": ["Move succeeded but the sidebar may be out of date — refresh to resync"],+ "8PifYj": ["Mermaid diagram"],"8PmoQF": ["Open the insert menu in an empty or active text position."],"8RtNI0": ["Failed to load documents"],"8XQRON": ["Loading repositories"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 0f7f7820f..8163f96ec 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4119,6 +4119,10 @@ msgstr "MCP connections"msgid "Medium section heading."msgstr "Medium section heading."+#: src/components/MermaidDocEditor.tsx+msgid "Mermaid diagram"+msgstr "Mermaid diagram"+#: src/editor/components/Mermaid.tsxmsgid "Mermaid diagram controls"msgstr "Mermaid diagram controls"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 539d609cb..e545a2a79 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -380,6 +380,7 @@"8Jm2EP": ["Ţōĝĝĺē ĥēàďĩńĝ ĺēvēĺś 1 ţĥŕōũĝĥ 6."],"8OGgNM": ["Ōƥēń ōŕ ćĺōśē vĩśũàĺ-ēďĩţōŕ ƒĩńď."],"8OxKZy": ["Ḿōvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],+ "8PifYj": ["Ḿēŕḿàĩď ďĩàĝŕàḿ"],"8PmoQF": ["Ōƥēń ţĥē ĩńśēŕţ ḿēńũ ĩń àń ēḿƥţŷ ōŕ àćţĩvē ţēxţ ƥōśĩţĩōń."],"8RtNI0": ["Ƒàĩĺēď ţō ĺōàď ďōćũḿēńţś"],"8XQRON": ["Ĺōàďĩńĝ ŕēƥōśĩţōŕĩēś"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex c14847de9..5f5693e43 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4114,6 +4114,10 @@ msgstr ""msgid "Medium section heading."msgstr ""+#: src/components/MermaidDocEditor.tsx+msgid "Mermaid diagram"+msgstr ""+#: src/editor/components/Mermaid.tsxmsgid "Mermaid diagram controls"msgstr ""diff --git a/packages/core/src/constants/upload.test.ts b/packages/core/src/constants/upload.test.tsindex 1fc0e1523..7ed1d5ff7 100644--- a/packages/core/src/constants/upload.test.ts+++ b/packages/core/src/constants/upload.test.ts@@ -5,6 +5,7 @@ import {FILE_ATTACHMENT_EXTENSIONS,IMAGE_EXTENSIONS,INLINE_RENDERABLE_EXTENSIONS,+ isMermaidDocFile,LINKABLE_ASSET_EXTENSIONS,MERMAID_FILE_EXTENSIONS,mediaKindForSidebarAssetExtension,@@ -259,3 +260,25 @@ describe('mediaKindForSidebarAssetExtension', () => {expect(mediaKindForSidebarAssetExtension('PDF')).toBe('pdf');});});++describe('isMermaidDocFile', () => {+ test('true for .mmd / .mermaid paths (any casing)', () => {+ expect(isMermaidDocFile('assets/flow.mmd')).toBe(true);+ expect(isMermaidDocFile('diagram.mermaid')).toBe(true);+ expect(isMermaidDocFile('deep/nested/chart.MMD')).toBe(true);+ });++ test('false for markdown + other extensions + extension-less names', () => {+ expect(isMermaidDocFile('notes/todo.md')).toBe(false);+ expect(isMermaidDocFile('docs/guide.mdx')).toBe(false);+ expect(isMermaidDocFile('assets/photo.png')).toBe(false);+ expect(isMermaidDocFile('reports/index')).toBe(false);+ expect(isMermaidDocFile('README')).toBe(false);+ });++ test('matches only the final extension segment', () => {+ // A markdown doc whose stem merely contains `mmd`/`mermaid` is not a match.+ expect(isMermaidDocFile('mmd-notes/plan')).toBe(false);+ expect(isMermaidDocFile('flow.mmd.md')).toBe(false);+ });+});diff --git a/packages/core/src/constants/upload.ts b/packages/core/src/constants/upload.tsindex 7f603687c..4323f5b85 100644--- a/packages/core/src/constants/upload.ts+++ b/packages/core/src/constants/upload.ts@@ -681,6 +681,23 @@ export const TEXT_VIEWER_FALLBACK_EXTENSIONS: ReadonlySet<string> = new Set(['ba// view in the app-side viewer, so the file always reads.export const MERMAID_FILE_EXTENSIONS: ReadonlySet<string> = new Set(['mmd', 'mermaid']);+/**+ * True when a path/docName names a standalone Mermaid source file. Pure string+ * op (no `node:path`) so it runs in the browser too — core stays server-free.+ *+ * Unlike markdown docNames (which are extension-LESS), a Mermaid doc's docName+ * RETAINS its extension (`assets/flow.mmd`), so this predicate doubles as the+ * `isMermaidDoc(documentName)` doc-class discriminator. Edge case: a markdown+ * file literally named `X.mermaid.md` strips to docName `X.mermaid` and would+ * collide here — pathological and unsupported (name markdown files without a+ * trailing `.mmd`/`.mermaid` stem segment).+ */+export function isMermaidDocFile(path: string): boolean {+ const lastDot = path.lastIndexOf('.');+ if (lastDot < 0) return false;+ return MERMAID_FILE_EXTENSIONS.has(path.slice(lastDot + 1).toLowerCase());+}+// Code-file extensions live in a sibling module so the// language→extension table can be shared with the app-side TextViewer// (which maps the same canonical IDs to CodeMirror language packs).diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f0753aa30..a14122f75 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -242,6 +242,7 @@ export {IMAGE_EXTENSIONS,INLINE_RENDERABLE_EXTENSIONS,type InlineAssetMediaKind,+ isMermaidDocFile,LINKABLE_ASSET_EXTENSIONS,MERMAID_FILE_EXTENSIONS,mediaKindForSidebarAssetExtension,diff --git a/packages/server/src/cc1-broadcast.ts b/packages/server/src/cc1-broadcast.tsindex 39bb3d81b..ad3417afb 100644--- a/packages/server/src/cc1-broadcast.ts+++ b/packages/server/src/cc1-broadcast.ts@@ -16,6 +16,7 @@ import {type ConfigValidationError,type DerivedViewChannel,isManagedArtifactDocName,+ isMermaidDocFile,SYSTEM_DOC_NAME,} from '@inkeep/open-knowledge-core';import { getLogger } from './logger.ts';@@ -79,6 +80,25 @@ export function isManagedArtifactDoc(documentName: string): boolean {return isManagedArtifactDocName(documentName);}+/**+ * True for standalone Mermaid docs — `.mmd` / `.mermaid` files whose docName+ * RETAINS its extension (`assets/flow.mmd`). A FOURTH doc class:+ *+ * - like CONFIG docs on the persistence-body axis — `Y.Text('source')`-only,+ * the markdown observer bridge is gated OFF (source stored verbatim, no+ * remark round-trip that would corrupt diagram syntax);+ * - but UNLIKE config/managed-artifact docs on admission — a Mermaid doc is+ * real user content: it stays in the document tree AND the link/graph index.+ * So it must NOT join `isReservedForUserTree` or `isLinkIndexExcludedDoc`;+ * tree/index sites let it fall through as normal content.+ *+ * Bridge / persistence dispatch sites short-circuit on this (like `isConfigDoc`)+ * so a Mermaid doc never runs the markdown bridge or the XmlFragment store path.+ */+export function isMermaidDoc(documentName: string): boolean {+ return isMermaidDocFile(documentName);+}+/*** True when a doc name must be hidden from the user document tree / search /* create-page surfaces — system, config, AND managed-artifact docs. This is thediff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.tsindex 9a97558a4..0f23b93f2 100644--- a/packages/server/src/doc-extensions.test.ts+++ b/packages/server/src/doc-extensions.test.ts@@ -79,6 +79,13 @@ describe('docNameToRelativePath', () => {test('defaults extension-less docNames to .md', () => {expect(docNameToRelativePath('docs/new')).toBe('docs/new.md');});++ test('returns Mermaid docNames verbatim (extension retained, no .md appended)', () => {+ // A Mermaid docName IS the filename (`assets/flow.mmd`) — it must map 1:1 to+ // the on-disk path, never `assets/flow.mmd.md`.+ expect(docNameToRelativePath('assets/flow.mmd')).toBe('assets/flow.mmd');+ expect(docNameToRelativePath('diagrams/seq.mermaid')).toBe('diagrams/seq.mermaid');+ });});describe('registerDocExtension / getDocExtension', () => {diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex 6552c6b0d..9c692d43f 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -29,6 +29,7 @@ import { extname } from 'node:path';import {DEFAULT_DOC_EXTENSION,type DocExtension,+ isMermaidDocFile,SUPPORTED_DOC_EXTENSIONS,} from '@inkeep/open-knowledge-core';@@ -167,7 +168,12 @@ export function getDocExtension(docName: string): string {* traversal validation against their target root after resolving the result.*/export function docNameToRelativePath(docName: string): string {- return isSupportedDocFile(docName) ? docName : `${docName}${getDocExtension(docName)}`;+ // Mermaid docs (`assets/flow.mmd`) retain their extension in the docName, so+ // — like `.md`/`.mdx` supported docs — the docName IS already the full+ // filename; only extension-less markdown docNames get an extension appended.+ return isSupportedDocFile(docName) || isMermaidDocFile(docName)+ ? docName+ : `${docName}${getDocExtension(docName)}`;}/** Clear the recorded extension for a docName (e.g. on file delete). */diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.tsindex eca6a32ed..fda5b12c9 100644--- a/packages/server/src/external-change.ts+++ b/packages/server/src/external-change.ts@@ -18,7 +18,7 @@ import {import { formatReconcileSubject } from '@inkeep/open-knowledge-core/shadow-repo-layout';import type * as Y from 'yjs';import { composeAndWriteRawBody } from './bridge-intake.ts';-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';+import { isConfigDoc, isMermaidDoc, isSystemDoc } from './cc1-broadcast.ts';import { isDocInConflict } from './conflict-errors.ts';import { recordContributor } from './contributor-tracker.ts';import { recordFrontmatterEditSurface } from './frontmatter-telemetry.ts';@@ -133,7 +133,7 @@ export function applyExternalChange(resolveEmbed?: (basename: string, sourcePath: string) => string | null,resolveSize?: (basename: string, sourcePath: string) => number | null,): void {- if (isSystemDoc(docName) || isConfigDoc(docName)) return;+ if (isSystemDoc(docName) || isConfigDoc(docName) || isMermaidDoc(docName)) return;const document = hocuspocus.documents.get(docName);if (!document) return;@@ -361,7 +361,7 @@ export function reconcileDiskBeforeAgentWrite(contentDir: string,resolveEmbed?: (basename: string, sourcePath: string) => string | null,): ReconcileBeforeWriteResult {- if (isSystemDoc(docName) || isConfigDoc(docName)) return NOT_RECONCILED;+ if (isSystemDoc(docName) || isConfigDoc(docName) || isMermaidDoc(docName)) return NOT_RECONCILED;// Never reconcile a doc that's mid-conflict: disk carries merge markers, and// the mutating write is about to be refused with DocInConflictError. Ingestingdiff --git a/packages/server/src/mermaid-persistence.test.ts b/packages/server/src/mermaid-persistence.test.tsnew file mode 100644index 000000000..2bbcf0c25--- /dev/null+++ b/packages/server/src/mermaid-persistence.test.ts@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';+import * as Y from 'yjs';+import {+ loadMermaidDoc,+ MERMAID_SOURCE_ORIGIN,+ type MermaidPersistenceCtx,+ storeMermaidDoc,+} from './mermaid-persistence.ts';++let contentDir: string;++function makeCtx(): MermaidPersistenceCtx {+ return { contentDir, lkgCache: new Map<string, string>() };+}++// A Mermaid docName retains its extension (`assets/flow.mmd`) — it maps 1:1 to+// the on-disk file relative to contentDir.+const DOC = 'assets/flow.mmd';+const ABS = () => resolve(contentDir, DOC);+const SRC = 'graph TD;\n A[Start] --> B{Choice};\n B -->|Yes| C[Go];\n';++/** Write the `.mmd` file to disk, creating its parent dir first. */+function writeMmd(content: string): void {+ mkdirSync(dirname(ABS()), { recursive: true });+ writeFileSync(ABS(), content, 'utf-8');+}++beforeEach(() => {+ contentDir = mkdtempSync(join(tmpdir(), 'ok-mermaid-'));+});+afterEach(() => {+ rmSync(contentDir, { recursive: true, force: true });+});++describe('storeMermaidDoc', () => {+ test('persists Y.Text("source") verbatim to the .mmd file', async () => {+ const ctx = makeCtx();+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('persisted');+ expect(readFileSync(ABS(), 'utf-8')).toBe(SRC);+ });++ test('stores source with markdown-syntactic + blank-line content byte-for-byte (no remark round-trip)', async () => {+ const ctx = makeCtx();+ // Content that a markdown pipeline would normalize (blank lines, `#`, `>`,+ // trailing spaces). A Mermaid doc must persist it unchanged.+ const awkward = '## not a heading\n\n\n> not a quote \ngraph LR; A-->B;\n';+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, awkward), 'agent');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('persisted');+ expect(readFileSync(ABS(), 'utf-8')).toBe(awkward);+ });++ test('no-op when the store originates from a seed/reconcile import (skip-store origin)', async () => {+ const ctx = makeCtx();+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');+ expect(await storeMermaidDoc(doc, DOC, MERMAID_SOURCE_ORIGIN, ctx)).toBe('no-op');+ });++ test('no-op on the second identical store (LKG equality guard)', async () => {+ const ctx = makeCtx();+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('persisted');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('no-op');+ });++ test('reconciles (imports disk) instead of clobbering when an external writer diverged from LKG', async () => {+ const ctx = makeCtx();+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('persisted');++ // Simulate a concurrent external edit landing on disk since our LKG.+ const external = 'sequenceDiagram; Alice->>Bob: Hi;\n';+ writeMmd(external);++ // A subsequent in-app edit tries to store — disk wins.+ doc.transact(() => {+ const yt = doc.getText('source');+ yt.delete(0, yt.length);+ yt.insert(0, 'graph TD; X-->Y;\n');+ }, 'agent');+ expect(await storeMermaidDoc(doc, DOC, 'agent', ctx)).toBe('reconciled');+ expect(doc.getText('source').toString()).toBe(external);+ expect(readFileSync(ABS(), 'utf-8')).toBe(external);+ // After reconcile the LKG cache MUST hold the imported disk bytes,+ // otherwise the next store will re-detect divergence and reconcile+ // in a loop (or worse, treat the imported bytes as a fresh in-app+ // edit and clobber the external writer's next update).+ expect(ctx.lkgCache.get(DOC)).toBe(external);+ });+});++describe('loadMermaidDoc', () => {+ test('seeds Y.Text("source") from disk and mints a lineage epoch', () => {+ writeMmd(SRC);+ const ctx = makeCtx();+ const doc = new Y.Doc();+ loadMermaidDoc(doc, DOC, ctx);+ expect(doc.getText('source').toString()).toBe(SRC);+ expect(typeof doc.getMap('lifecycle').get(LINEAGE_EPOCH_KEY)).toBe('string');+ // The XmlFragment stays empty — these docs are Y.Text-only (bridge off).+ expect(doc.getXmlFragment('default').length).toBe(0);+ });++ test('lazy: a missing file seeds nothing (admitting a doc never creates disk)', () => {+ const ctx = makeCtx();+ const doc = new Y.Doc();+ loadMermaidDoc(doc, DOC, ctx);+ expect(doc.getText('source').toString()).toBe('');+ });++ test('idempotent: does not re-seed when Y.Text is already populated', () => {+ writeMmd(SRC);+ const ctx = makeCtx();+ const doc = new Y.Doc();+ doc.transact(() => doc.getText('source').insert(0, 'pre-existing'), 'agent');+ loadMermaidDoc(doc, DOC, ctx);+ expect(doc.getText('source').toString()).toBe('pre-existing');+ });++ test('round-trips store → load through disk unchanged', async () => {+ const ctx = makeCtx();+ const writeDoc = new Y.Doc();+ writeDoc.transact(() => writeDoc.getText('source').insert(0, SRC), 'agent');+ await storeMermaidDoc(writeDoc, DOC, 'agent', ctx);++ const readDoc = new Y.Doc();+ loadMermaidDoc(readDoc, DOC, makeCtx());+ expect(readDoc.getText('source').toString()).toBe(SRC);+ });+});diff --git a/packages/server/src/mermaid-persistence.ts b/packages/server/src/mermaid-persistence.tsnew file mode 100644index 000000000..78ab71e33--- /dev/null+++ b/packages/server/src/mermaid-persistence.ts@@ -0,0 +1,201 @@+/**+ * Persistence for standalone Mermaid docs — `.mmd` / `.mermaid` files whose+ * docName RETAINS its extension (`assets/flow.mmd`). A FOURTH doc class.+ *+ * Shape: config-persistence's Y.Text-only body handling — the markdown observer+ * bridge is gated OFF for these (see `server-observer-extension.ts` /+ * `isMermaidDoc`), so the diagram source is stored VERBATIM. Routing the source+ * through the markdown pipeline (as `.md`/`.mdx` docs do) would re-canonicalize+ * it (blank-line normalization, escaping, fence promotion) and corrupt Mermaid+ * syntax. Verbatim fidelity (precedent #38, Y.Text-is-truth): the store+ * serializes from `Y.Text('source')` and never touches the XmlFragment.+ *+ * Unlike config docs (bounded `.ok/` set, schema-validated) these are arbitrary+ * user content files: no validation (any text is a valid `.mmd` — parse-failing+ * content still renders as source), and path resolution goes to the content dir.+ * A concurrent external writer (CLI / another editor) is caught by a+ * read-before-write reconcile; no file lock is taken (one server per contentDir+ * per `server.lock`, and Hocuspocus serializes `onStoreDocument` per doc).+ *+ * The path resolver is replicated here (rather than importing `safeContentPath`+ * from `persistence.ts`) to avoid a circular import — `persistence.ts` imports+ * this module for its dispatch branch.+ */++import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import type { LocalTransactionOrigin } from '@hocuspocus/server';+import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';+import type * as Y from 'yjs';+import { docNameToRelativePath } from './doc-extensions.ts';+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';+import { getLogger } from './logger.ts';+import { isWithinDir } from './path-utils.ts';++const log = getLogger('mermaid-persistence');++/**+ * Transaction origin for Mermaid seed / reconcile / external-import writes to+ * `Y.Text('source')`. `skipStoreHooks: true` so seeding never re-triggers a disk+ * write. Deliberately NOT `FILE_WATCHER_ORIGIN`: that origin is `paired: true`+ * (it mutates BOTH Y.Text and Y.XmlFragment and must route through a bridge-intake+ * primitive — enforced by `paired-write-enforcement.test.ts`). Mermaid docs are+ * Y.Text-only (the markdown bridge is gated off), so this origin is NON-paired,+ * mirroring config docs' `CONFIG_VALIDATION_REVERT_ORIGIN` (registered in that+ * test's SANCTIONED_NON_PRIMITIVE_ORIGINS for the identical reason).+ */+export const MERMAID_SOURCE_ORIGIN = {+ source: 'local' as const,+ skipStoreHooks: true,+ context: { origin: 'mermaid-source' },+} as const satisfies LocalTransactionOrigin;++export interface MermaidPersistenceCtx {+ /** Content root — a Mermaid doc resolves to `<contentDir>/<docName>`. */+ contentDir: string;+ /**+ * Per-server-instance last-known-good cache: the verbatim bytes last loaded+ * from or written to disk. Drives the store short-circuit, the concurrent-+ * writer reconcile, and the file-watcher self-write guard. Its own cache+ * (distinct doc-name space from the config / managed-artifact LKG caches).+ */+ lkgCache: Map<string, string>;+}++/** Store outcome — surfaced for tests + telemetry. */+export type StoreMermaidOutcome = 'persisted' | 'no-op' | 'reconciled' | 'write-failed';++/**+ * Resolve + containment-guard the on-disk path for a Mermaid docName. Mirrors+ * `safeContentPath` (NUL guard + `docNameToRelativePath` + within-dir check);+ * `docNameToRelativePath` returns a `.mmd` docName verbatim (it retains its ext).+ */+function mermaidAbsPath(documentName: string, contentDir: string): string {+ if (documentName.includes('\x00')) {+ throw new Error(`Invalid document name: ${documentName}`);+ }+ const filePath = resolve(contentDir, docNameToRelativePath(documentName));+ if (!isWithinDir(filePath, contentDir)) {+ throw new Error(`Invalid document name: ${documentName}`);+ }+ return filePath;+}++/**+ * Replace the whole `Y.Text('source')` with `raw` under `MERMAID_SOURCE_ORIGIN`+ * (`skipStoreHooks: true`, so seeding never re-triggers a disk write). Full+ * delete+insert rather than a diff: external-disk / reconcile imports are rare,+ * and yCollab merges the replacement for connected peers.+ */+function replaceSource(document: Y.Doc, raw: string, bumpLineage: boolean): void {+ const ytext = document.getText('source');+ document.transact(() => {+ if (ytext.length > 0) ytext.delete(0, ytext.length);+ if (raw.length > 0) ytext.insert(0, raw);+ if (bumpLineage) {+ // Fresh Yjs lineage per seed-from-disk (mirrors the content + managed-+ // artifact load paths): no Y-binary survives an unload, so the source is+ // re-inserted under fresh client IDs. Without an epoch a client's prior-+ // lineage IndexedDB copy would rejoin and concatenate the two independent+ // same-text insertions (self-duplication). Reconcile/external imports do+ // NOT bump — they mutate an already-established lineage.+ document.getMap('lifecycle').set(LINEAGE_EPOCH_KEY, crypto.randomUUID());+ }+ }, MERMAID_SOURCE_ORIGIN);+}++/**+ * Seed a Mermaid doc's `Y.Text('source')` from disk. Idempotent: re-seeds only+ * when Y.Text is empty. Lazy: a missing file seeds nothing (admitting a doc must+ * never auto-create disk).+ */+export function loadMermaidDoc(+ document: Y.Doc,+ documentName: string,+ ctx: MermaidPersistenceCtx,+): void {+ const ytext = document.getText('source');+ if (ytext.length > 0) return;++ const filePath = mermaidAbsPath(documentName, ctx.contentDir);+ if (!existsSync(filePath)) return;++ let raw: string;+ try {+ raw = readFileSync(filePath, 'utf-8');+ } catch (e) {+ log.warn({ documentName, err: e }, 'load: could not read; seeding empty');+ return;+ }+ replaceSource(document, raw, true);+ ctx.lkgCache.set(documentName, raw);+}++/**+ * Persist a Mermaid doc to disk. Serializes from `Y.Text('source')` (verbatim —+ * precedent #38); atomic tmp+rename. Entry gate: a store whose last transaction+ * was the load/reconcile import (`MERMAID_SOURCE_ORIGIN`) is a no-op — belt-and-+ * suspenders alongside that origin's `skipStoreHooks: true`. Reconciles (imports+ * disk) instead of clobbering when an external writer changed the file since our+ * LKG.+ */+export async function storeMermaidDoc(+ document: Y.Doc,+ documentName: string,+ lastTransactionOrigin: unknown,+ ctx: MermaidPersistenceCtx,+): Promise<StoreMermaidOutcome> {+ if (lastTransactionOrigin === MERMAID_SOURCE_ORIGIN) return 'no-op';++ const content = document.getText('source').toString();+ const lkg = ctx.lkgCache.get(documentName);+ if (content === lkg) return 'no-op';++ const filePath = mermaidAbsPath(documentName, ctx.contentDir);+ try {+ await tracedMkdir(resolve(filePath, '..'), { recursive: true });++ if (existsSync(filePath)) {+ let disk: string | null = null;+ try {+ disk = readFileSync(filePath, 'utf-8');+ } catch (readErr) {+ // ENOENT (vanished between existsSync and read) is the benign race —+ // fall through and write. Anything else, log before proceeding so a+ // failed atomic write below isn't the first sign a read preceded it.+ if ((readErr as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(+ { documentName, err: readErr },+ 'store: pre-write disk read failed (non-ENOENT); proceeding to write',+ );+ }+ disk = null;+ }+ // Concurrent external writer (CLI / another editor) diverged from our LKG:+ // import their bytes into Y.Text instead of clobbering.+ if (disk !== null && disk !== lkg && disk !== content) {+ replaceSource(document, disk, false);+ ctx.lkgCache.set(documentName, disk);+ return 'reconciled';+ }+ }++ await atomicWriteFile(filePath, content, { fs: tracedAtomicFs });+ ctx.lkgCache.set(documentName, content);+ return 'persisted';+ } catch (e) {+ log.warn({ documentName, err: e }, 'store: write failed');+ return 'write-failed';+ }+}++// NOTE (follow-up): live external-disk-edit → open-Y.Doc sync is intentionally+// not wired here. `.mmd` stays a first-class asset in the file-watcher/index, so+// an external edit while the doc is OPEN is not pushed into `Y.Text` live; it is+// picked up on the next open (`loadMermaidDoc` re-reads disk) and, if the doc was+// edited in-app meanwhile, `storeMermaidDoc`'s reconcile makes disk win rather+// than clobbering the external change. Adding a `mermaid-*` file-watcher event+// (an `applyExternalMermaidChange` that replaces `Y.Text` under+// `MERMAID_SOURCE_ORIGIN`) would close that gap — deferred to avoid touching the+// file-watcher's DiskEvent taxonomy + fileIndex "never widen" contract.diff --git a/packages/server/src/paired-write-enforcement.test.ts b/packages/server/src/paired-write-enforcement.test.tsindex cd886d534..b64f4ff26 100644--- a/packages/server/src/paired-write-enforcement.test.ts+++ b/packages/server/src/paired-write-enforcement.test.ts@@ -68,6 +68,9 @@ const TRANSITIVE_PRIMITIVE_CALLERS = new Set<string>([* CONFIG_VALIDATION_REVERT_ORIGIN, CONFIG_FILE_WATCHER_ORIGIN — config docs* bypass the markdown bridge entirely (Y.Text-only mutation; see* `server-observer-extension.ts` config-doc gate).+ * MERMAID_SOURCE_ORIGIN — standalone `.mmd`/`.mermaid` docs; Y.Text-only, the+ * markdown bridge is gated off (same config-doc gate), so seed/reconcile+ * writes mutate only Y.Text and need no bridge-intake primitive.* PARK_SNAPSHOT_ORIGIN — read-only transact wrapping `serializeDoc` so Y.js* serializes the snapshot atomically against concurrent writers* (`server-factory.ts`). `paired: true` makes observers short-@@ -85,6 +88,7 @@ const SANCTIONED_NON_PRIMITIVE_ORIGINS = new Set<string>(['OBSERVER_SYNC_ORIGIN','CONFIG_VALIDATION_REVERT_ORIGIN','CONFIG_FILE_WATCHER_ORIGIN',+ 'MERMAID_SOURCE_ORIGIN','PARK_SNAPSHOT_ORIGIN','EFFECT_CAPTURE_ORIGIN',]);diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex 2e235b73e..cf7650195 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -45,7 +45,7 @@ import { LINEAGE_EPOCH_KEY } from './auth-token-schema.ts';import type { BacklinkIndex } from './backlink-index.ts';import { getMsSinceLastUserTx, isDocQuiescent } from './bridge-quiescence.ts';import { assertBridgeInvariant, createDocCanonicalizer } from './bridge-watchdog.ts';-import { isConfigDoc, isManagedArtifactDoc, isSystemDoc } from './cc1-broadcast.ts';+import { isConfigDoc, isManagedArtifactDoc, isMermaidDoc, isSystemDoc } from './cc1-broadcast.ts';import { type ConfigPersistenceCtx, loadConfigDoc, storeConfigDoc } from './config-persistence.ts';import type { ContributorEntry } from './contributor-tracker.ts';import {@@ -68,6 +68,11 @@ import {storeManagedArtifactDoc,} from './managed-artifact-persistence.ts';import { mdManager, schema } from './md-manager.ts';+import {+ loadMermaidDoc,+ type MermaidPersistenceCtx,+ storeMermaidDoc,+} from './mermaid-persistence.ts';import {incrementDeferredStoreFailures,incrementGitAutoSaveFailure,@@ -685,6 +690,15 @@ export function createPersistenceExtension(options?: PersistenceOptions): PersisgetReconciledBase,};+ // Mermaid (`.mmd`/`.mermaid`) persistence ctx. Y.Text-only, content-dir paths,+ // its own LKG cache (distinct doc-name space). No reconciled-base: the markdown+ // observer bridge is gated off for these, so there is no baseline to track.+ const mermaidLkgCache = new Map<string, string>();+ const mermaidPersistenceCtx: MermaidPersistenceCtx = {+ contentDir,+ lkgCache: mermaidLkgCache,+ };+// Frontmatter lives in the YAML region of `Y.Text('source')`:// `onStoreDocument` reads FM via `stripFrontmatter(ytext.toString())` and// writes Y.Text verbatim — no recompose step, no per-key cache, no L3 hook.@@ -2050,6 +2064,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): PersisloadManagedArtifactDoc(document, documentName, managedArtifactCtx);return;}+ if (isMermaidDoc(documentName)) {+ loadMermaidDoc(document, documentName, mermaidPersistenceCtx);+ return;+ }ensureHistograms();const started = Date.now();return withSpan(@@ -2268,6 +2286,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis}return;}+ if (isMermaidDoc(documentName)) {+ await storeMermaidDoc(document, documentName, lastTransactionOrigin, mermaidPersistenceCtx);+ return;+ }if (isBatchInProgress()) {deferStore({ document, documentName, lastTransactionOrigin });return;diff --git a/packages/server/src/reconciliation.ts b/packages/server/src/reconciliation.tsindex 66ece58f7..d3c7e9534 100644--- a/packages/server/src/reconciliation.ts+++ b/packages/server/src/reconciliation.ts@@ -1,4 +1,4 @@-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';+import { isConfigDoc, isMermaidDoc, isSystemDoc } from './cc1-broadcast.ts';/*** Three-way reconciliation for external writes.@@ -118,7 +118,8 @@ export function splitMarkdownBlocks(md: string): string[] {* Perform three-way reconciliation between base, ours, and theirs.*/export function reconcile(input: ReconcileInput): ReconcileOutcome {- if (isSystemDoc(input.docName) || isConfigDoc(input.docName)) return { kind: 'noop' };+ if (isSystemDoc(input.docName) || isConfigDoc(input.docName) || isMermaidDoc(input.docName))+ return { kind: 'noop' };const { base, ours, theirs } = input;// Check for conflict markers first — refuse to ingestdiff --git a/packages/server/src/server-observer-extension.ts b/packages/server/src/server-observer-extension.tsindex 6556b2cb4..c173ef10e 100644--- a/packages/server/src/server-observer-extension.ts+++ b/packages/server/src/server-observer-extension.ts@@ -12,7 +12,7 @@ import type { Extension } from '@hocuspocus/server';import type { MarkdownManager } from '@inkeep/open-knowledge-core';import type { Schema } from '@tiptap/pm/model';import type * as Y from 'yjs';-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';+import { isConfigDoc, isMermaidDoc, isSystemDoc } from './cc1-broadcast.ts';import { incrementServerObserverError } from './metrics.ts';import { setupServerObservers } from './server-observers.ts';import type { ShadowRef } from './shadow-repo.ts';@@ -64,7 +64,10 @@ export function createServerObserverExtension(opts: ServerObserverExtensionOptioreturn {async afterLoadDocument({ documentName, document }) {- if (isSystemDoc(documentName) || isConfigDoc(documentName)) return;+ // Mermaid docs are Y.Text-only like config docs — the markdown bridge must+ // NOT run (it would re-canonicalize the diagram source through remark).+ if (isSystemDoc(documentName) || isConfigDoc(documentName) || isMermaidDoc(documentName))+ return;if (cleanups.has(documentName)) return;const doc = document as unknown as Y.Doc;