Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): plugin infra, markdownlint content rules, Themes plugin (#2433)
serafin-garcia1c8f56cec912
diff --git a/.changeset/content-rules-and-theme-plugins.md b/.changeset/content-rules-and-theme-plugins.mdnew file mode 100644index 000000000..37e15c6ed--- /dev/null+++ b/.changeset/content-rules-and-theme-plugins.md@@ -0,0 +1,26 @@+---+"@inkeep/open-knowledge-core": minor+"@inkeep/open-knowledge-app": minor+"@inkeep/open-knowledge-desktop": minor+"@inkeep/open-knowledge": minor+---++Add content rules (a markdown linter with native markdownlint support) and themes as a toggleable plugin, introducing the new **Settings → Plugins** area. Shipping the two together makes the Plugins taxonomy legible from day one: content rules are a project-scope plugin (shared via git) and Themes is a user-scope plugin (personal to this device) — the two kinds of plugin the system is built around.++**Content rules.** Powered by [markdownlint](https://github.com/DavidAnson/markdownlint) (the engine behind VS Code's markdownlint), the linter surfaces common issues — hard tabs, trailing whitespace, heading-increment skips, inconsistent list markers, and more — as non-blocking warnings, with a gutter marker, hover tooltip, and a one-click "Fix" for auto-fixable rules. WYSIWYG mode flags the offending block with the same wavy underline — or, for textless blocks like thematic breaks and images, an outline so the mark is always visible. Enable it per project in Settings → This project → Plugins.++Your rules live in your project's own `.markdownlint.{json,jsonc,yaml,yml}` (or `.markdownlintrc`) file — the portable, ecosystem-standard config, discovered at the content root — not in Open Knowledge's config. With no file present, the default matches the VS Code markdownlint extension exactly: every rule on, except `MD013` (line-length). The only OK-config surface is the plugin toggle (`contentRules.markdownlint.enabled`, project scope).++**Problems panel.** A new **Problems** tab in the right-hand document panel lists every problem for the active document with a count badge, and clicking a row jumps to the offending spot: the exact line and column in source mode, the containing block in WYSIWYG. It reads the document's source CRDT directly, so problems show in WYSIWYG mode too — not just source mode; the WYSIWYG block markers lint those same source bytes, so byte-level findings (hard tabs, trailing spaces, blank-line runs) paint in both modes. A "This doc / Project" scope toggle runs a whole-project audit on demand (a refresh button re-runs it; nothing polls in the background), listing every violating file with its diagnostics and error/warning totals. Clicking a diagnostic opens the offending file and lands on the violation — the exact line in source mode, the containing block in WYSIWYG. Auto-fixable diagnostics carry a one-click **Fix** in every mode: the CodeMirror lint action in source mode, a Fix button on the panel row, and a Fix button in the WYSIWYG block's hover tooltip — each applies the fix straight to the document's source.++**Settings → Plugins.** A new Plugins management page (under *This project*) groups plugins by scope — "This project — shared via git" (content rules) and "This device — personal" (Themes) — and each enabled plugin appears under a **Plugins** header in the settings sidebar with its own panel. Whole-project audits run from the Problems panel, not Settings.++**Full-catalog rule browser.** The markdownlint panel lists every rule the installed engine ships (53 today), grouped by category, with search over id/alias/name and an "Only modified" filter. Rule metadata — names, descriptions, documentation links, option types — is generated from markdownlint's own config schema, so the catalog always matches the installed engine version. Toggle any rule on or off and the change lands in your native `.markdownlint.json` (created from OK's tuned defaults on first edit). Expanding a rule row reveals its documentation link and a typed field per option: switches for booleans, dropdowns for enums, number inputs honoring the schema's minimum/maximum, plain text for strings, and tag-pill lists for arrays — set `MD013`'s `line_length`, `MD003`'s heading style, or `MD043`'s required headings without hand-editing JSON. The rare option shape with no generic control shows an "Edit in config file" chip.++**Themes as a plugin.** The IDE color palettes (Dracula, Catppuccin Frappé, Catppuccin Latte, Monokai, Gruvbox, Solarized, and a six-seed-color Custom theme with live preview) now live under Settings → Plugins → Themes, and the Themes plugin itself can be toggled off — disabling it reverts the whole app to the default palette (including the pre-paint flash cache) without losing your saved choice. Palettes are personal, user-scoped preferences (`appearance.colorTheme`, `appearance.customTheme`, `appearance.colorThemeEnabled`) applied flash-free on launch; dark IDE palettes force dark mode so Tailwind `dark:` styles stay correct, and switching back to Default restores your saved light/dark choice.++**Native config, the markdownlint-cli2 way.** Rules live in the project's own `.markdownlint.{jsonc,json,yaml,yml}` files and are honored exactly as markdownlint-cli2 would: full JSONC (comments, trailing commas, BOM), `extends` chains (relative file paths, escape-guarded; package refs declined with a clear diagnostic; `extends: null` accepted), and a per-directory cascade — the nearest config file on a document's path governs it wholesale, with no OK-flavored merging underneath. The VS Code-parity defaults apply only when a project has no markdownlint file at all, and the first rule edit from Settings materializes them into a real `.markdownlint.json`. Executable configs (`.cjs`/`.mjs`) are detected but never executed. Malformed configs and unresolvable `extends` surface loudly (Settings, `ok lint`, and the lint API) instead of silently falling back, with the underlying parse/read detail in the message.++Edits are faithful to your file. Alias-keyed configs (`line-length` for `MD013`, case-insensitive, last matching key wins) are resolved with markdownlint's own semantics, and rule edits rewrite the key form already in your file instead of appending a duplicate canonical id. Toggling a rule in a `.markdownlint.jsonc` preserves your comments, and unrelated keys and formatting stay untouched. Severity strings (`"error"` / `"warning"`) — valid in markdownlint's own schema — load and lint normally; the rule browser shows such a rule as enabled with a read-only severity chip, and discloses before an edit that saving replaces the severity string. Lint reads are symlink-safe: a path that resolves outside the content directory is refused, matching the escape protection on every other read surface.++**Headless + MCP.** A new `ok lint [path]` CLI command lints the project (or a folder/file) from the terminal, with `--fix` to apply auto-fixable rules and `--json` for structured output — exits non-zero on problems, CI-friendly. A new `lint` MCP tool surfaces problems to connected agents — for a single document or as a whole-project audit, capped at 10 files × 10 diagnostics with explicit "… and N more" indicators and always-accurate totals. Passing `fix: true` with a document applies markdownlint's auto-fixes in place through the collaborative document — attributed to the agent and reflected in the live preview, exactly like the editor's Fix button, never an unattributed shell edit; it stays auto-approvable because the fix is a recoverable, shadow-versioned content write like `write`/`edit`. Agent `write`/`edit` responses also carry the written document's problems as advisory warnings, so agents see the same issues the editor shows without an extra round-trip. The lint HTTP API is grouped under `/api/lint/*`.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 6b6628fd7..b8499737f 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -1205,6 +1205,11 @@ Homepage: https://github.com/codemirror/legacy-modesCopyright (C) 2018-2021 by Marijn Haverbeke <[email protected]> and others+### `@codemirror/[email protected]`+Homepage: https://code.haverbeke.berlin/codemirror/lint++Copyright (C) 2018-2021 by Marijn Haverbeke <[email protected]> and others+### `@codemirror/[email protected]`Homepage: https://github.com/codemirror/lint@@ -1225,8 +1230,8 @@ Homepage: https://github.com/codemirror/stateCopyright (C) 2018-2021 by Marijn Haverbeke <[email protected]> and others-### `@codemirror/[email protected]`-Homepage: https://github.com/codemirror/view+### `@codemirror/[email protected]`+Homepage: https://code.haverbeke.berlin/codemirror/viewCopyright (C) 2018-2021 by Marijn Haverbeke <[email protected]> and others@@ -4034,6 +4039,11 @@ Homepage: https://github.com/wooorm/markdown-tableCopyright (c) Titus Wormer <[email protected]>+### `[email protected]`+Homepage: https://github.com/DavidAnson/markdownlint++Copyright (c) David Anson+### `[email protected]`Homepage: https://marked.js.org@@ -4175,6 +4185,11 @@ Homepage: https://github.com/micromark/micromark/tree/main/packages/micromark-coCopyright (c) Titus Wormer <[email protected]>+### `[email protected]`+Homepage: https://github.com/micromark/micromark-extension-directive++Copyright (c) Titus Wormer <[email protected]>+### `[email protected]`Homepage: https://github.com/micromark/micromark-extension-frontmatter@@ -5272,6 +5287,11 @@ Homepage: https://github.com/open-draft/strict-event-emitter_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_+### `[email protected]`+Homepage: https://github.com/sindresorhus/string-width++Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)+### `[email protected]`Homepage: https://github.com/sindresorhus/string-widthdiff --git a/bun.lock b/bun.lockindex f020e07bd..a2a844de9 100644--- a/bun.lock+++ b/bun.lock@@ -76,10 +76,11 @@"@codemirror/lang-yaml": "^6.1.2","@codemirror/language": "^6.12.3","@codemirror/legacy-modes": "^6.5.1",+ "@codemirror/lint": "^6.9.7","@codemirror/merge": "^6.12.1","@codemirror/search": "^6.6.0","@codemirror/state": "^6.6.0",- "@codemirror/view": "^6.41.0",+ "@codemirror/view": "^6.43.3","@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",@@ -276,6 +277,7 @@"@tiptap/starter-kit": "^3.22.3","decode-named-character-reference": "^1.3.0","diff-match-patch": "^1.0.5",+ "markdownlint": "^0.41.0","mdast-util-from-markdown": "^2.0.3","mdast-util-math": "^3.0.0","mdast-util-mdx": "3.0.0",@@ -400,6 +402,7 @@"happy-dom": "^20.10.2","ignore": "^5.3.2","ipaddr.js": "^2.3.0",+ "jsonc-parser": "^3.3.1","just-bash": "^2.14.3","mermaid": "^11.14.0","mrmime": "^2.0.1",@@ -440,6 +443,8 @@"[email protected]": "patches/[email protected]",},"overrides": {+ "@codemirror/state": "6.6.0",+ "@codemirror/view": "6.43.3","mdast-util-mdx-jsx": "3.2.0",},"packages": {@@ -613,7 +618,7 @@"@codemirror/legacy-modes": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/jJbwSTazlQEDOQw2FJ8LEEKVS72pU0lx6oM54kGpL8t/NJ2Jda3CZ4pcltiKTdqYSRk3ug1B3pil1gsjA6+8Q=="],- "@codemirror/lint": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.35.0", "crelt": "^1.0.5" } }, "sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA=="],+ "@codemirror/lint": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="],"@codemirror/merge": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/highlight": "^1.0.0", "style-mod": "^4.1.0" } }, "sha512-GA8hBq2T+IFM0sb5fk8CunTrqOulA3zurJmHtzcU15EMnL8aYpVINfJ5bkfd53M4ikwoew4Y1ydtSaAlk6+B1w=="],@@ -621,7 +626,7 @@"@codemirror/state": ["@codemirror/[email protected]", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ=="],- "@codemirror/view": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-6H/qadXsVuDY219Yljhohglve8xf4B8xJkVOEWfA5uiYKiTFppjqsvsfR5iPA0RbvRBoOyTZpbLIxe9+0UR8xA=="],+ "@codemirror/view": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-MwEwCAr/o0agJefhC2+reBv5kfOQpMcDRUNQrRYZgWlhH8IwQcerMZrpqWyUFSyO0ebgN2cnh/w87F7G4BGSng=="],"@colors/colors": ["@colors/[email protected]", "", {}, "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ=="],@@ -3197,6 +3202,8 @@"markdown-table": ["[email protected]", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="],+ "markdownlint": ["[email protected]", "", { "dependencies": { "micromark": "4.0.2", "micromark-core-commonmark": "2.0.3", "micromark-extension-directive": "4.0.0", "micromark-extension-gfm-autolink-literal": "2.1.0", "micromark-extension-gfm-footnote": "2.1.0", "micromark-extension-gfm-table": "2.1.1", "micromark-extension-math": "3.1.0", "micromark-util-types": "2.0.2", "string-width": "8.2.1" } }, "sha512-xMUI3ChBuRuxuLF4ENvCZyS8z/+Jly1coUcZwErKLIB3sDj7ojpaTBa1e9YVPhSN4jGEIjYGQCldbTJS/hqS+A=="],+"marked": ["[email protected]", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA=="],"matcher": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],@@ -3263,6 +3270,8 @@"micromark-core-commonmark": ["[email protected]", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="],+ "micromark-extension-directive": ["[email protected]", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="],+"micromark-extension-frontmatter": ["[email protected]", "", { "dependencies": { "fault": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg=="],"micromark-extension-gfm": ["[email protected]", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="],@@ -4393,6 +4402,8 @@"@changesets/get-dependents-graph/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],+ "@codemirror/lang-javascript/@codemirror/lint": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.35.0", "crelt": "^1.0.5" } }, "sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA=="],+"@develar/schema-utils/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="],"@dotenvx/dotenvx/commander": ["[email protected]", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],@@ -4653,6 +4664,8 @@"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],+ "codemirror/@codemirror/lint": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.35.0", "crelt": "^1.0.5" } }, "sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA=="],+"cytoscape-fcose/cose-base": ["[email protected]", "", { "dependencies": { "layout-base": "^2.0.0" } }, "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g=="],"d3-dsv/commander": ["[email protected]", "", {}, "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw=="],@@ -4757,6 +4770,8 @@"markdown-it/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],+ "markdownlint/string-width": ["[email protected]", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-IIaP0g3iy9Cyy18w3M9YcaDudujEAVHKt3a3QJg1+sr/oX96TbaGUubG0hJyCjCBThFH+tFpcIyoUHUn1ogaLA=="],+"matcher/escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],"memlab/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-q6rbdDd1o2mAnQreO7YADIxf/Whx4AHBiRf6d+/cVT8h44ss+lHgxf1FemcqDnQt9X3ct4McHr+JMGlYSsK7Cg=="],@@ -5261,6 +5276,8 @@"log-update/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],+ "markdownlint/string-width/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],+"minipass-flush/minipass/yallist": ["[email protected]", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],"minipass-pipeline/minipass/yallist": ["[email protected]", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],@@ -5495,6 +5512,8 @@"glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],+ "markdownlint/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],+"openai/node-fetch/whatwg-url/tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],"openai/node-fetch/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],diff --git a/docs/content/advanced/content-rules/markdownlint.mdx b/docs/content/advanced/content-rules/markdownlint.mdxnew file mode 100644index 000000000..c703a4ec7--- /dev/null+++ b/docs/content/advanced/content-rules/markdownlint.mdx@@ -0,0 +1,43 @@+---+title: markdownlint+icon: LuListChecks+description: The markdownlint linter for content rules — VS Code-parity defaults, your project's native `.markdownlint.*` config, and a no-code browser for all 53 rules.+---++markdownlint is the first content-rules linter — the standard [markdownlint](https://github.com/DavidAnson/markdownlint) engine, the same one behind `markdownlint-cli2` and the popular editor extensions. This page covers its defaults, how it reads your project's config, and the built-in rule browser. For the linter-agnostic parts — where problems appear, the Problems panel, `ok lint`, and agent advisories — see the [content rules overview](/docs/advanced/content-rules/overview).++## Default rules++The rules aren't stored in OK config — they live in your project's own native markdownlint file (see [below](#your-markdownlint-file)). With **no file**, OK uses the same default as the [VS Code markdownlint extension](https://github.com/DavidAnson/vscode-markdownlint): every rule on, except `MD013` (line-length). Nothing else is pre-disabled — so, exactly as in VS Code:++- `MD033` flags inline HTML, including MDX/JSX components like `<Callout>`,+- `MD041` flags docs that don't open with a top-level heading,+- `MD025` flags a frontmatter `title` beside an H1.++Turn off whichever don't fit your project — the first change [creates the file for you](#the-rule-browser).++## Your `.markdownlint.*` file++The rules live in your project's own native markdownlint file — `.markdownlint.jsonc`, `.markdownlint.json`, `.markdownlint.yaml`, or `.markdownlint.yml` (`.markdownlintrc` is recognized too; the first that exists wins). It's a plain, portable markdownlint config: the same file `markdownlint-cli2` and editor extensions read, with nothing OK-specific in it.++- **A file governs wholesale.** When a native file exists it's honored exactly as `markdownlint-cli2` would honor it — OK layers nothing underneath.+- **Per-folder cascade.** The nearest `.markdownlint.*` file on the walk from a doc's folder up to the project root governs that doc, matching `markdownlint-cli2` conventions. Subfolders inherit shared config explicitly via `extends` with a relative path (npm-package `extends` isn't resolved).+- **Aliases and severities.** Rule aliases are valid keys (`line-length` ≡ `MD013`, matched case-insensitively), and `"error"` / `"warning"` severity strings are honored — either as the rule's value (`"MD010": "error"`) or as a `severity` key in its options object. Everything else reports as a warning.+- **Executable configs.** A `.markdownlint.cjs` / `.mjs` is detected but **not executed**: you get a loud configuration warning, linting falls back to OK's defaults, and OK will never rewrite the file. Convert it to JSON, JSONC, or YAML to have it govern.++## The rule browser++**Settings ▸ Plugins ▸ markdownlint** (markdownlint appears there once the plugin is enabled) lists the full catalog — all 53 rules, generated from the installed engine's own config schema, so it always matches what actually runs. Search by id, alias, or name; browse by category (Headings, Lists, Whitespace, Code, Links & images, Style); or check **Only modified** to see just the rules your config changes. Expanding a rule reveals a link to its upstream documentation and typed editors for each of its options.++Every edit writes back to your native `.markdownlint.*` file, preserving what you wrote: JSON and JSONC files get minimal text edits (comments and formatting survive), and a rule you configured under an alias stays under that alias. Severity strings are shown as a read-only badge. If the project has no file yet, the first change creates a `.markdownlint.json` seeded with the defaults — from then on that file is the whole story for OK and every other markdownlint tool.++## Auto-fix and severities++- **Auto-fix covers only some rules.** markdownlint can mechanically fix problems like hard tabs, trailing whitespace, list-marker style, and blank-line spacing — but not ones that need a human decision, such as inline HTML (`MD033`) or a missing top-level heading (`MD041`). In source mode the **Fix** action appears only on a problem markdownlint can fix; `ok lint --fix` applies every fixable problem across the project and leaves the rest untouched, still reported. There's no "fix everything" — the rest always need a manual edit.+- **Severities.** A rule reports as a warning unless your config promotes it to `"error"`. Set `"error"` as the rule's value or via a `severity` key, then gate CI on just those rules with `ok lint --errors-only`.++## See also++- [Content rules overview](/docs/advanced/content-rules/overview): where problems show up, the Problems panel, `ok lint`, and agents+- [Configuration reference](/docs/reference/configuration): `config.yml` and what's shared via git+- [markdownlint rules](https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md): the upstream rule referencediff --git a/docs/content/advanced/content-rules/meta.json b/docs/content/advanced/content-rules/meta.jsonnew file mode 100644index 000000000..0890441d4--- /dev/null+++ b/docs/content/advanced/content-rules/meta.json@@ -0,0 +1,5 @@+{+ "title": "Content rules",+ "icon": "LuListChecks",+ "pages": ["overview", "markdownlint"]+}diff --git a/docs/content/advanced/content-rules/overview.mdx b/docs/content/advanced/content-rules/overview.mdxnew file mode 100644index 000000000..81eb40ca7--- /dev/null+++ b/docs/content/advanced/content-rules/overview.mdx@@ -0,0 +1,52 @@+---+title: Overview+icon: LuBookOpen+description: A non-blocking linting layer over your project's markdown — problems as you write, a Problems panel, `ok lint` for CI, and advisories for AI agents. Enable it per project.+---++Content rules are a lightweight linting layer over your project's markdown. **Enable a linter for a project** and it checks your markdown as you write. Findings are **non-blocking**: they surface as warnings, never stop a save, and never gate an agent's edit.++Today the only linter is [markdownlint](/docs/advanced/content-rules/markdownlint) — the standard engine for markdown style (hard tabs, heading increments, list markers, and the rest). Content rules is built as a pluggable system, and more linters are planned. This page covers the parts that are the same whatever the linter runs; the [markdownlint page](/docs/advanced/content-rules/markdownlint) covers that engine's rules and configuration.++## Where problems show up++- **Source mode** — wavy underlines on the offending range, markers in the lint gutter, hover tooltips, and (for auto-fixable rules) an inline **Fix** action.+- **WYSIWYG** — the block a problem falls in is marked, so issues stay visible without raw markdown lines to underline.+- **The Problems panel** — a tab in the document panel on the right, with a live count badge and two scopes:+ - **This doc** — live diagnostics for the open document, in both WYSIWYG and source mode. Click a problem to jump to it: source mode lands on the exact line and column, WYSIWYG scrolls to the block it falls in.+ - **Project** — an on-demand audit of every in-scope document. It runs when you first open the scope and on the refresh button — never in the background. Results group per file with error/warning totals; configuration problems (a malformed config file, a broken `extends`) surface at the top. Clicking a problem opens the offending doc at that position.++The panel is also available in [single-file sessions](/docs/features/editor#open-a-single-file) (`ok <file>`).++## Enabling a linter++Open **Settings ▸ This project ▸ Plugins** and turn on a linter; open editors react live. Each linter has its own toggle, off until you enable it. The choice is saved to the project's `config.yml` (see the [configuration reference](/docs/reference/configuration)), so committing it shares the setting with every collaborator — the whole-project equivalent of a committed lint config.++## From the command line++`ok lint` runs content rules headlessly, with the same config resolution as the editor:++```bash+ok lint # audit the whole project+ok lint guides/ # scope to a folder+ok lint guides/intro.md # or a single file+ok lint --fix # apply auto-fixes in place+ok lint --json # structured JSON output+ok lint --errors-only # exit non-zero only on error-severity problems+```++The exit code is CI-friendly: non-zero when any problems are found. Findings are warnings unless your config promotes a rule to `"error"` severity, so `--errors-only` lets you gate CI on just the rules you've chosen to enforce.++## AI agents++Agents get the same signal you see:++- The MCP **`lint`** tool lints a single document or audits the project (optionally scoped to a folder or file), and with `fix: true` on a document auto-fixes fixable rules in place — attributed and live in the preview, the same result as the editor's **Fix** action. Audit output is capped at 10 files × 10 diagnostics per file with explicit "… and N more" indicators — the totals always reflect the full scan, and re-running with a narrower scope recovers the detail. See the [MCP reference](/docs/reference/mcp).+- Every agent write response carries up to 10 lint findings for the document it touched, so an agent can clean up after itself without being asked. Advisory only — a finding never blocks the write.++## See also++- [markdownlint](/docs/advanced/content-rules/markdownlint): the rules, your `.markdownlint.*` config, and the rule browser+- [Editor](/docs/features/editor): source mode, WYSIWYG, and the document panel+- [Configuration reference](/docs/reference/configuration): `config.yml` and what's shared via git+- [MCP reference](/docs/reference/mcp): the tools agents use to read and write your projectdiff --git a/docs/content/advanced/meta.json b/docs/content/advanced/meta.jsonindex 7fe4256d8..b9918dfc0 100644--- a/docs/content/advanced/meta.json+++ b/docs/content/advanced/meta.json@@ -1,5 +1,5 @@{"title": "Advanced","icon": "LuLayers",- "pages": ["folders-and-templates"]+ "pages": ["folders-and-templates", "content-rules"]}diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 1a5b96917..8c121ec81 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -24,6 +24,8 @@ Open any doc from the sidebar. The body renders as WYSIWYG markdown with familiaA slash command (`/`) opens an insert menu for headings, lists, tables, code blocks, callouts, footnotes, inline math, and the other content shapes the editor supports.+Markdown problems (hard tabs, heading increments, and the rest) are flagged inline as you write, with a **Problems** panel in the document panel for the whole doc or project. See [Content rules](/docs/advanced/content-rules/overview).+### TablesInsert a table from the slash menu. The header row stays visible as you scroll down a long table, the first column stays pinned as you scroll sideways, and dragging a row or column handle reorders it. Cells are single-line in the stored markdown: pressing Enter inside a cell — or pasting a table whose cells hold lists or paragraphs — joins the lines with `<br />`, the GFM line-break idiom, so the table stays valid for everyone else opening the file. `<br>` tags in existing files render as real line breaks and round-trip byte-for-byte.diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex e6e1f8f87..11362c4f2 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -33,6 +33,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| --- | --- | --- | --- | --- || `content.dir` | string | `"."` | project | Content directory, relative to project root. Defaults to `.` (the project root) even when `.ok/` is scaffolded at the git working-tree root from a sub-folder, so opened folder and content scope align by default. To narrow scope to a sub-folder, pass `--content-dir <dir>` to `ok init`, or uncomment `content.dir` in `.ok/config.yml` post-init. Excluded paths live in `.okignore`; see [Ignore patterns](/docs/features/ignore-patterns). || `content.attachmentFolderPath` | string | `"./"` | project | Where pasted and dropped assets are stored. `"./"` colocates beside the current document; `"/"` targets the content root; `"./subdir"` targets a subfolder under the current folder; `"folder"` targets a fixed folder under the content root. |+| `contentRules.plugins.markdownlint.enabled` | boolean | `false` | project | Enable the [markdownlint](/docs/advanced/content-rules/markdownlint) content-rules plugin for this project (shared via git). Off by default — turn it on in **Settings → This project → Plugins**. The rules themselves live in your native `.markdownlint.*` file, not here. || `appearance.theme` | `"light" \| "dark" \| "system"` | (unset) | user | Editor theme. || `appearance.sidebar.showHiddenFiles` | boolean | `false` | project-local | Show files whose path segments start with `.`. The sidebar otherwise lists every file on disk under the content directory; tooling internals (`.git/`, `.ok/`, `node_modules/`) stay hidden regardless. Toggled from the sidebar's right-click menu or the macOS **View → Show Hidden Files** item. || `autoSync.enabled` | `boolean \| null` | `null` | project-local | Per-machine git auto-sync toggle. `null` means "unanswered"; the editor's onboarding modal triggers on first remote-detected open. |diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex 1ba60b719..c173818c1 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -17,6 +17,7 @@ The surface is **19 tools**. The four write verbs — `write`, `edit`, `delete`,| `exec` | Read-only shell (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`); reads return frontmatter, backlinks, and recent history. Fs-direct; works without the server. || `search` | Ranked workspace search (title boost + body BM25 + recency; same engine the cmd-K palette uses). `intent: "omnibar"` narrows to fast title/path matching (`full_text`, the default, includes the body); `scopes` filters hit kinds; `limit` caps rows (default 20, max 100). When [semantic search](/docs/reference/configuration#semantic-search) is enabled, an embeddings signal is additionally fused into `full_text` ranking (opt-in, content egress) — pass `semantic: false` to force pure-lexical. Right after boot, an empty result set with `ready: false` means the index is still building — retry after a couple of seconds rather than treating it as no matches. || `links` | Wiki-link graph. `kind` selects: `backlinks`, `forward`, `dead`, `orphans`, `hubs`, or `suggest`. Accepts an array (e.g. `["dead", "orphans", "hubs"]`) to fetch several views in one call; each view nests under its own key in the response |+| `lint` | Report markdownlint problems for one `document` or a whole-project audit (`path` scopes it); each finding carries `source`/`code`/`message`/`range`/`severity`, audit capped at 10 files × 10 diagnostics with accurate totals. Pass `fix: true` with `document` to auto-fix fixable rules in place — the fix lands through the collaborative document (attributed, live preview), not a shell edit; the rest need `edit`/`write` || `history` | Version timeline for a `document`, `folder`, or `skill`. Each entry carries a `version` (commit SHA) you pass to `restore_version`. Filter with `kind` (`checkpoint` / `wip` / `upstream`), `author` / `excludeAuthor`, and `branch`; paginate with `limit` / `offset` (default 50, max 200). `folder: ""` selects the project-root timeline || `skills` | Find and read agent skills. Omit `name` to list every skill across Project + Global (rows carry `installed` + `hosts`); pass `name` to read one (addressed by `name`+`scope`, never by path); pass `name` + `file` to read one bundle file's text — the read path for `references/` and `scripts/` content || `config` | Read the effective merged config (`config({ key: "appearance.theme" })` for a sub-tree; omit `key` for the whole config) |diff --git a/package.json b/package.jsonindex 13df78863..b4b36cafe 100644--- a/package.json+++ b/package.json@@ -66,7 +66,9 @@"turbo": "^2.7.0"},"overrides": {- "mdast-util-mdx-jsx": "3.2.0"+ "mdast-util-mdx-jsx": "3.2.0",+ "@codemirror/state": "6.6.0",+ "@codemirror/view": "6.43.3"},"puppeteer": {"skipDownload": truediff --git a/packages/app/index.html b/packages/app/index.htmlindex 2f5436343..d2d3b658d 100644--- a/packages/app/index.html+++ b/packages/app/index.html@@ -43,10 +43,20 @@so the BrowserWindow's vibrancy material shows through. Web mode(no `window.okDesktop`) skips the class so chrome stays solid.+ The IDE color palette is read from `ok-color-theme-v1` and applied as+ the `data-color-theme` attribute consumed by+ `color-themes.generated.css`. Each named IDE palette carries its own mode, so+ a present value forces the `dark` class (or clears it for a light palette like+ `catppuccin-latte`) regardless of `ok-theme-v1`. The `custom`+ palette is replayed from `ok-custom-theme-v1` (`{ css, dark }`): its prebuilt+ stylesheet is injected as a `<style>` and its `dark` flag drives the class.+ Paired consumers: `src/lib/use-apply-config-color-theme.ts` (writes the+ caches) + `src/lib/color-themes.ts` (the id allowlist — keep it in sync).+Single-line script body — same biome HTML-formatter constraint asthe editor-mode FOUC above.-->- <script>(() => { let t = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (r === 'light' || r === 'dark' || r === 'system') t = r; } catch {} let dark = t === 'dark'; if (t === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } if (dark) document.documentElement.classList.add('dark'); if (window.okDesktop) document.documentElement.classList.add('electron-mode'); })();</script>+ <script>(() => { let t = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (r === 'light' || r === 'dark' || r === 'system') t = r; } catch {} let ct = null; try { const c = localStorage.getItem('ok-color-theme-v1'); if (c && ['dracula', 'catppuccin-frappe', 'catppuccin-latte', 'monokai', 'gruvbox', 'solarized', 'custom'].includes(c)) ct = c; } catch {} let dark = t === 'dark'; if (t === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } let customCss = null; if (ct === 'custom') { try { const raw = localStorage.getItem('ok-custom-theme-v1'); if (raw) { const o = JSON.parse(raw); if (o?.css) { customCss = o.css; dark = !!o.dark; } } } catch {} if (!customCss) ct = null; } else if (ct) { dark = !['catppuccin-latte'].includes(ct); } if (dark) document.documentElement.classList.add('dark'); if (ct) document.documentElement.setAttribute('data-color-theme', ct); if (customCss) { const s = document.createElement('style'); s.id = 'ok-custom-theme'; s.textContent = customCss; document.head.appendChild(s); } if (window.okDesktop) document.documentElement.classList.add('electron-mode'); })();</script><style>html { background-color: __OK_CHROME_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style></head>diff --git a/packages/app/package.json b/packages/app/package.jsonindex 27e4db398..90c35fe63 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -26,7 +26,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-compact-folders.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/show-ok-folders.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-compact-folders.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",@@ -36,6 +36,7 @@"sweep:cache-regime": "bun run tests/perf/profile.ts --scenario=sweep-cache-regime","sweep:convention-cap-graduation": "bun run tests/perf/profile.ts --scenario=sweep-convention-cap-graduation","probe:tiptap-leak": "bun run tests/perf/probes/tiptap-destroy-leak.ts",+ "gen:color-themes": "bun run scripts/gen-color-themes.ts","audit:strings": "bun run scripts/audit-strings/extract.ts","audit:strings:casing": "bun run scripts/audit-strings/check-casing.ts","size": "turbo run build --filter=@inkeep/open-knowledge-app && size-limit"@@ -44,21 +45,21 @@{"name": "main app bundle (gzipped)","path": "dist/assets/index-*.js",- "limit": "470 kB",+ "limit": "476 kB","gzip": true,"running": false},{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "3.10 MB",+ "limit": "3.17 MB","gzip": true,"running": false},{"name": "main CSS (gzipped)","path": "dist/assets/index-*.css",- "limit": "52 kB",+ "limit": "54 kB","gzip": true,"running": false}@@ -76,10 +77,11 @@"@codemirror/lang-yaml": "^6.1.2","@codemirror/language": "^6.12.3","@codemirror/legacy-modes": "^6.5.1",+ "@codemirror/lint": "^6.9.7","@codemirror/merge": "^6.12.1","@codemirror/search": "^6.6.0","@codemirror/state": "^6.6.0",- "@codemirror/view": "^6.41.0",+ "@codemirror/view": "^6.43.3","@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",diff --git a/packages/app/scripts/gen-color-themes.ts b/packages/app/scripts/gen-color-themes.tsnew file mode 100644index 000000000..45a53f4c6--- /dev/null+++ b/packages/app/scripts/gen-color-themes.ts@@ -0,0 +1,13 @@+/**+ * Regenerate `src/color-themes.generated.css` from the `COLOR_THEMES` registry+ * in `src/lib/color-themes.ts`. Run via `bun run gen:color-themes`. The+ * companion `src/lib/color-themes.generated.test.ts` fails on drift, so commit+ * the regenerated file whenever a palette changes.+ */+import { writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { generateColorThemesCss } from '../src/lib/color-themes';++const out = resolve(import.meta.dir, '../src/color-themes.generated.css');+writeFileSync(out, generateColorThemesCss());+console.log(`Wrote ${out}`);diff --git a/packages/app/src/color-themes.generated.css b/packages/app/src/color-themes.generated.cssnew file mode 100644index 000000000..f6ebf3812--- /dev/null+++ b/packages/app/src/color-themes.generated.css@@ -0,0 +1,259 @@+/* GENERATED by `bun run gen:color-themes` from src/lib/color-themes.ts — do not edit by hand. */++html[data-color-theme="dracula"] {+ color-scheme: dark;+ --background: #282a36;+ --foreground: #f8f8f2;+ --card: #343746;+ --card-foreground: #f8f8f2;+ --popover: #343746;+ --popover-foreground: #f8f8f2;+ --primary: #bd93f9;+ --primary-foreground: #282a36;+ --secondary: #343746;+ --secondary-foreground: #f8f8f2;+ --muted: #343746;+ --muted-foreground: #9aa0c5;+ --accent: #343746;+ --accent-foreground: #f8f8f2;+ --destructive: #ff5555;+ --border: #44475a;+ --input: #44475a;+ --ring: #bd93f9;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #bd93f9;+ --chart-2: #50fa7b;+ --chart-3: #f1fa8c;+ --chart-4: #ff79c6;+ --chart-5: #ff5555;+ --sidebar: #21222c;+ --sidebar-foreground: #f8f8f2;+ --sidebar-primary: #bd93f9;+ --sidebar-primary-foreground: #282a36;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #bd93f9;+ --sidebar-hover: #343746;+ --sidebar-border: #44475a;+ --sidebar-ring: #bd93f9;+ --syntax-keyword: #ff79c6;+ --syntax-tag: #ff5555;+ --syntax-attr: #8be9fd;+ --syntax-string: #50fa7b;+ --syntax-number: #ffb86c;+ --syntax-atom: #8be9fd;+}++html[data-color-theme="catppuccin-frappe"] {+ color-scheme: dark;+ --background: #303446;+ --foreground: #c6d0f5;+ --card: #414559;+ --card-foreground: #c6d0f5;+ --popover: #414559;+ --popover-foreground: #c6d0f5;+ --primary: #ca9ee6;+ --primary-foreground: #303446;+ --secondary: #414559;+ --secondary-foreground: #c6d0f5;+ --muted: #414559;+ --muted-foreground: #a5adce;+ --accent: #414559;+ --accent-foreground: #c6d0f5;+ --destructive: #e78284;+ --border: #51576d;+ --input: #51576d;+ --ring: #ca9ee6;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #ca9ee6;+ --chart-2: #a6d189;+ --chart-3: #e5c890;+ --chart-4: #ca9ee6;+ --chart-5: #e78284;+ --sidebar: #292c3c;+ --sidebar-foreground: #c6d0f5;+ --sidebar-primary: #ca9ee6;+ --sidebar-primary-foreground: #303446;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #ca9ee6;+ --sidebar-hover: #414559;+ --sidebar-border: #51576d;+ --sidebar-ring: #ca9ee6;+ --syntax-keyword: #ca9ee6;+ --syntax-tag: #e78284;+ --syntax-attr: #8caaee;+ --syntax-string: #a6d189;+ --syntax-number: #ef9f76;+ --syntax-atom: #81c8be;+}++html[data-color-theme="catppuccin-latte"] {+ color-scheme: light;+ --background: #eff1f5;+ --foreground: #4c4f69;+ --card: #ffffff;+ --card-foreground: #4c4f69;+ --popover: #ffffff;+ --popover-foreground: #4c4f69;+ --primary: #8839ef;+ --primary-foreground: #ffffff;+ --secondary: #ffffff;+ --secondary-foreground: #4c4f69;+ --muted: #ffffff;+ --muted-foreground: #6c6f85;+ --accent: #ffffff;+ --accent-foreground: #4c4f69;+ --destructive: #d20f39;+ --border: #ccd0da;+ --input: #ccd0da;+ --ring: #8839ef;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #8839ef;+ --chart-2: #40a02b;+ --chart-3: #df8e1d;+ --chart-4: #8839ef;+ --chart-5: #d20f39;+ --sidebar: #e6e9ef;+ --sidebar-foreground: #4c4f69;+ --sidebar-primary: #8839ef;+ --sidebar-primary-foreground: #ffffff;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #8839ef;+ --sidebar-hover: #ffffff;+ --sidebar-border: #ccd0da;+ --sidebar-ring: #8839ef;+ --syntax-keyword: #8839ef;+ --syntax-tag: #d20f39;+ --syntax-attr: #1e66f5;+ --syntax-string: #40a02b;+ --syntax-number: #fe640b;+ --syntax-atom: #179299;+}++html[data-color-theme="monokai"] {+ color-scheme: dark;+ --background: #272822;+ --foreground: #f8f8f2;+ --card: #31322b;+ --card-foreground: #f8f8f2;+ --popover: #31322b;+ --popover-foreground: #f8f8f2;+ --primary: #66d9ef;+ --primary-foreground: #272822;+ --secondary: #31322b;+ --secondary-foreground: #f8f8f2;+ --muted: #31322b;+ --muted-foreground: #a6a28c;+ --accent: #31322b;+ --accent-foreground: #f8f8f2;+ --destructive: #f92672;+ --border: #49483e;+ --input: #49483e;+ --ring: #66d9ef;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #66d9ef;+ --chart-2: #a6e22e;+ --chart-3: #e6db74;+ --chart-4: #ae81ff;+ --chart-5: #f92672;+ --sidebar: #1e1f1a;+ --sidebar-foreground: #f8f8f2;+ --sidebar-primary: #66d9ef;+ --sidebar-primary-foreground: #272822;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #66d9ef;+ --sidebar-hover: #31322b;+ --sidebar-border: #49483e;+ --sidebar-ring: #66d9ef;+ --syntax-keyword: #ae81ff;+ --syntax-tag: #f92672;+ --syntax-attr: #66d9ef;+ --syntax-string: #a6e22e;+ --syntax-number: #fd971f;+ --syntax-atom: #66d9ef;+}++html[data-color-theme="gruvbox"] {+ color-scheme: dark;+ --background: #282828;+ --foreground: #ebdbb2;+ --card: #32302f;+ --card-foreground: #ebdbb2;+ --popover: #32302f;+ --popover-foreground: #ebdbb2;+ --primary: #83a598;+ --primary-foreground: #1d2021;+ --secondary: #32302f;+ --secondary-foreground: #ebdbb2;+ --muted: #32302f;+ --muted-foreground: #a89984;+ --accent: #32302f;+ --accent-foreground: #ebdbb2;+ --destructive: #fb4934;+ --border: #3c3836;+ --input: #3c3836;+ --ring: #83a598;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #83a598;+ --chart-2: #b8bb26;+ --chart-3: #fabd2f;+ --chart-4: #d3869b;+ --chart-5: #fb4934;+ --sidebar: #1d2021;+ --sidebar-foreground: #ebdbb2;+ --sidebar-primary: #83a598;+ --sidebar-primary-foreground: #1d2021;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #83a598;+ --sidebar-hover: #32302f;+ --sidebar-border: #3c3836;+ --sidebar-ring: #83a598;+ --syntax-keyword: #d3869b;+ --syntax-tag: #fb4934;+ --syntax-attr: #83a598;+ --syntax-string: #b8bb26;+ --syntax-number: #fe8019;+ --syntax-atom: #8ec07c;+}++html[data-color-theme="solarized"] {+ color-scheme: dark;+ --background: #002b36;+ --foreground: #93a1a1;+ --card: #073642;+ --card-foreground: #93a1a1;+ --popover: #073642;+ --popover-foreground: #93a1a1;+ --primary: #268bd2;+ --primary-foreground: #fdf6e3;+ --secondary: #073642;+ --secondary-foreground: #93a1a1;+ --muted: #073642;+ --muted-foreground: #6a7f86;+ --accent: #073642;+ --accent-foreground: #93a1a1;+ --destructive: #dc322f;+ --border: #0e4a56;+ --input: #0e4a56;+ --ring: #268bd2;+ --selection-soft: oklch(from var(--primary) l c h / 0.3);+ --chart-1: #268bd2;+ --chart-2: #859900;+ --chart-3: #b58900;+ --chart-4: #6c71c4;+ --chart-5: #dc322f;+ --sidebar: #00252e;+ --sidebar-foreground: #93a1a1;+ --sidebar-primary: #268bd2;+ --sidebar-primary-foreground: #fdf6e3;+ --sidebar-accent: oklch(from var(--primary) l c h / 0.14);+ --sidebar-accent-foreground: #268bd2;+ --sidebar-hover: #073642;+ --sidebar-border: #0e4a56;+ --sidebar-ring: #268bd2;+ --syntax-keyword: #6c71c4;+ --syntax-tag: #dc322f;+ --syntax-attr: #268bd2;+ --syntax-string: #859900;+ --syntax-number: #cb4b16;+ --syntax-atom: #2aa198;+}diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsxindex a9c3577ee..5eb55c954 100644--- a/packages/app/src/components/DocPanel.dom.test.tsx+++ b/packages/app/src/components/DocPanel.dom.test.tsx@@ -1,11 +1,14 @@/**- * Behavioral tests for DocPanel's single-file tab gating.+ * Behavioral tests for DocPanel's tab strip: single-file gating + the Problems+ * tab badge.*- * Single-file `ok <file>` keeps only the Outline tab — Links/Graph need a- * multi-doc knowledge base and Timeline is git history, all empty/inert for a- * lone git-off file. Asserts the rendered tab set (by `role="tab"` count, so the- * test doesn't depend on localized label text) and that a persisted- * links/graph/timeline selection coerces back to Outline.+ * Single-file `ok <file>` keeps only the Outline + Problems tabs — Links/Graph+ * need a multi-doc knowledge base and Timeline is git history, all empty/inert+ * for a lone git-off file, but linting applies to any single file. Asserts the+ * rendered tab set (by `role="tab"` count, so the test doesn't depend on+ * localized label text), that a persisted now-hidden selection coerces back to+ * Outline, and that the Problems tab shows a count badge when there are+ * diagnostics.*/import { afterEach, describe, expect, mock, test } from 'bun:test';@@ -41,6 +44,19 @@ mock.module('@lingui/react/macro', () => ({let singleFileValue = false;mock.module('@/lib/single-file-mode', () => ({ useSingleFileMode: () => singleFileValue }));+// Lint plumbing — DocPanel computes live diagnostics to drive the Problems+// badge. Stub the source so the test controls the count without a provider/fetch.+let diagnosticsValue: Array<{ severity: string }> = [];+mock.module('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ activeProvider: null, activeDocName: 'notes' }),+}));+mock.module('@/editor/lint-config-client', () => ({+ useDocLintConfig: () => ({ data: null }),+}));+mock.module('@/editor/useDocDiagnostics', () => ({+ useDocDiagnostics: () => diagnosticsValue,+}));+// Stub the heavy panel children so the test stays focused on tab visibility.mock.module('@/components/OutlinePanel', () => ({OutlinePanel: () => <div data-testid="outline-panel" />,@@ -51,10 +67,15 @@ mock.module('@/components/LinksPanel', () => ({mock.module('@/components/TimelinePanel', () => ({TimelineContent: () => <div data-testid="timeline-panel" />,}));+mock.module('@/components/ProblemsPanel', () => ({+ ProblemsPanel: () => <div data-testid="problems-panel" />,+}));const { DocPanel } = await import('./DocPanel');-function renderPanel(activeTab: 'outline' | 'links' | 'graph' | 'timeline') {+type Tab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems';++function renderPanel(activeTab: Tab) {return render(<TooltipProvider><DocPanel@@ -71,22 +92,49 @@ function renderPanel(activeTab: 'outline' | 'links' | 'graph' | 'timeline') {afterEach(() => {cleanup();singleFileValue = false;+ diagnosticsValue = [];});-describe('DocPanel — single-file tab gating', () => {- test('project mode renders the full tab strip (outline + links + graph + timeline)', () => {+describe('DocPanel — tab gating', () => {+ test('project mode renders the full tab strip (outline + links + graph + timeline + problems)', () => {singleFileValue = false;renderPanel('outline');- expect(screen.getAllByRole('tab')).toHaveLength(4);+ expect(screen.getAllByRole('tab')).toHaveLength(5);expect(screen.getByTestId('outline-panel')).toBeTruthy();});- test('single-file mode drops the tab strip and shows only the Outline', () => {+ test('single-file mode keeps only Outline + Problems', () => {singleFileValue = true;// Persisted selection is 'graph' — it must coerce back to Outline rather// than render a now-hidden panel.renderPanel('graph');- expect(screen.queryAllByRole('tab')).toHaveLength(0);+ expect(screen.getAllByRole('tab')).toHaveLength(2);expect(screen.getByTestId('outline-panel')).toBeTruthy();});++ test('renders the Problems panel when its tab is active', () => {+ renderPanel('problems');+ expect(screen.getByTestId('problems-panel')).toBeTruthy();+ });+});++describe('DocPanel — Problems badge', () => {+ test('no badge when there are no diagnostics', () => {+ diagnosticsValue = [];+ renderPanel('outline');+ // The Problems tab is present but carries no count text.+ expect(screen.queryByText('3')).toBeNull();+ });++ test('shows the diagnostic count on the Problems tab', () => {+ diagnosticsValue = [{ severity: 'warning' }, { severity: 'error' }, { severity: 'warning' }];+ renderPanel('outline');+ expect(screen.getByText('3')).toBeTruthy();+ });++ test('caps the badge at 99+', () => {+ diagnosticsValue = Array.from({ length: 150 }, () => ({ severity: 'warning' }));+ renderPanel('outline');+ expect(screen.getByText('99+')).toBeTruthy();+ });});diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsxindex 89945596a..80e73deb6 100644--- a/packages/app/src/components/DocPanel.tsx+++ b/packages/app/src/components/DocPanel.tsx@@ -1,22 +1,29 @@import { t } from '@lingui/core/macro';import { Trans, useLingui } from '@lingui/react/macro';-import { Clock, Link2, ListTree, Network } from 'lucide-react';+import { AlertTriangle, Clock, Link2, ListTree, Network } from 'lucide-react';import { lazy, Suspense, useState } from 'react';import type { DiffLayout } from '@/components/DiffView';import { LinksPanel } from '@/components/LinksPanel';import { OutlinePanel } from '@/components/OutlinePanel';+import { ProblemsPanel } from '@/components/ProblemsPanel';import { TimelineContent } from '@/components/TimelinePanel';+import { Badge } from '@/components/ui/badge';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { applyLintFixes } from '@/editor/apply-lint-fix';+import { useDocumentContext } from '@/editor/DocumentContext';+import { useDocLintConfig } from '@/editor/lint-config-client';+import { useDocDiagnostics } from '@/editor/useDocDiagnostics';import { useSingleFileMode } from '@/lib/single-file-mode';-export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline';+export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems';export const TABS: { id: PanelTab; icon: typeof ListTree }[] = [{ id: 'outline', icon: ListTree },{ id: 'links', icon: Link2 },{ id: 'graph', icon: Network },{ id: 'timeline', icon: Clock },+ { id: 'problems', icon: AlertTriangle },];/** Localized display label for a doc-panel tab. */@@ -24,6 +31,7 @@ function tabLabel(id: PanelTab): string {if (id === 'outline') return t`Outline`;if (id === 'links') return t`Links`;if (id === 'graph') return t`Graph`;+ if (id === 'problems') return t`Problems`;return t`Timeline`;}@@ -72,13 +80,30 @@ export function DocPanel({// TimelineContent unmounts when activeTab leaves 'timeline'.const { t } = useLingui();const [diffLayout, setDiffLayout] = useState<DiffLayout>('unified');- // Single-file `ok <file>` keeps only the Outline tab. Links/Graph need a- // multi-doc knowledge base, and Timeline is git history — all empty or inert- // for a lone git-off file. Coerce a persisted links/graph/timeline selection- // back to outline so the rail never renders a now-hidden panel, and drop the- // one-item tab strip entirely.+ // Live, mode-agnostic lint diagnostics for the active doc — drives both the+ // Problems tab badge and the panel itself. Reads `Y.Text('source')`, so it+ // works in WYSIWYG mode too. Gated to the matching provider during nav.+ const { activeProvider, activeDocName } = useDocumentContext();+ const { data: lintConfig } = useDocLintConfig(docName);+ const lintProvider = activeDocName === docName ? activeProvider : null;+ const diagnostics = useDocDiagnostics(lintProvider, lintConfig?.effective ?? null);+ // Apply a diagnostic's auto-fix to the source CRDT. `lintProvider` is the+ // active provider only when it matches this doc, so a fix always targets the+ // document the user is viewing.+ const handleFix = (diagnostic: (typeof diagnostics)[number]) => {+ if (lintProvider !== null && diagnostic.fixes && diagnostic.fixes.length > 0) {+ applyLintFixes(lintProvider, diagnostic.fixes);+ }+ };+ // Single-file `ok <file>` keeps only the Outline + Problems tabs. Links/Graph+ // need a multi-doc knowledge base, and Timeline is git history — all empty or+ // inert for a lone git-off file; linting applies to any single file. Coerce a+ // persisted now-hidden selection back to outline so the rail never renders a+ // hidden panel.const singleFile = useSingleFileMode();- const tabs = singleFile ? TABS.filter((tab) => tab.id === 'outline') : TABS;+ const tabs = singleFile+ ? TABS.filter((tab) => tab.id === 'outline' || tab.id === 'problems')+ : TABS;const effectiveTab: PanelTab = tabs.some((tab) => tab.id === activeTab) ? activeTab : 'outline';const showTabStrip = mode === 'doc' && tabs.length > 1;return (@@ -100,6 +125,7 @@ export function DocPanel({>{tabs.map(({ id, icon: Icon }) => {const label = tabLabel(id);+ const showBadge = id === 'problems' && diagnostics.length > 0;return (<Tooltip key={id}><ToggleGroupItem@@ -107,11 +133,20 @@ export function DocPanel({role="tab"id={`tab-${id}`}aria-controls={`panel-${id}`}- aria-label={label}+ aria-label={showBadge ? t`${label} (${diagnostics.length})` : label}asChild>- <TooltipTrigger>+ <TooltipTrigger className="relative"><Icon />+ {showBadge && (+ <Badge+ variant="destructive"+ aria-hidden="true"+ className="absolute -right-1.5 -top-1.5 h-4 min-w-4 rounded-full px-1 text-[10px] leading-none"+ >+ {diagnostics.length > 99 ? '99+' : diagnostics.length}+ </Badge>+ )}</TooltipTrigger></ToggleGroupItem><TooltipContent side="bottom">{label}</TooltipContent>@@ -158,6 +193,13 @@ export function DocPanel({onDiffLayoutChange={setDiffLayout}/>)}+ {effectiveTab === 'problems' && (+ <ProblemsPanel+ docName={docName}+ diagnostics={diagnostics}+ onFix={lintProvider !== null ? handleFix : undefined}+ />+ )}</div>) : (<div className="min-h-0 flex-1">diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsxindex b42484791..31887cff6 100644--- a/packages/app/src/components/EditorArea.dom.test.tsx+++ b/packages/app/src/components/EditorArea.dom.test.tsx@@ -21,6 +21,13 @@ mock.module('@/components/PropertyContext', () => ({useProperties: () => ({ requestAddProperty: () => {} }),}));+// EditorArea reads the project config binding (for the desktop "toggle content+// rules" menu action). These tests mount EditorArea outside a ConfigProvider,+// so stub the hook with a null binding — the toggle handler is a no-op here.+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({ projectBinding: null }),+}));+const FOLDER_DOC_CTX = {activeDocName: 'folder/index',activeProvider: null,diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsxindex 0261eb162..add6bcdc9 100644--- a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';import { cleanup, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';+import { ConfigProvider } from '@/lib/config-provider';import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';// A missing target with a live provider — the phantom-doc state the resolver@@ -100,13 +101,17 @@ mock.module('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="const { EditorArea } = await import('./EditorArea');function renderEditorArea() {+ // EditorArea reads useConfigContext (projectBinding); a null collabUrl+ // provider skips binding creation, matching the no-project fail-open path.return render(- <EditorArea- editorMode="wysiwyg"- onModeChange={() => {}}- activeTab="timeline"- onActiveTabChange={() => {}}- />,+ <ConfigProvider collabUrl={null}>+ <EditorArea+ editorMode="wysiwyg"+ onModeChange={() => {}}+ activeTab="timeline"+ onActiveTabChange={() => {}}+ />+ </ConfigProvider>,);}diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsxindex 92621e945..918119c50 100644--- a/packages/app/src/components/EditorArea.tsx+++ b/packages/app/src/components/EditorArea.tsx@@ -66,7 +66,7 @@ import { shouldPaintOverlay } from './editor-area-overlay';import { computeStickyRepinLayout } from './editor-area-sticky-repin';import { TerminalDock } from './TerminalDock';import { TerminalRevealTab } from './TerminalRevealTab';-import { xtermThemeForMode } from './terminal-theme';+import { useLiveXtermTheme } from './use-live-xterm-theme';const LazyActivityModeContent = lazy(async () => {const mod = await import('@/components/ActivityModeContent');@@ -199,7 +199,7 @@ function EditorAreaInner({// strip + chrome read as one continuous surface with the terminal — matching the// bottom dock (TerminalDock applies the same fill). Without it the strip shows// the app background and reads as a black seam above the terminal.- const xtermBackground = xtermThemeForMode(resolvedTheme).background;+ const xtermBackground = useLiveXtermTheme(resolvedTheme).background;const {activeDocName,activeProvider,diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex b6a014ba1..5071a82f4 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -51,6 +51,9 @@ function shiftJKeydownInit(): KeyboardEventInit {mock.module('@lingui/react/macro', () => ({Trans: ({ children }: { children: ReactNode }) => <>{children}</>,+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (+ <>{(value === 1 ? one : other).replace('#', String(value))}</>+ ),useLingui: () => ({t: (strings: TemplateStringsArray, ...values: unknown[]) =>strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),diff --git a/packages/app/src/components/PanelScopeHeader.tsx b/packages/app/src/components/PanelScopeHeader.tsxnew file mode 100644index 000000000..1ddf78f97--- /dev/null+++ b/packages/app/src/components/PanelScopeHeader.tsx@@ -0,0 +1,42 @@+import { Trans, useLingui } from '@lingui/react/macro';+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';++export type PanelScope = 'doc' | 'project';++/**+ * Doc/Project scope switch for right-rail panels. Problems uses it today;+ * other per-doc panels (Timeline) can adopt the same header when they grow a+ * project-wide view, so the two scopes stay one non-diverging experience.+ */+export function PanelScopeHeader({+ scope,+ onScopeChange,+}: {+ scope: PanelScope;+ onScopeChange: (scope: PanelScope) => void;+}) {+ const { t } = useLingui();+ return (+ <div className="shrink-0 px-4 pb-2">+ <ToggleGroup+ type="single"+ variant="segmented"+ size="sm"+ spacing={1}+ value={scope}+ onValueChange={(value: PanelScope) => {+ if (value) onScopeChange(value);+ }}+ aria-label={t`Scope`}+ className="w-full rounded-md bg-muted p-0.5 dark:bg-background"+ >+ <ToggleGroupItem value="doc" className="flex-1" data-testid="panel-scope-doc">+ <Trans>This doc</Trans>+ </ToggleGroupItem>+ <ToggleGroupItem value="project" className="flex-1" data-testid="panel-scope-project">+ <Trans>Project</Trans>+ </ToggleGroupItem>+ </ToggleGroup>+ </div>+ );+}diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsxnew file mode 100644index 000000000..5b7420eb4--- /dev/null+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx@@ -0,0 +1,343 @@+/**+ * Behavioral tests for ProblemsPanel: renders a row per diagnostic, shows the+ * empty state, and on row click dispatches a LINT_NAV_EVENT plus banks a+ * pending lint intent so the source editor can jump now or on its next+ * activation. Project scope runs the audit on demand (never on mount), caches+ * the result across scope flips, re-fetches only through the refresh+ * affordance, and click-navigates to the offending doc by hash.+ */++import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { LintAuditResponse, LintDiagnostic } from '@inkeep/open-knowledge-core';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++mock.module('@lingui/core/macro', () => ({ t: renderLinguiTemplate }));+mock.module('@lingui/react/macro', () => ({+ Trans: ({ children }: { children: ReactNode }) => children,+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (+ <>{(value === 1 ? one : other).replace('#', String(value))}</>+ ),+ useLingui: () => ({ t: renderLinguiTemplate }),+}));++let auditCalls = 0;+let runLintAuditImpl: () => Promise<LintAuditResponse | null> = async () => null;++mock.module('@/editor/lint-config-client', () => ({+ emitLintConfigChanged: () => {},+ subscribeToLintConfigChanged: () => () => {},+ runLintAudit: () => {+ auditCalls += 1;+ return runLintAuditImpl();+ },+ useDocLintConfig: () => ({ data: null }),+ useProjectLintConfig: () => ({ data: null }),+ fetchEffectiveLintConfig: async () => null,+ writeMarkdownlintRule: async () => ({ ok: false, errorDetail: null }),+}));++const { ProblemsPanel, LINT_NAV_EVENT } = await import('./ProblemsPanel');+// The real registry, deliberately unmocked: the tests assert the banked intent+// through its public consume API — the same call the source editor replays.+const { consumePendingSourceNavigation, clearPendingSourceNavigationsForTest } = await import(+ '@/editor/source-editor-navigation'+);++/** Diagnostic at a 1-based line/column (the display convention these tests assert). */+function diag(over: Partial<LintDiagnostic> & { line?: number; column?: number }): LintDiagnostic {+ const { line = 3, column = 1, ...rest } = over;+ return {+ range: {+ start: { line: line - 1, character: column - 1 },+ end: { line: line - 1, character: column },+ },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ ...rest,+ };+}++function auditResult(over: Partial<LintAuditResponse> = {}): LintAuditResponse {+ return { files: [], fileCount: 3, errorCount: 0, warningCount: 0, warnings: [], ...over };+}++beforeEach(() => {+ auditCalls = 0;+ runLintAuditImpl = async () => null;+});++afterEach(() => {+ cleanup();+ clearPendingSourceNavigationsForTest();+ window.location.hash = '';+});++describe('ProblemsPanel', () => {+ test('shows the empty state when there are no diagnostics', () => {+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ expect(screen.getByText('No problems found.')).toBeTruthy();+ });++ test('a fixable row renders a Fix button that calls onFix; unfixable does not', () => {+ const fixable = diag({+ line: 3,+ code: 'MD010',+ fixes: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ },+ ],+ });+ const unfixable = diag({ line: 5, code: 'MD025', message: 'Multiple H1' });+ const onFix = mock(() => {});+ render(<ProblemsPanel docName="notes" diagnostics={[fixable, unfixable]} onFix={onFix} />);+ const fixButtons = screen.getAllByRole('button', { name: /Fix markdownlint\/MD010/ });+ expect(fixButtons).toHaveLength(1);+ // The unfixable row has no Fix button.+ expect(screen.queryByRole('button', { name: /Fix markdownlint\/MD025/ })).toBeNull();+ fixButtons[0]?.click();+ expect(onFix).toHaveBeenCalledTimes(1);+ });++ test('without onFix, a fixable row renders no Fix button', () => {+ const fixable = diag({+ code: 'MD010',+ fixes: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ },+ ],+ });+ render(<ProblemsPanel docName="notes" diagnostics={[fixable]} />);+ expect(screen.queryByRole('button', { name: /Fix markdownlint/ })).toBeNull();+ });++ test('renders a row per diagnostic, sorted by line', () => {+ const diagnostics = [+ diag({ code: 'MD012', message: 'Multiple blanks', line: 9 }),+ diag({ code: 'MD010', message: 'Hard tabs', line: 2 }),+ ];+ render(<ProblemsPanel docName="notes" diagnostics={diagnostics} />);+ const buttons = screen.getAllByRole('button');+ expect(buttons).toHaveLength(2);+ // Lower line sorts first.+ expect(buttons[0]?.textContent).toContain('MD010');+ expect(buttons[1]?.textContent).toContain('MD012');+ });++ test('clicking a row dispatches LINT_NAV_EVENT with the line', () => {+ let received: { line: number; column: number } | null = null;+ const listener = (e: Event) => {+ received = (e as CustomEvent<{ line: number; column: number }>).detail;+ };+ window.addEventListener(LINT_NAV_EVENT, listener);+ try {+ render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 7, column: 2 })]} />);+ fireEvent.click(screen.getByRole('button'));+ expect(received).toEqual({ line: 7, column: 2 });+ } finally {+ window.removeEventListener(LINT_NAV_EVENT, listener);+ }+ });++ test('clicking a row banks a pending lint intent for later source-mode activation', () => {+ render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 7, column: 2 })]} />);+ fireEvent.click(screen.getByRole('button'));+ // Banked even though no source editor consumed the event (WYSIWYG case):+ // the next source-mode activation within the TTL replays it.+ expect(consumePendingSourceNavigation('notes')).toEqual({+ kind: 'lint',+ detail: { line: 7, column: 2 },+ });+ });+});++describe('ProblemsPanel — project scope', () => {+ test('audit runs on demand at first Project activation and renders per-file groups', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ files: [+ {+ file: 'guides/setup.md',+ diagnostics: [+ diag({ line: 4 }),+ diag({ code: 'MD001', message: 'Heading increment', line: 8 }),+ ],+ },+ { file: 'notes.md', diagnostics: [diag({ line: 2 })] },+ ],+ fileCount: 5,+ warningCount: 3,+ });++ render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 1 })]} />);+ // Mounting the panel in doc scope never runs the audit.+ expect(auditCalls).toBe(0);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());+ expect(auditCalls).toBe(1);++ // Per-file groups list their diagnostics (expanded by default) with counts.+ expect(screen.getByText('notes.md')).toBeTruthy();+ expect(screen.getByText('Heading increment')).toBeTruthy();+ const groups = screen.getAllByTestId('problems-audit-group');+ expect(groups).toHaveLength(2);+ expect(groups[0]?.querySelector('[data-testid="problems-audit-file-count"]')?.textContent).toBe(+ '2',+ );+ // The summary carries the audit-wide error/warning counts.+ expect(screen.getByTestId('problems-audit-summary').textContent).toContain('0 errors');+ expect(screen.getByTestId('problems-audit-summary').textContent).toContain('3 warnings');+ });++ test('the cached result is reused when toggling scopes; refresh re-fetches', async () => {+ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'first.md', diagnostics: [diag({})] }] });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('first.md')).toBeTruthy());++ fireEvent.click(screen.getByTestId('panel-scope-doc'));+ expect(screen.getByText('No problems found.')).toBeTruthy();+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ // Re-activation shows the cached snapshot without a new fetch.+ expect(screen.getByText('first.md')).toBeTruthy();+ expect(auditCalls).toBe(1);++ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'second.md', diagnostics: [diag({})] }] });+ fireEvent.click(screen.getByLabelText('Refresh audit'));+ await waitFor(() => expect(screen.getByText('second.md')).toBeTruthy());+ expect(auditCalls).toBe(2);+ expect(screen.queryByText('first.md')).toBeNull();+ });++ test('a pending audit shows the loading skeleton with the refresh disabled', async () => {+ let resolveAudit: (value: LintAuditResponse | null) => void = () => {};+ runLintAuditImpl = () =>+ new Promise((resolve) => {+ resolveAudit = resolve;+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ const status = await screen.findByRole('status');+ expect(status.getAttribute('aria-busy')).toBe('true');+ expect((screen.getByLabelText('Refresh audit') as HTMLButtonElement).disabled).toBe(true);++ resolveAudit(auditResult({ fileCount: 2 }));+ await waitFor(() => expect(screen.getByText('No problems across 2 documents.')).toBeTruthy());+ expect((screen.getByLabelText('Refresh audit') as HTMLButtonElement).disabled).toBe(false);+ });++ test('a failed audit surfaces the error and refresh retries it', async () => {+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() =>+ expect(screen.getByText('The audit could not be completed. Try again.')).toBeTruthy(),+ );++ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'retried.md', diagnostics: [diag({})] }] });+ fireEvent.click(screen.getByLabelText('Refresh audit'));+ await waitFor(() => expect(screen.getByText('retried.md')).toBeTruthy());+ expect(screen.queryByText('The audit could not be completed. Try again.')).toBeNull();+ });++ test('config warnings from the audit render above the file groups', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ files: [{ file: 'notes.md', diagnostics: [diag({})] }],+ warnings: ['Failed to parse .markdownlint.json: unexpected token'],+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() =>+ expect(screen.getByText('Failed to parse .markdownlint.json: unexpected token')).toBeTruthy(),+ );+ });++ test('clicking a project-scope diagnostic for another doc navigates by hash and banks the intent', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ files: [{ file: 'guides/setup.md', diagnostics: [diag({ line: 4, column: 2 })] }],+ });+ let navEvents = 0;+ const listener = () => {+ navEvents += 1;+ };+ window.addEventListener(LINT_NAV_EVENT, listener);+ try {+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());++ fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));++ expect(window.location.hash).toBe('#/guides/setup');+ expect(consumePendingSourceNavigation('guides/setup')).toEqual({+ kind: 'lint',+ detail: { line: 4, column: 2 },+ });+ // The in-doc nav event stays quiet on cross-doc clicks — it carries no+ // docName and would move the cursor in the doc that is still open.+ expect(navEvents).toBe(0);+ } finally {+ window.removeEventListener(LINT_NAV_EVENT, listener);+ }+ });++ test('clicking a project-scope diagnostic for the open doc keeps the in-doc event fast path', async () => {+ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'notes.md', diagnostics: [diag({ line: 7, column: 2 })] }] });+ let received: { line: number; column: number } | null = null;+ const listener = (e: Event) => {+ received = (e as CustomEvent<{ line: number; column: number }>).detail;+ };+ window.addEventListener(LINT_NAV_EVENT, listener);+ try {+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('notes.md')).toBeTruthy());+ const hashBefore = window.location.hash;++ fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));++ expect(received).toEqual({ line: 7, column: 2 });+ expect(window.location.hash).toBe(hashBefore);+ expect(consumePendingSourceNavigation('notes')).toEqual({+ kind: 'lint',+ detail: { line: 7, column: 2 },+ });+ } finally {+ window.removeEventListener(LINT_NAV_EVENT, listener);+ }+ });++ test('doc-scope content and count stay doc-scoped while project scope is active', async () => {+ runLintAuditImpl = async () =>+ auditResult({ files: [{ file: 'other.md', diagnostics: [diag({}), diag({ line: 9 })] }] });+ render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 1 })]} />);+ // Doc scope shows the doc's own diagnostic count in the panel header.+ expect(screen.getByText('1')).toBeTruthy();++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('other.md')).toBeTruthy());+ // The header count belongs to doc scope; project scope drops it rather+ // than mislabel project totals with the doc's number.+ expect(screen.queryByText('1', { selector: '[data-slot="panel-count"]' })).toBeNull();++ fireEvent.click(screen.getByTestId('panel-scope-doc'));+ expect(screen.getByText('Hard tabs')).toBeTruthy();+ });+});diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsxnew file mode 100644index 000000000..a17c96893--- /dev/null+++ b/packages/app/src/components/ProblemsPanel.tsx@@ -0,0 +1,381 @@+// biome-ignore-all lint/plugin/no-raw-html-interactive-element: matches sibling OutlinePanel — positional list of <button> rows awaiting a shared shadcn list primitive; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit+import type { LintAuditResponse, LintDiagnostic, LintDocResult } from '@inkeep/open-knowledge-core';+import { Plural, Trans, useLingui } from '@lingui/react/macro';+import { AlertCircle, AlertTriangle, ChevronRight, RefreshCw, Wrench } from 'lucide-react';+import { useState } from 'react';+import { type PanelScope, PanelScopeHeader } from '@/components/PanelScopeHeader';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+import {+ Panel,+ PanelBody,+ PanelCount,+ PanelEmpty,+ PanelError,+ PanelHeader,+ PanelTitle,+} from '@/components/ui/panel';+import { Skeleton } from '@/components/ui/skeleton';+import { runLintAudit } from '@/editor/lint-config-client';+import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';+import { filePathToDocName, hashFromDocName } from '@/lib/doc-hash';+import { cn } from '@/lib/utils';++/** Jump-to-line intent dispatched when a problem row is clicked in source mode. */+export interface LintNavDetail {+ /** 1-based line in `Y.Text('source')` (full doc incl. frontmatter). */+ line: number;+ /** 1-based column. */+ column: number;+}++export const LINT_NAV_EVENT = 'open-knowledge:lint-nav';++/**+ * Wire-loose diagnostic shape from the audit response. The engine's+ * `LintDiagnostic` (doc scope) is a subtype — its `source` is a plugin-id+ * literal where the wire admits any string — so the row helpers below accept+ * this wider shape and serve both scopes.+ */+type DiagnosticLike = LintDocResult['diagnostics'][number];++/** Stable sort key: line, then column. */+function compareDiagnostics(a: DiagnosticLike, b: DiagnosticLike): number {+ return (+ a.range.start.line - b.range.start.line || a.range.start.character - b.range.start.character+ );+}++/** The nav contract is 1-based (CodeMirror lines); the diagnostic range is 0-based LSP. */+function lintNavDetailOf(diagnostic: DiagnosticLike): LintNavDetail {+ return {+ line: diagnostic.range.start.line + 1,+ column: diagnostic.range.start.character + 1,+ };+}++type ProjectAuditState =+ | { status: 'idle' }+ | { status: 'loading' }+ | { status: 'loaded'; result: LintAuditResponse }+ | { status: 'failed' };++/** Message line + `source/code · line` subline shared by doc- and project-scope rows. */+function DiagnosticRowBody({ diagnostic }: { diagnostic: DiagnosticLike }) {+ const { t } = useLingui();+ const Icon = diagnostic.severity === 'error' ? AlertCircle : AlertTriangle;+ const flatId = `${diagnostic.source}/${diagnostic.code}`;+ const displayLine = diagnostic.range.start.line + 1;+ return (+ <>+ <span className="flex items-start gap-1.5 text-sm">+ <Icon+ aria-hidden="true"+ className={cn(+ 'mt-0.5 size-3.5 shrink-0',+ diagnostic.severity === 'error' ? 'text-destructive' : 'text-amber-500',+ )}+ />+ <span className="text-foreground">{diagnostic.message}</span>+ </span>+ <span className="ps-5 font-mono text-xs text-muted-foreground">+ {flatId} · {t`line ${displayLine}`}+ </span>+ </>+ );+}++function diagnosticKey(diagnostic: DiagnosticLike): string {+ return `${diagnostic.source}/${diagnostic.code}-${diagnostic.range.start.line}-${diagnostic.range.start.character}-${diagnostic.message}`;+}++/**+ * Lint diagnostics panel in the right-hand doc rail, scoped per-doc or+ * project-wide. Doc scope is live and mode-agnostic: `useDocDiagnostics`+ * lints `Y.Text('source')` directly, so the list is populated in WYSIWYG mode+ * too (where no CodeMirror view exists); clicking a row jumps to that line in+ * source mode, or to the containing block in WYSIWYG (the visible editor+ * consumes the nav event). Project scope audits the whole content dir strictly+ * on demand (scope activation or the refresh button — never on mount, never+ * polled) and keeps the last snapshot across scope flips; its rows navigate to+ * the offending doc by hash.+ */+export function ProblemsPanel({+ docName,+ diagnostics,+ onFix,+}: {+ docName: string;+ diagnostics: LintDiagnostic[];+ /** Apply a fixable diagnostic's auto-fix (this-doc scope only). When absent+ * (e.g. unit harness), fixable rows render no Fix button. */+ onFix?: (diagnostic: LintDiagnostic) => void;+}) {+ const { t } = useLingui();+ const [scope, setScope] = useState<PanelScope>('doc');+ const [audit, setAudit] = useState<ProjectAuditState>({ status: 'idle' });++ const sorted = [...diagnostics].sort(compareDiagnostics);++ async function loadAudit() {+ setAudit({ status: 'loading' });+ const result = await runLintAudit();+ setAudit(result === null ? { status: 'failed' } : { status: 'loaded', result });+ }++ function handleScopeChange(next: PanelScope) {+ setScope(next);+ // Only the first activation fetches; afterwards the snapshot is served+ // until an explicit refresh (a failed run keeps its error until retried).+ if (next === 'project' && audit.status === 'idle') void loadAudit();+ }++ function handleNav(diagnostic: DiagnosticLike) {+ const detail = lintNavDetailOf(diagnostic);+ // Banked unconditionally: the visible editor (source line-jump, or the+ // WYSIWYG block-jump in markdown-lint-decorations) consumes the event live+ // and clears the intent; when neither can anchor it (frontmatter+ // diagnostics in WYSIWYG), the intent waits (bounded by the registry TTL)+ // for the next source-mode activation.+ rememberPendingSourceNavigation(docName, { kind: 'lint', detail });+ window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail }));+ }++ function handleProjectNav(filePath: string, diagnostic: DiagnosticLike) {+ const targetDocName = filePathToDocName(filePath);+ if (targetDocName === docName) {+ handleNav(diagnostic);+ return;+ }+ rememberPendingSourceNavigation(targetDocName, {+ kind: 'lint',+ detail: lintNavDetailOf(diagnostic),+ });+ // No LINT_NAV_EVENT here: the event carries no docName and would move the+ // cursor in the doc that is still open. The banked intent replays once+ // the target doc's source editor activates.+ window.location.hash = hashFromDocName(targetDocName);+ }++ return (+ <Panel>+ <PanelHeader>+ <PanelTitle>+ <Trans>Problems</Trans>+ </PanelTitle>+ {scope === 'doc' && sorted.length > 0 && <PanelCount>{sorted.length}</PanelCount>}+ </PanelHeader>+ <PanelScopeHeader scope={scope} onScopeChange={handleScopeChange} />+ {scope === 'doc' ? (+ <PanelBody className="px-2 py-2">+ {sorted.length === 0 ? (+ <PanelEmpty className="px-2">+ <Trans>No problems found.</Trans>+ </PanelEmpty>+ ) : (+ <ul aria-label={t`Problems`} className="flex flex-col gap-0.5">+ {sorted.map((diagnostic) => {+ const displayLine = diagnostic.range.start.line + 1;+ const fixable = onFix !== undefined && (diagnostic.fixes?.length ?? 0) > 0;+ const flatId = `${diagnostic.source}/${diagnostic.code}`;+ return (+ <li+ key={diagnosticKey(diagnostic)}+ className="group flex items-start gap-1 rounded transition-colors hover:bg-muted"+ >+ <button+ type="button"+ onClick={() => handleNav(diagnostic)}+ className="flex flex-1 cursor-pointer flex-col gap-0.5 rounded px-2 py-1.5 text-left"+ title={t`Go to line ${displayLine}`}+ >+ <DiagnosticRowBody diagnostic={diagnostic} />+ </button>+ {fixable ? (+ <Button+ size="sm"+ variant="ghost"+ className="mt-1 mr-1 h-6 shrink-0 px-2 text-xs opacity-0 focus-visible:opacity-100 group-hover:opacity-100"+ onClick={() => onFix?.(diagnostic)}+ aria-label={t`Fix ${flatId}`}+ data-testid="problems-fix"+ >+ <Wrench aria-hidden="true" className="size-3" />+ <Trans>Fix</Trans>+ </Button>+ ) : null}+ </li>+ );+ })}+ </ul>+ )}+ </PanelBody>+ ) : (+ <ProjectAuditBody+ audit={audit}+ onRefresh={() => void loadAudit()}+ onNavigate={handleProjectNav}+ />+ )}+ </Panel>+ );+}++function ProjectAuditBody({+ audit,+ onRefresh,+ onNavigate,+}: {+ audit: ProjectAuditState;+ onRefresh: () => void;+ onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;+}) {+ const { t } = useLingui();+ const loading = audit.status === 'loading' || audit.status === 'idle';+ return (+ <PanelBody className="px-2 py-2" data-testid="problems-project-scope">+ <div className="flex items-center justify-between gap-2 px-2 pb-1">+ <p className="text-xs text-muted-foreground" data-testid="problems-audit-summary">+ {audit.status === 'loaded' && (+ <>+ <Plural value={audit.result.errorCount} one="# error" other="# errors" />+ {' · '}+ <Plural value={audit.result.warningCount} one="# warning" other="# warnings" />+ </>+ )}+ </p>+ <Button+ variant="ghost"+ size="icon"+ className="size-6 shrink-0 text-muted-foreground"+ aria-label={t`Refresh audit`}+ data-testid="problems-audit-refresh"+ disabled={loading}+ onClick={onRefresh}+ >+ <RefreshCw className="size-3.5" />+ </Button>+ </div>++ {loading && (+ <div+ className="flex flex-col gap-1"+ role="status"+ aria-busy="true"+ aria-label={t`Running project audit`}+ >+ {[1, 2, 3].map((i) => (+ <div key={i} className="flex items-start gap-2.5 rounded px-2 py-1.5">+ <Skeleton className="mt-0.5 size-3.5 shrink-0 rounded" />+ <div className="flex-1 space-y-1.5">+ <Skeleton className="h-3 w-28" />+ <Skeleton className="h-3 w-40" />+ </div>+ </div>+ ))}+ </div>+ )}++ {audit.status === 'failed' && (+ <PanelError className="px-2 text-xs">+ <Trans>The audit could not be completed. Try again.</Trans>+ </PanelError>+ )}++ {audit.status === 'loaded' && (+ <ProjectAuditResults result={audit.result} onNavigate={onNavigate} />+ )}+ </PanelBody>+ );+}++function ProjectAuditResults({+ result,+ onNavigate,+}: {+ result: LintAuditResponse;+ onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;+}) {+ const { t } = useLingui();+ return (+ <div className="flex flex-col gap-1">+ {result.warnings.length > 0 && (+ <ul aria-label={t`Configuration warnings`} className="flex flex-col gap-0.5 pb-1">+ {result.warnings.map((warning, index) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: the warnings array is a static audit snapshot (no reorder/insert between renders), and identical config warnings can legitimately repeat — a text-only key would collide.+ <li key={`${index}-${warning}`} className="flex items-start gap-1.5 px-2 text-xs">+ <AlertTriangle+ aria-hidden="true"+ className="mt-0.5 size-3.5 shrink-0 text-amber-500"+ />+ <span className="min-w-0 text-foreground">{warning}</span>+ </li>+ ))}+ </ul>+ )}+ {result.files.length === 0 ? (+ <PanelEmpty className="px-2">+ <Plural+ value={result.fileCount}+ one="No problems across # document."+ other="No problems across # documents."+ />+ </PanelEmpty>+ ) : (+ result.files.map((file) => (+ <ProjectFileGroup key={file.file} file={file} onNavigate={onNavigate} />+ ))+ )}+ </div>+ );+}++function ProjectFileGroup({+ file,+ onNavigate,+}: {+ file: LintDocResult;+ onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;+}) {+ const { t } = useLingui();+ const sorted = [...file.diagnostics].sort(compareDiagnostics);+ return (+ <Collapsible defaultOpen data-testid="problems-audit-group">+ <CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-1.5 rounded px-2 py-1.5 text-left transition-colors hover:bg-muted">+ <ChevronRight+ aria-hidden="true"+ className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-90 motion-reduce:transition-none"+ />+ <span+ className="min-w-0 flex-1 truncate font-mono text-xs text-foreground"+ title={file.file}+ >+ {file.file}+ </span>+ <Badge variant="gray" data-testid="problems-audit-file-count" className="shrink-0">+ {sorted.length}+ </Badge>+ </CollapsibleTrigger>+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">+ <ul aria-label={t`Problems in ${file.file}`} className="flex flex-col gap-0.5 pb-1 ps-3">+ {sorted.map((diagnostic) => {+ const displayLine = diagnostic.range.start.line + 1;+ return (+ <li key={diagnosticKey(diagnostic)}>+ <button+ type="button"+ onClick={() => onNavigate(file.file, diagnostic)}+ className="flex w-full cursor-pointer flex-col gap-0.5 rounded px-2 py-1.5 text-left transition-colors hover:bg-muted"+ title={t`Go to line ${displayLine} in ${file.file}`}+ >+ <DiagnosticRowBody diagnostic={diagnostic} />+ </button>+ </li>+ );+ })}+ </ul>+ </CollapsibleContent>+ </Collapsible>+ );+}diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsxindex 32941e1a1..df9641984 100644--- a/packages/app/src/components/TerminalDock.tsx+++ b/packages/app/src/components/TerminalDock.tsx@@ -6,7 +6,7 @@ import type { TerminalDockPosition } from '@/lib/terminal-dock-store';import { getInitialTerminalHeight, writeTerminalHeight } from '@/lib/terminal-height-store';import { cn } from '@/lib/utils';import { TerminalRevealTab } from './TerminalRevealTab';-import { xtermThemeForMode } from './terminal-theme';+import { useLiveXtermTheme } from './use-live-xterm-theme';const TERMINAL_PANEL_ID = 'terminal-dock-panel';@@ -69,7 +69,7 @@ export function TerminalDock({const { resolvedTheme } = useTheme();const panelRef = usePanelRef();const [isCollapsed, setIsCollapsed] = useState(!visible);- const xtermBackground = xtermThemeForMode(resolvedTheme).background;+ const xtermBackground = useLiveXtermTheme(resolvedTheme).background;// A right-docked terminal keeps `visible` true while this panel sits collapsed// and empty — the handle must gate on this, not `visible`, or the grabber// lingers and drags up an empty panel.diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsxindex 6f0bfcef0..a55a917e5 100644--- a/packages/app/src/components/TerminalPanel.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx@@ -1221,7 +1221,7 @@ describe('TerminalPanel', () => {const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });render(<TerminalPanel bridge={bridge} />);await waitFor(() => expect(lastTerm).not.toBeNull());- expect(lastTerm?.options.theme).toBe(XTERM_LIGHT_THEME);+ expect(lastTerm?.options.theme).toEqual(XTERM_LIGHT_THEME);cleanup();lastTerm = null;@@ -1229,7 +1229,7 @@ describe('TerminalPanel', () => {const second = makeBridge({ ok: true, ptyId: 'pty-2' });render(<TerminalPanel bridge={second.bridge} />);await waitFor(() => expect(lastTerm).not.toBeNull());- expect(lastTerm?.options.theme).toBe(XTERM_DARK_THEME);+ expect(lastTerm?.options.theme).toEqual(XTERM_DARK_THEME);});test('re-skins the live terminal on a theme switch without respawning the PTY', async () => {@@ -1239,13 +1239,13 @@ describe('TerminalPanel', () => {await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));const term = lastTerm;- expect(term?.options.theme).toBe(XTERM_DARK_THEME);+ expect(term?.options.theme).toEqual(XTERM_DARK_THEME);// Flip the app theme and re-render: the open session must re-skin in place.mockResolvedTheme = 'light';rerender(<TerminalPanel bridge={bridge} />);- await waitFor(() => expect(lastTerm?.options.theme).toBe(XTERM_LIGHT_THEME));+ await waitFor(() => expect(lastTerm?.options.theme).toEqual(XTERM_LIGHT_THEME));// Same xterm instance, same PTY — no teardown/respawn on a theme change.expect(lastTerm).toBe(term);expect(term?.dispose).not.toHaveBeenCalled();diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex 07506bd39..ac90bb941 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -28,8 +28,8 @@ import { createTerminalFileLinkProvider } from './terminal-link-provider';import { createRecentOpenGuard, type TerminalLinkTarget } from './terminal-links';import { createSameFrameRepaint } from './terminal-render-flush';import { createResizeThrottle } from './terminal-resize-throttle';-import { xtermThemeForMode } from './terminal-theme';import { nextWheelReports, sgrWheelReport, wheelReportPosition } from './terminal-wheel';+import { useLiveXtermTheme } from './use-live-xterm-theme';/*** Interval for the PTY-resize throttle (see terminal-resize-throttle.ts).@@ -115,6 +115,7 @@ export function TerminalPanel({// Paint the panel chrome (the kill strip) with the exact xterm canvas color so// the strip and the terminal read as one surface — single source: terminal-theme.const { resolvedTheme } = useTheme();+ const xtermTheme = useLiveXtermTheme(resolvedTheme);// Restart is a full session reset: bumping the key remounts TerminalSession,// which disposes the dead terminal and spawns a fresh PTY in the same window// (cwd is fixed per window in main) — no stale listeners survive the swap.@@ -129,7 +130,7 @@ export function TerminalPanel({// is remounted.<sectionaria-label={t`Terminal`}- style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}+ style={{ backgroundColor: xtermTheme.background }}className={cn('relative flex h-full w-full flex-col overflow-hidden', className)}>{/* Positioning context for the session's absolute exit/refusal notices, so@@ -187,12 +188,14 @@ function TerminalSession({const onTitleChangeRef = useRef(onTitleChange);const onPtyIdRef = useRef(onPtyId);const { resolvedTheme } = useTheme();+ // Palette derived from the live theme tokens (mode + color theme + custom).+ const xtermTheme = useLiveXtermTheme(resolvedTheme);// Live xterm instance, exposed so the theme effect below can re-skin it in// place — re-theming must not tear down and respawn the PTY.const termRef = useRef<Terminal | null>(null);- // Resolved theme captured at first render, used for the initial xterm- // palette; later theme changes flow through the dedicated effect below.- const initialResolvedThemeRef = useRef(resolvedTheme);+ // Palette captured at first render, used for the initial xterm theme; later+ // theme changes flow through the dedicated effect below.+ const initialXtermThemeRef = useRef(xtermTheme);const [status, setStatus] = useState<SessionStatus>('starting');const [readiness, setReadiness] = useState<ClaudeReadiness | null>(null);const [exitInfo, setExitInfo] = useState<TerminalExitInfo | null>(null);@@ -285,7 +288,7 @@ function TerminalSession({linkHandler: {activate: (_event, uri) => openUrl(uri),},- theme: xtermThemeForMode(initialResolvedThemeRef.current),+ theme: initialXtermThemeRef.current,});termRef.current = term;const fit = new FitAddon();@@ -879,14 +882,16 @@ function TerminalSession({// mount/adopt effect — it only satisfies the exhaustive-deps check.}, [bridge, adoptPtyId, launch]);- // Re-skin the live terminal when the app theme changes. Mutating- // `term.options.theme` re-paints in place, so an open session follows- // light/dark switches without a restart (the PTY and scrollback survive).+ // Re-skin the live terminal when the app theme changes — light/dark AND the+ // color-theme layer (useLiveXtermTheme keeps identity stable until colors+ // actually change). Mutating `term.options.theme` re-paints in place, so an+ // open session follows theme switches without a restart (the PTY and+ // scrollback survive).useEffect(() => {const term = termRef.current;if (term === null) return;- term.options.theme = xtermThemeForMode(resolvedTheme);- }, [resolvedTheme]);+ term.options.theme = xtermTheme;+ }, [xtermTheme]);// Follow assistive-tech attach/detach in place: toggling// `term.options.screenReaderMode` builds or tears down xterm's a11y DOMdiff --git a/packages/app/src/components/TerminalWindowApp.tsx b/packages/app/src/components/TerminalWindowApp.tsxindex 37359a87a..7beff2c4e 100644--- a/packages/app/src/components/TerminalWindowApp.tsx+++ b/packages/app/src/components/TerminalWindowApp.tsx@@ -4,7 +4,7 @@ import { useInstalledClis } from '@/hooks/use-installed-clis';import { ConfigProvider } from '@/lib/config-provider';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { TerminalSessionsHost } from './TerminalSessionsHost';-import { xtermThemeForMode } from './terminal-theme';+import { useLiveXtermTheme } from './use-live-xterm-theme';interface TerminalWindowAppProps {/** Desktop bridge — the terminal window renders only on the Electron host. */@@ -41,6 +41,9 @@ export function TerminalWindowApp({ bridge }: TerminalWindowAppProps) {function TerminalWindowBody({ bridge }: TerminalWindowAppProps) {const { resolvedTheme } = useTheme();+ // Live theme tokens (mode + color theme + custom), matching the xterm canvas+ // inside — the window chrome must not clash with a plugin/custom theme.+ const xtermTheme = useLiveXtermTheme(resolvedTheme);const installedClis = useInstalledClis();// The host portals its session subtree into this container (a callback-ref// state so the host re-renders once the div mounts).@@ -53,7 +56,7 @@ function TerminalWindowBody({ bridge }: TerminalWindowAppProps) {<divref={setContainer}className="flex h-screen min-h-0 flex-col"- style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}+ style={{ backgroundColor: xtermTheme.background }}/><TerminalSessionsHostbridge={bridge}diff --git a/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsxnew file mode 100644index 000000000..d3ba4e1a3--- /dev/null+++ b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx@@ -0,0 +1,58 @@+import { afterEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { COLOR_THEMES } from '@/lib/color-themes';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++mock.module('@lingui/react/macro', () => ({+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: renderLinguiTemplate }),+}));++async function renderPicker(value: string, onSelect: (id: string) => void) {+ const { ColorThemePicker } = await import('./ColorThemePicker');+ return render(<ColorThemePicker value={value} onSelect={onSelect} aria-label="Color theme" />);+}++describe('ColorThemePicker', () => {+ afterEach(cleanup);++ test('renders one radio tile per registered theme, labelled by name', async () => {+ await renderPicker('default', () => {});+ const radios = screen.getAllByRole('radio');+ expect(radios.length).toBe(COLOR_THEMES.length);+ for (const theme of COLOR_THEMES) {+ expect(screen.getByText(theme.label)).toBeDefined();+ }+ });++ test('marks the selected theme as checked', async () => {+ await renderPicker('dracula', () => {});+ const dracula = screen.getByRole('radio', { name: /Dracula/ });+ expect(dracula.getAttribute('data-state')).toBe('checked');+ const mocha = screen.getByRole('radio', { name: /Catppuccin Frappé/ });+ expect(mocha.getAttribute('data-state')).toBe('unchecked');+ });++ test('falls back to default when value is empty or unknown', async () => {+ await renderPicker('', () => {});+ const def = screen.getByRole('radio', { name: /Default/ });+ expect(def.getAttribute('data-state')).toBe('checked');+ });++ test('fires onSelect with the theme id when a tile is activated', async () => {+ const picks: string[] = [];+ await renderPicker('default', (id) => picks.push(id));+ fireEvent.click(screen.getByRole('radio', { name: /Catppuccin Frappé/ }));+ expect(picks).toEqual(['catppuccin-frappe']);+ });++ test('tags themes by their forced mode: default is Auto, Latte is Light, the rest Dark', async () => {+ await renderPicker('default', () => {});+ // Default is the only Auto; Catppuccin Latte is the only Light palette; every+ // other palette (the dark IDE themes + the default-seed custom) is Dark.+ expect(screen.getAllByText('Auto').length).toBe(1);+ expect(screen.getAllByText('Light').length).toBe(1);+ expect(screen.getAllByText('Dark').length).toBe(COLOR_THEMES.length - 2);+ });+});diff --git a/packages/app/src/components/settings/ColorThemePicker.tsx b/packages/app/src/components/settings/ColorThemePicker.tsxnew file mode 100644index 000000000..cf928c6db--- /dev/null+++ b/packages/app/src/components/settings/ColorThemePicker.tsx@@ -0,0 +1,169 @@+import { useLingui } from '@lingui/react/macro';+import { RadioGroup as RadioGroupPrimitive } from 'radix-ui';+import {+ COLOR_THEMES,+ type ColorTheme,+ type CustomThemeSeed,+ customThemeKind,+ expandCustomSeed,+ expandPalette,+ resolveCustomSeed,+} from '@/lib/color-themes';+import { cn } from '@/lib/utils';++type SeedInput = Partial<Record<keyof CustomThemeSeed, unknown>> | undefined;++interface ColorThemePickerProps {+ /** Currently-selected theme id (the `appearance.colorTheme` value; `''`/unknown → default). */+ value: string;+ /** Fired with the chosen theme id when a tile is activated. */+ onSelect: (id: string) => void;+ /** The user's custom-theme seed (partial), used to paint the Custom tile preview. */+ customSeed?: SeedInput;+ /** Forwarded id (from the settings form's `<FormControl>` Slot) onto the radio group root. */+ id?: string;+ 'aria-label'?: string;+ 'aria-describedby'?: string;+}++/** The handful of palette colors a preview tile renders. */+interface SwatchColors {+ chrome: string;+ surface: string;+ bar: string;+ line: string;+ dots: [string, string, string];+}++function swatchFromTokens(t: Record<string, string>): SwatchColors {+ return {+ chrome: t.sidebar,+ surface: t.background,+ bar: t.primary,+ line: t.border,+ dots: [t['syntax-string'], t['syntax-keyword'], t['syntax-atom']],+ };+}++function swatchColors(theme: ColorTheme, customSeed: SeedInput): SwatchColors {+ if (theme.id === 'custom') {+ return swatchFromTokens(expandPalette(expandCustomSeed(resolveCustomSeed(customSeed))));+ }+ if (!theme.base) {+ // `default` tracks the user's live theme — read the cascaded CSS vars so the+ // tile reflects their current light/dark appearance.+ return {+ chrome: 'var(--sidebar)',+ surface: 'var(--background)',+ bar: 'var(--primary)',+ line: 'var(--border)',+ dots: ['var(--chart-2)', 'var(--chart-4)', 'var(--chart-3)'],+ };+ }+ return swatchFromTokens(expandPalette(theme.base));+}++/** A miniature editor-window preview, à la the Vivaldi theme tiles. */+function ThemeSwatch({ theme, customSeed }: { theme: ColorTheme; customSeed: SeedInput }) {+ const c = swatchColors(theme, customSeed);+ return (+ <div+ aria-hidden+ className="aspect-[4/3] w-full overflow-hidden rounded-md border"+ style={{ backgroundColor: c.surface, borderColor: c.line }}+ >+ {/* Title bar: accent pill + a faux address field. */}+ <div+ className="flex h-1/3 items-center gap-1 px-1.5"+ style={{ backgroundColor: c.chrome, borderBottom: `1px solid ${c.line}` }}+ >+ <span className="h-1.5 w-5 rounded-full" style={{ backgroundColor: c.bar }} />+ <span+ className="h-1.5 flex-1 rounded-full opacity-50"+ style={{ backgroundColor: c.line }}+ />+ </div>+ {/* Body: a sidebar rail of dots + content accents. */}+ <div className="flex h-2/3">+ <div+ className="flex w-1/4 flex-col items-center justify-center gap-1"+ style={{ backgroundColor: c.chrome, borderRight: `1px solid ${c.line}` }}+ >+ {c.dots.map((dot, i) => (+ <span+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length decorative swatch dots+ key={i}+ className="size-1.5 rounded-full"+ style={{ backgroundColor: dot }}+ />+ ))}+ </div>+ <div className="flex flex-1 flex-col justify-center gap-1 px-1.5">+ <span className="h-1.5 w-3/4 rounded-full" style={{ backgroundColor: c.dots[1] }} />+ <span+ className="h-1.5 w-1/2 rounded-full opacity-60"+ style={{ backgroundColor: c.line }}+ />+ <span className="h-1.5 w-2/3 rounded-full" style={{ backgroundColor: c.dots[0] }} />+ </div>+ </div>+ </div>+ );+}++/**+ * Tile grid for `appearance.colorTheme`. Radix `RadioGroup` gives single-select+ * semantics + roving-focus arrow-key navigation; each item renders as a button,+ * so no raw interactive element is introduced. The `default` tile follows the+ * light/dark mode toggle above it; the IDE tiles are self-contained dark+ * palettes; the `custom` tile previews the user's own seed.+ */+export function ColorThemePicker({+ value,+ onSelect,+ customSeed,+ id,+ 'aria-label': ariaLabel,+ 'aria-describedby': ariaDescribedby,+}: ColorThemePickerProps) {+ const { t } = useLingui();+ const selected = COLOR_THEMES.some((theme) => theme.id === value) ? value : 'default';+ return (+ <RadioGroupPrimitive.Root+ id={id}+ aria-label={ariaLabel}+ aria-describedby={ariaDescribedby}+ value={selected}+ onValueChange={onSelect}+ className="grid w-full grid-cols-2 gap-2 sm:grid-cols-3"+ >+ {COLOR_THEMES.map((theme) => (+ <RadioGroupPrimitive.Item+ key={theme.id}+ value={theme.id}+ className={cn(+ 'group/tile flex flex-col gap-1.5 rounded-lg border-2 border-transparent p-1 text-left outline-none',+ 'hover:bg-accent/50 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40',+ 'data-checked:border-primary',+ )}+ >+ <ThemeSwatch theme={theme} customSeed={customSeed} />+ <div className="flex items-center justify-between px-0.5">+ <span className="text-1sm font-medium text-foreground">{theme.label}</span>+ <span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ {theme.id === 'custom'+ ? customThemeKind(resolveCustomSeed(customSeed)) === 'dark'+ ? t`Dark`+ : t`Light`+ : theme.kind === 'system'+ ? t`Auto`+ : theme.kind === 'light'+ ? t`Light`+ : t`Dark`}+ </span>+ </div>+ </RadioGroupPrimitive.Item>+ ))}+ </RadioGroupPrimitive.Root>+ );+}diff --git a/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx b/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsxnew file mode 100644index 000000000..b662fafbc--- /dev/null+++ b/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx@@ -0,0 +1,90 @@+import { afterEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, fireEvent, render } from '@testing-library/react';+import type { ReactNode } from 'react';+import { DEFAULT_CUSTOM_SEED } from '@/lib/color-themes';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++let mergedConfig: { appearance?: { colorTheme?: string; customTheme?: Record<string, string> } } =+ {};+const patchCalls: unknown[] = [];++mock.module('@lingui/react/macro', () => ({+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: renderLinguiTemplate }),+}));+mock.module('next-themes', () => ({ useTheme: () => ({ setTheme: () => {} }) }));+mock.module('@/lib/config-context', () => ({+ useConfigContextOptional: () => ({ merged: mergedConfig }),+}));+mock.module('@/lib/use-apply-config-color-theme', () => ({+ applyColorThemeToDom: () => {},+}));++const userBinding = { patch: (p: unknown) => patchCalls.push(p) } as never;++async function renderEditor() {+ const { CustomThemeEditor } = await import('./CustomThemeEditor');+ return render(<CustomThemeEditor userBinding={userBinding} />);+}++describe('CustomThemeEditor', () => {+ afterEach(() => {+ cleanup();+ patchCalls.length = 0;+ mergedConfig = {};+ });++ test('renders a color + hex input for each of the six seed fields', async () => {+ const { container } = await renderEditor();+ expect(container.querySelectorAll('input[type="color"]').length).toBe(6);+ // 6 color + 6 hex text inputs.+ expect(container.querySelectorAll('input').length).toBe(12);+ });++ test('the section is a landmark labelled by its heading, like sibling subsections', async () => {+ const { container } = await renderEditor();+ const section = container.querySelector('section');+ expect(section?.getAttribute('aria-labelledby')).toBe('settings-custom-theme-title');+ const heading = container.querySelector('h3#settings-custom-theme-title');+ expect(heading?.textContent).toBe('Custom theme');+ });++ test('committing a valid hex patches that field on the user binding', async () => {+ mergedConfig = { appearance: { colorTheme: 'custom' } };+ const { container } = await renderEditor();+ const hex = container.querySelectorAll('input:not([type="color"])')[0] as HTMLInputElement;+ fireEvent.change(hex, { target: { value: '#123456' } });+ fireEvent.blur(hex, { target: { value: '#123456' } });+ expect(patchCalls).toContainEqual({ appearance: { customTheme: { background: '#123456' } } });+ });++ test('an invalid hex does not patch', async () => {+ const { container } = await renderEditor();+ const hex = container.querySelectorAll('input:not([type="color"])')[0] as HTMLInputElement;+ fireEvent.change(hex, { target: { value: 'nope' } });+ fireEvent.blur(hex, { target: { value: 'nope' } });+ expect(patchCalls.length).toBe(0);+ });++ test('an invalid hex shows an inline error, marks the field invalid, and keeps the value', async () => {+ const { container, queryByTestId } = await renderEditor();+ const hex = container.querySelectorAll('input:not([type="color"])')[0] as HTMLInputElement;+ // Pristine value is a valid hex — no error, not marked invalid.+ expect(queryByTestId('custom-theme-hex-error-background')).toBeNull();+ expect(hex.getAttribute('aria-invalid')).toBe('false');++ fireEvent.change(hex, { target: { value: '#12' } });+ expect(queryByTestId('custom-theme-hex-error-background')).not.toBeNull();+ expect(hex.getAttribute('aria-invalid')).toBe('true');+ // The invalid value stays visible (no silent revert) so the user can fix it.+ expect(hex.value).toBe('#12');+ });++ test('reset writes the full default seed', async () => {+ const { getByText } = await renderEditor();+ fireEvent.click(getByText('Reset'));+ expect(patchCalls).toContainEqual({+ appearance: { customTheme: { ...DEFAULT_CUSTOM_SEED } },+ });+ });+});diff --git a/packages/app/src/components/settings/CustomThemeEditor.tsx b/packages/app/src/components/settings/CustomThemeEditor.tsxnew file mode 100644index 000000000..3fd70c332--- /dev/null+++ b/packages/app/src/components/settings/CustomThemeEditor.tsx@@ -0,0 +1,189 @@+import type { ConfigBinding } from '@inkeep/open-knowledge-core';+import { useLingui } from '@lingui/react/macro';+import { useTheme } from 'next-themes';+import { useEffect, useState } from 'react';+import { Button } from '@/components/ui/button';+import { FieldError } from '@/components/ui/field';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ type CustomThemeSeed,+ customThemeKind,+ DEFAULT_CUSTOM_SEED,+ expandCustomSeed,+ expandPalette,+ isHexColor,+ resolveCustomSeed,+} from '@/lib/color-themes';+import { useConfigContextOptional } from '@/lib/config-context';+import { applyColorThemeToDom } from '@/lib/use-apply-config-color-theme';++const FIELD_ORDER: (keyof CustomThemeSeed)[] = [+ 'background',+ 'surface',+ 'foreground',+ 'primary',+ 'accent',+ 'border',+];++/** A compact mini-window preview painted from the live seed. */+function SeedPreview({ seed }: { seed: CustomThemeSeed }) {+ const t = expandPalette(expandCustomSeed(seed));+ return (+ <div+ aria-hidden+ className="h-20 w-32 shrink-0 overflow-hidden rounded-md border"+ style={{ backgroundColor: t.background, borderColor: t.border }}+ >+ <div+ className="flex h-1/3 items-center gap-1 px-1.5"+ style={{ backgroundColor: t.sidebar, borderBottom: `1px solid ${t.border}` }}+ >+ <span className="h-1.5 w-6 rounded-full" style={{ backgroundColor: t.primary }} />+ </div>+ <div className="flex flex-col gap-1 p-1.5">+ <span+ className="h-1.5 w-4/5 rounded-full"+ style={{ backgroundColor: t['syntax-keyword'] }}+ />+ <span+ className="h-1.5 w-3/5 rounded-full opacity-70"+ style={{ backgroundColor: t.foreground }}+ />+ <span+ className="h-1.5 w-2/3 rounded-full"+ style={{ backgroundColor: t['syntax-string'] }}+ />+ </div>+ </div>+ );+}++/**+ * Editor for the six `appearance.customTheme` seed colors (the `custom` color+ * theme). Reads the live seed from merged config, writes per-field through the+ * user `ConfigBinding`, and — when `custom` is the active theme — applies edits+ * to the DOM optimistically so the whole app previews as you type. Light/dark+ * mode is auto-detected from the background's luminance.+ */+export function CustomThemeEditor({ userBinding }: { userBinding: ConfigBinding }) {+ const { t } = useLingui();+ const { setTheme } = useTheme();+ const merged = useConfigContextOptional()?.merged ?? null;+ const committed = resolveCustomSeed(merged?.appearance?.customTheme);+ const isActive = merged?.appearance?.colorTheme === 'custom';++ // Local working copy for smooth live editing; re-sync when committed config+ // changes underneath us (another window, a reset, a hand-edit).+ const [seed, setSeed] = useState<CustomThemeSeed>(committed);+ const committedKey = JSON.stringify(committed);+ // biome-ignore lint/correctness/useExhaustiveDependencies: committedKey is the value-stable proxy for `committed`.+ useEffect(() => {+ setSeed(committed);+ }, [committedKey]);++ const labels: Record<keyof CustomThemeSeed, string> = {+ background: t`Background`,+ surface: t`Surface`,+ foreground: t`Text`,+ primary: t`Primary`,+ accent: t`Accent`,+ border: t`Border`,+ };++ function preview(next: CustomThemeSeed) {+ if (!isActive) return;+ applyColorThemeToDom('custom', next);+ setTheme(customThemeKind(next) === 'dark' ? 'dark' : 'light');+ }++ function onPick(key: keyof CustomThemeSeed, value: string) {+ const next = { ...seed, [key]: value };+ setSeed(next);+ // Only push valid hex to the live DOM preview — an invalid partial the user+ // is mid-typing shouldn't repaint the app with a broken color.+ if (isHexColor(value)) preview(next);+ }++ function commit(key: keyof CustomThemeSeed, value: string) {+ // Invalid input stays visible (with its inline error) so the user can+ // correct it — no silent revert, and nothing is written to config until the+ // value is a valid 6-digit hex.+ if (!isHexColor(value)) return;+ userBinding.patch({ appearance: { customTheme: { [key]: value } } });+ }++ function reset() {+ setSeed(DEFAULT_CUSTOM_SEED);+ preview(DEFAULT_CUSTOM_SEED);+ userBinding.patch({ appearance: { customTheme: { ...DEFAULT_CUSTOM_SEED } } });+ }++ return (+ <section+ aria-labelledby="settings-custom-theme-title"+ className="space-y-3"+ data-section="custom-theme"+ >+ <div className="flex items-center justify-between gap-2">+ <div>+ <h3 id="settings-custom-theme-title" className="font-medium text-sm">+ {t`Custom theme`}+ </h3>+ <p className="text-1sm text-muted-foreground">+ {isActive+ ? t`Edits apply live. Light or dark is chosen from the background.`+ : t`Pick “Custom” above to use this palette.`}+ </p>+ </div>+ <Button variant="ghost" size="sm" onClick={reset} className="text-muted-foreground">+ {t`Reset`}+ </Button>+ </div>++ <div className="flex items-start gap-4">+ <SeedPreview seed={seed} />+ <div className="grid flex-1 grid-cols-1 gap-2 sm:grid-cols-2">+ {FIELD_ORDER.map((key) => (+ <div key={key} className="flex items-center gap-2">+ <Input+ type="color"+ aria-label={labels[key]}+ value={seed[key]}+ onChange={(e) => onPick(key, e.target.value)}+ onBlur={(e) => commit(key, e.target.value)}+ className="h-8 w-9 shrink-0 cursor-pointer rounded-md p-1"+ />+ <div className="relative min-w-0 flex-1">+ <Label className="text-1sm text-muted-foreground">{labels[key]}</Label>+ <Input+ value={seed[key]}+ spellCheck={false}+ aria-label={t`${labels[key]} hex value`}+ aria-invalid={!isHexColor(seed[key])}+ onChange={(e) => onPick(key, e.target.value)}+ onBlur={(e) => commit(key, e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') commit(key, (e.target as HTMLInputElement).value);+ }}+ className="h-7 font-mono text-1sm uppercase"+ />+ {!isHexColor(seed[key]) ? (+ // Absolutely positioned so an invalid value doesn't reflow the+ // other color fields in the grid — every swatch stays put.+ <FieldError+ className="absolute top-full left-0 mt-0.5 text-xs leading-tight"+ data-testid={`custom-theme-hex-error-${key}`}+ >+ {t`Enter a 6-digit hex like #1A2B3C`}+ </FieldError>+ ) : null}+ </div>+ </div>+ ))}+ </div>+ </div>+ </section>+ );+}diff --git a/packages/app/src/components/settings/LintingSection.dom.test.tsx b/packages/app/src/components/settings/LintingSection.dom.test.tsxnew file mode 100644index 000000000..fc19c22c4--- /dev/null+++ b/packages/app/src/components/settings/LintingSection.dom.test.tsx@@ -0,0 +1,217 @@+/**+ * RTL mount tests for the linter Settings sections (the lint-plugin model).+ * Behavior is driven through a mocked project ConfigContext binding and asserted+ * on the exact CRDT patch payloads (per-plugin toggle) and on the native-rule+ * editor's write calls + gated visibility of controls.+ */++import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { Config, ConfigBinding } from '@inkeep/open-knowledge-core';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { TooltipProvider } from '@/components/ui/tooltip';++// Radix primitives reach for DOM globals the jsdom preload doesn't expose;+// hoist the same shims the sibling settings DOM tests use.+type WindowGlobals = { NodeFilter?: typeof NodeFilter };+type GlobalWithDomShims = typeof globalThis &+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };+const globalWithDomShims = globalThis as GlobalWithDomShims;+if (+ globalWithDomShims.NodeFilter === undefined &&+ globalWithDomShims.window?.NodeFilter !== undefined+) {+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;+}+if (globalWithDomShims.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalWithDomShims.ResizeObserver = NoopResizeObserver;+}++let mockProjectConfig: Config | null = null;+let mockProjectSynced = true;+let mockProjectBinding: ConfigBinding | null = null;++mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ userBinding: null,+ userSynced: false,+ projectBinding: mockProjectBinding,+ projectLocalBinding: null,+ okignoreBinding: null,+ okignoreSynced: false,+ userConfig: null,+ projectConfig: mockProjectConfig,+ projectSynced: mockProjectSynced,+ projectLocalConfig: null,+ projectLocalSynced: false,+ merged: null,+ }),+}));++// The markdownlint editor reads native rules via `useProjectLintConfig()` and+// writes via `writeMarkdownlintRule`. Mock the lint-config client so the panel's+// data is controllable and writes are observable. The other exports keep their+// benign jsdom behavior (fetches fail → null), matching the unmocked module.+let mockProjectLintData: unknown = null;+const writeMarkdownlintRuleCalls: Array<[string, unknown]> = [];+function projectDataWithMarkdownlintRules(+ rules: Record<string, unknown>,+ configFile?: string,+): unknown {+ return {+ ...(configFile ? { configFile } : {}),+ effective: {+ enabled: true,+ plugins: {+ markdownlint: { enabled: true, rules },+ },+ },+ };+}+mock.module('@/editor/lint-config-client', () => ({+ emitLintConfigChanged: () => {},+ subscribeToLintConfigChanged: () => () => {},+ runLintAudit: async () => null,+ useDocLintConfig: () => ({ data: null }),+ useProjectLintConfig: () => ({ data: mockProjectLintData }),+ fetchEffectiveLintConfig: async () => null,+ writeMarkdownlintRule: async (ruleId: string, value: unknown) => {+ writeMarkdownlintRuleCalls.push([ruleId, value]);+ // Match the production discriminated union so tests exercise the success+ // branch (a bare LintConfigResponse would read as ok: undefined → error path).+ return { ok: true, response: mockProjectLintData };+ },+}));++const { ProjectPluginsManageSection, UserPluginsManageSection, MarkdownlintPluginSection } =+ await import('./LintingSection');++interface SliceOverrides {+ markdownlint?: Record<string, unknown>;+}++function configWith(linter: SliceOverrides): Config {+ return {+ contentRules: {+ markdownlint: { enabled: true, ...linter.markdownlint },+ },+ } as unknown as Config;+}++function makeBinding(): { binding: ConfigBinding; calls: unknown[] } {+ const calls: unknown[] = [];+ const binding = {+ current: () => ({}),+ patch: (patch: unknown) => {+ calls.push(patch);+ return { ok: true, value: { applied: [], effective: {} } };+ },+ subscribe: () => () => {},+ } as unknown as ConfigBinding;+ return { binding, calls };+}++beforeEach(() => {+ mockProjectConfig = configWith({});+ mockProjectSynced = true;+ mockProjectBinding = null;+ mockProjectLintData = null;+ writeMarkdownlintRuleCalls.length = 0;+});++afterEach(() => {+ cleanup();+});++describe('ProjectPluginsManageSection', () => {+ test('renders the project plugin toggles and points project audits at the Problems panel', () => {+ const { binding } = makeBinding();+ mockProjectBinding = binding;+ render(<ProjectPluginsManageSection />);+ expect(screen.getByTestId('settings-plugin-toggle-markdownlint')).toBeDefined();+ // The user-scope theme toggle is NOT here — it lives in the User → Plugins page.+ expect(screen.queryByTestId('settings-plugin-toggle-theme')).toBeNull();+ // The project audit lives in the Problems panel, not Settings — no runner here.+ expect(screen.queryByTestId('settings-linting-audit')).toBeNull();+ expect(screen.getByTestId('settings-plugins-audit-pointer').textContent).toContain(+ 'Run a project audit from the Problems panel',+ );+ });++ test('toggling a project plugin writes the per-plugin enabled patch', async () => {+ const { binding, calls } = makeBinding();+ mockProjectBinding = binding;+ render(<ProjectPluginsManageSection />);+ await userEvent.click(screen.getByTestId('settings-plugin-toggle-markdownlint'));+ expect(calls).toContainEqual({+ contentRules: { markdownlint: { enabled: false } },+ });+ });++ test('disables controls until the binding is ready', () => {+ mockProjectBinding = null;+ mockProjectSynced = false;+ render(<ProjectPluginsManageSection />);+ expect(+ (screen.getByTestId('settings-plugin-toggle-markdownlint') as HTMLButtonElement).disabled,+ ).toBe(true);+ });+});++describe('UserPluginsManageSection', () => {+ test('renders only the user-scope Themes toggle, not project plugins', () => {+ const { binding } = makeBinding();+ mockProjectBinding = binding;+ render(<UserPluginsManageSection userBinding={null} />);+ expect(screen.getByTestId('settings-plugin-toggle-theme')).toBeDefined();+ expect(screen.queryByTestId('settings-plugin-toggle-markdownlint')).toBeNull();+ });++ test('the Themes toggle writes the user-scope enabled patch', async () => {+ const { binding } = makeBinding();+ mockProjectBinding = binding;+ // The theme plugin is user-scope, so it writes through the user binding.+ const { binding: userBinding, calls: userCalls } = makeBinding();+ render(<UserPluginsManageSection userBinding={userBinding} />);+ await userEvent.click(screen.getByTestId('settings-plugin-toggle-theme'));+ expect(userCalls).toContainEqual({ appearance: { colorThemeEnabled: false } });+ });+});++// Row-level browser behavior (search, filters, toggles, MD043 editor, severity+// chips) is covered in markdownlint-rule-browser.dom.test.tsx; this block pins+// the section wrapper: header + browser mount + the config-source description.+describe('MarkdownlintPluginSection', () => {+ test('renders the full-catalog rule browser', () => {+ mockProjectLintData = projectDataWithMarkdownlintRules({ default: true });+ render(+ <TooltipProvider>+ <MarkdownlintPluginSection />+ </TooltipProvider>,+ );+ expect(screen.getByTestId('settings-plugin-markdownlint')).toBeDefined();+ expect(screen.getByTestId('settings-linting-markdownlint-rules')).toBeDefined();+ expect(screen.getByTestId('markdownlint-rule-search')).toBeDefined();+ expect(screen.getByTestId('markdownlint-rule-row-MD001')).toBeDefined();+ });++ test('names the project config file in the description when one is present', () => {+ // When the project has a committed `.markdownlint.*`, the description+ // switches to a different UX context — it names the file and says it+ // governs linting — and interpolates the filename via <Trans>.+ mockProjectLintData = projectDataWithMarkdownlintRules({ MD010: false }, '.markdownlint.json');+ render(+ <TooltipProvider>+ <MarkdownlintPluginSection />+ </TooltipProvider>,+ );+ const rules = screen.getByTestId('settings-linting-markdownlint-rules');+ expect(rules.textContent).toContain('.markdownlint.json');+ expect(rules.textContent).toContain('governs linting');+ });+});diff --git a/packages/app/src/components/settings/LintingSection.tsx b/packages/app/src/components/settings/LintingSection.tsxnew file mode 100644index 000000000..b4cfde86a--- /dev/null+++ b/packages/app/src/components/settings/LintingSection.tsx@@ -0,0 +1,245 @@+/**+ * Settings → Plugins — the no-code GUI for the markdown linter, organized as+ * lint plugins. Project scope: lint rules are an authoring standard shared with+ * the team via the committed `config.yml` + the project's native+ * `.markdownlint.*` file (the source of truth for rules).+ *+ * Exported sections: `ProjectPluginsManageSection` + `UserPluginsManageSection`+ * (per-plugin on/off, one manage page per scope) and `MarkdownlintPluginSection`+ * (the full-catalog rule browser — see `markdownlint-rule-browser.tsx`).+ */+import {+ type ConfigBinding,+ type ConfigPatch,+ humanFormat,+ type LintPluginId,+} from '@inkeep/open-knowledge-core';+import { Trans, useLingui } from '@lingui/react/macro';+import { ArrowUpRight } from 'lucide-react';+import type { ReactNode } from 'react';+import { toast } from 'sonner';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';+import { useConfigContext } from '@/lib/config-provider';+import { dispatchExternalLinkClick } from '@/lib/external-link';+import { LINT_PLUGIN_META } from './lint-plugin-meta';+import { MarkdownlintRuleBrowser } from './markdownlint-rule-browser';++/** Project-scope content-rules config + a `contentRules`-patch writer. Shared by the sections. */+function useLinterConfig() {+ const { t } = useLingui();+ const { projectConfig, projectSynced, projectBinding } = useConfigContext();+ const contentRules = projectConfig?.contentRules;+ const bindingReady = projectSynced && projectBinding !== null;++ function write(patch: ConfigPatch['contentRules']): boolean {+ if (projectBinding === null) {+ toast.error(t`Content rules not yet loaded — try again in a moment`);+ return false;+ }+ const result = projectBinding.patch({ contentRules: patch });+ if (!result.ok) {+ toast.error(t`Failed to save content rules — ${humanFormat(result.error)}`);+ return false;+ }+ return true;+ }++ return { contentRules, bindingReady, write };+}++/** A `contentRules` patch toggling one plugin's `enabled` (dynamic key needs the cast). */+function pluginEnabledPatch(id: LintPluginId, enabled: boolean): ConfigPatch['contentRules'] {+ return { [id]: { enabled } } as ConfigPatch['contentRules'];+}++function PluginManageDescription({ id }: { id: LintPluginId }) {+ switch (id) {+ case 'markdownlint':+ return (+ <Trans>+ Common markdown issues — hard tabs, heading increments, list markers, and more.+ </Trans>+ );+ }+}++/**+ * Project-scope plugins management page (This project → Plugins). Toggles the+ * project's content-rule plugins on/off; the choice is committed to config.yml+ * and shared via git. Enabled plugins also appear under the Plugins sidebar+ * section with their own panel.+ */+export function ProjectPluginsManageSection() {+ const { t } = useLingui();+ const { contentRules, bindingReady, write } = useLinterConfig();++ return (+ <section+ aria-labelledby="settings-plugins-title"+ className="space-y-4"+ data-testid="settings-plugins-manage"+ >+ <div className="space-y-1">+ <h3 id="settings-plugins-title" className="text-base font-semibold">+ <Trans>Plugins</Trans>+ </h3>+ <p className="text-sm text-muted-foreground">+ <Trans>+ Project plugins are your project's authoring standard — turn them on or off here. The+ choice is committed to config.yml and shared with every collaborator via git. Each+ enabled plugin gets its own page under Plugins in the settings sidebar.+ </Trans>+ </p>+ </div>++ <div className="divide-y rounded-md border" data-testid="settings-plugins-list">+ {LINT_PLUGIN_META.map((plugin) => {+ const on = contentRules?.[plugin.id]?.enabled === true;+ return (+ <div key={plugin.id} className="flex items-center justify-between gap-3 px-3 py-2">+ <div className="min-w-0">+ <Label+ htmlFor={`settings-plugin-toggle-${plugin.id}`}+ className="text-sm font-medium"+ >+ {plugin.label}+ </Label>+ <p className="text-sm text-muted-foreground">+ <PluginManageDescription id={plugin.id} />+ </p>+ </div>+ <Switch+ id={`settings-plugin-toggle-${plugin.id}`}+ checked={on}+ disabled={!bindingReady}+ onCheckedChange={(next) => write(pluginEnabledPatch(plugin.id, next))}+ aria-label={on ? t`Disable ${plugin.label}` : t`Enable ${plugin.label}`}+ data-testid={`settings-plugin-toggle-${plugin.id}`}+ />+ </div>+ );+ })}+ </div>++ <p className="text-sm text-muted-foreground" data-testid="settings-plugins-audit-pointer">+ <Trans>Run a project audit from the Problems panel.</Trans>+ </p>+ </section>+ );+}++/**+ * User-scope plugins management page (User → Plugins). Toggles personal,+ * device-local plugins (Themes) on/off; the choice lives in your user config+ * and is never committed to the project.+ */+export function UserPluginsManageSection({ userBinding }: { userBinding: ConfigBinding | null }) {+ const { t } = useLingui();+ const { userConfig } = useConfigContext();+ // The theme plugin is user-scope (personal). Default on.+ const themeEnabled = userConfig?.appearance?.colorThemeEnabled !== false;++ return (+ <section+ aria-labelledby="settings-user-plugins-title"+ className="space-y-4"+ data-testid="settings-user-plugins-manage"+ >+ <div className="space-y-1">+ <h3 id="settings-user-plugins-title" className="text-base font-semibold">+ <Trans>Plugins</Trans>+ </h3>+ <p className="text-sm text-muted-foreground">+ <Trans>+ User plugins are personal to this device — turn them on or off here. The choice lives in+ your user config and is never committed to the project. Each enabled plugin gets its own+ page under Plugins in the settings sidebar.+ </Trans>+ </p>+ </div>++ <div className="rounded-md border p-3" data-testid="settings-user-plugins-list">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <Label htmlFor="settings-plugin-toggle-theme" className="text-sm font-medium">+ <Trans>Themes</Trans>+ </Label>+ <p className="text-sm text-muted-foreground">+ <Trans>+ A personal color-theme picker — not shared with your project. When on, it appears+ under Plugins in the sidebar.+ </Trans>+ </p>+ </div>+ <Switch+ id="settings-plugin-toggle-theme"+ checked={themeEnabled}+ disabled={userBinding === null}+ onCheckedChange={(next) => {+ if (!userBinding) return;+ const result = userBinding.patch({ appearance: { colorThemeEnabled: next } });+ if (!result.ok) toast.error(t`Failed to save theme setting`);+ }}+ aria-label={themeEnabled ? t`Disable Themes` : t`Enable Themes`}+ data-testid="settings-plugin-toggle-theme"+ />+ </div>+ </div>+ </section>+ );+}++/** Shared header for a per-plugin settings panel. */+function PluginSectionHeader({+ titleId,+ title,+ children,+}: {+ titleId: string;+ title: string;+ children: ReactNode;+}) {+ return (+ <div className="space-y-1">+ <h3 id={titleId} className="text-base font-semibold">+ {title}+ </h3>+ <p className="text-sm text-muted-foreground">{children}</p>+ </div>+ );+}++/** markdownlint plugin: the full-catalog rule browser. */+export function MarkdownlintPluginSection() {+ return (+ <section+ aria-labelledby="settings-plugin-markdownlint-title"+ className="space-y-4"+ data-testid="settings-plugin-markdownlint"+ >+ <PluginSectionHeader titleId="settings-plugin-markdownlint-title" title="markdownlint">+ <Trans>+ Flag common markdown issues in the editor. Powered by{' '}+ <a+ href="https://github.com/DavidAnson/markdownlint"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) =>+ dispatchExternalLinkClick(e, 'https://github.com/DavidAnson/markdownlint')+ }+ onAuxClick={(e) =>+ dispatchExternalLinkClick(e, 'https://github.com/DavidAnson/markdownlint')+ }+ className="inline-flex items-center gap-0.5 text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ markdownlint+ <ArrowUpRight aria-hidden className="size-3" />+ </a>+ .+ </Trans>+ </PluginSectionHeader>+ <MarkdownlintRuleBrowser />+ </section>+ );+}diff --git a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsxindex 3c6585200..516ef9c18 100644--- a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx@@ -326,3 +326,69 @@ describe('SettingsDialogBody theme toggle — optimistic apply', () => {expect(patches).toEqual([{ appearance: { theme: 'light' } }]);});});++/**+ * The color-palette picker (Settings → Plugins → Themes) optimistically flips+ * next-themes to the palette's FORCED mode, not merely "dark or nothing". A+ * light-kind built-in (Catppuccin Latte) must flip to light so the `.dark`+ * class drops in the same tick the light palette paints — otherwise Tailwind+ * `dark:` variants coexist with the light palette until the config round-trips,+ * a flash of dark-on-light. Same harness/probe rationale as the toggle tests+ * above: with no ConfigProvider effect mounted, only the optimistic+ * `setTheme(colorThemeMode(next))` path can move the probe.+ */+function renderThemePluginWithTheme(binding: ConfigBinding) {+ themeStorageKeySeq += 1;+ return render(+ <ThemeProvider+ attribute="class"+ defaultTheme="system"+ enableSystem+ storageKey={`ok-theme-v1-test-${themeStorageKeySeq}`}+ >+ <SettingsContextProvider>+ <TooltipProvider>+ <SettingsDialogBody+ activeId="plugin:theme"+ userBinding={binding}+ okignoreBinding={null}+ okignoreSynced={false}+ />+ <ThemeProbe />+ </TooltipProvider>+ </SettingsContextProvider>+ </ThemeProvider>,+ );+}++describe('SettingsDialogBody color-palette picker — optimistic mode flip', () => {+ afterEach(() => {+ cleanup();+ });++ test('selecting a light palette (Catppuccin Latte) flips next-themes to light', async () => {+ const user = userEvent.setup();+ const { binding } = makeBinding();+ renderThemePluginWithTheme(binding);++ expect(screen.getByTestId('theme-probe').textContent).toBe('system');++ await user.click(screen.getByRole('radio', { name: /Catppuccin Latte/ }));++ await waitFor(() => {+ expect(screen.getByTestId('theme-probe').textContent).toBe('light');+ });+ });++ test('selecting a dark palette (Catppuccin Frappé) flips next-themes to dark', async () => {+ const user = userEvent.setup();+ const { binding } = makeBinding();+ renderThemePluginWithTheme(binding);++ await user.click(screen.getByRole('radio', { name: /Catppuccin Frappé/ }));++ await waitFor(() => {+ expect(screen.getByTestId('theme-probe').textContent).toBe('dark');+ });+ });+});diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsxindex 2c7c2c8a5..66f6fdecb 100644--- a/packages/app/src/components/settings/SettingsDialogBody.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx@@ -93,6 +93,8 @@ import {useSyncEnabledWriter,} from '@/hooks/use-enable-sync-with-confirm';import { useGitSyncStatus } from '@/hooks/use-git-sync-status';+import { colorThemeMode, customThemeKind, resolveCustomSeed } from '@/lib/color-themes';+import { useConfigContextOptional } from '@/lib/config-context';import { useConfigContext } from '@/lib/config-provider';import { subscribeToConfigValidationRejected } from '@/lib/config-validation-events';import { useClaudeDesktopIntegration } from '@/lib/handoff/use-claude-desktop-integration';@@ -104,11 +106,16 @@ import {SHORTCUT_CATEGORY_ORDER,type ShortcutBinding,} from '@/lib/keyboard-shortcuts';+import { applyColorThemeToDom } from '@/lib/use-apply-config-color-theme';import { cn } from '@/lib/utils';import { AccountSection } from './AccountSection';import { AiToolsSection } from './AiToolsSection';+import { ColorThemePicker } from './ColorThemePicker';+import { CustomThemeEditor } from './CustomThemeEditor';import { EmbeddingsKeySection } from './EmbeddingsKeySection';import { LinkPreviewsSection } from './LinkPreviewsSection';+import { ProjectPluginsManageSection, UserPluginsManageSection } from './LintingSection';+import { LINT_PLUGIN_UI } from './lint-plugins';import { OkignoreSection } from './OkignoreSection';import { ProjectAiToolsSection } from './ProjectAiToolsSection';import { ProjectTemplatesSection } from './ProjectTemplatesSection';@@ -136,8 +143,12 @@ interface FieldDef {path: string[];label: MessageDescriptor;description?: MessageDescriptor;- /** Optional override: 'enum-toggle' renders enum as a ToggleGroup; default is select-style toggle. */- control?: 'enum-toggle';+ /**+ * Optional override: 'enum-toggle' renders enum as a ToggleGroup;+ * 'theme-tiles' renders the IDE color-palette tile picker; default is a+ * select-style toggle.+ */+ control?: 'enum-toggle' | 'theme-tiles';}const FIELDS_USER_PREFERENCES: FieldDef[] = [@@ -159,6 +170,18 @@ const FIELDS_USER_PREFERENCES: FieldDef[] = [},];+// The color-theme picker is a theme "plugin": it lives in the Plugins menu+// (Settings → Plugins → Themes) as a peer of the lint plugins, not in+// Preferences. `appearance.theme` (light/dark/system) stays in Preferences.+const FIELDS_THEME_PLUGIN: FieldDef[] = [+ {+ path: ['appearance', 'colorTheme'],+ label: msg`Color theme`,+ description: msg`Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences.`,+ control: 'theme-tiles',+ },+];+// The selected committed-default option uses the app's primary blue (the same// token as the Button default variant), not the muted ToggleGroup default, so// the active stance reads as clearly chosen and matches the accent used@@ -226,6 +249,29 @@ export function SettingsDialogBody({// binding from ConfigContext (like SyncSection) — no prop threading.return <SearchSection />;}+ if (activeId === 'plugins-manage') {+ // Project-scope plugins management (This project → Plugins): toggle the+ // project's content-rule plugins + the audit pointer.+ return <ProjectPluginsManageSection />;+ }+ if (activeId === 'user-plugins-manage') {+ // User-scope plugins management (User → Plugins): toggle personal plugins+ // (Themes) via the user-scope binding.+ return <UserPluginsManageSection userBinding={userBinding} />;+ }+ if (activeId === 'plugin:theme') {+ // The theme "plugin" — a peer of the lint plugins in the Plugins menu, not a+ // lint plugin (it owns no `contentRules` slice). Its config is user-scope.+ return userBinding ? <ThemePluginSection userBinding={userBinding} /> : <SectionSkeleton />;+ }+ if (activeId.startsWith('plugin:')) {+ // One enabled lint plugin's settings panel.+ const pluginId = activeId.slice('plugin:'.length);+ const plugin = LINT_PLUGIN_UI.find((p) => p.id === pluginId);+ if (!plugin) return null;+ const PluginSection = plugin.Section;+ return <PluginSection key={activeId} />;+ }if (activeId === 'link-previews') {// Project-local external-link-preview egress opt-in. Reads its own// project-local binding from ConfigContext, same as SearchSection. The@@ -489,6 +535,28 @@ function BoundSchemaSection({);}+/**+ * The theme "plugin" panel — the color-palette picker + custom-theme editor,+ * rendered in the Plugins menu (Settings → Plugins → Themes) as a peer of the+ * lint plugins. Reuses the same user-scope config-form machinery the Preferences+ * pane uses.+ */+function ThemePluginSection({ userBinding }: { userBinding: ConfigBinding }) {+ const { t } = useLingui();+ return (+ <div className="space-y-6">+ <BoundSchemaSection+ title={t`Themes`}+ description={t`Pick a built-in IDE color palette, or define your own.`}+ scope="user"+ binding={userBinding}+ fields={FIELDS_THEME_PLUGIN}+ />+ <CustomThemeEditor userBinding={userBinding} />+ </div>+ );+}+interface SchemaSectionProps {title: string;description: string;@@ -1213,7 +1281,7 @@ function SettingsField({ field, scope, commitField, isFlashed }: SettingsFieldPronCommit={runCommitIfDirty}/></FormControl>- <SavedIndicator visible={savedTick} />+ <SavedIndicator visible={savedTick} srOnly={field.control === 'theme-tiles'} /></div><FormMessage data-field-error={field.path.join('.')} /></FormItem>@@ -1267,6 +1335,39 @@ function FieldControlBody({// mounts one in `main.tsx`. The actual flip is gated to the theme field in// the enum-toggle branch below, so non-theme controls are unaffected.const { setTheme } = useTheme();+ // Optional: the theme-tiles control reads the custom-theme seed from config,+ // but FieldControlBody also renders in provider-less unit harnesses.+ const merged = useConfigContextOptional()?.merged ?? null;+ if (field.control === 'theme-tiles') {+ const { id: forwardedId, ...wrapperSlotProps } = slotForwarded;+ const customSeed = merged?.appearance?.customTheme;+ return (+ <ColorThemePicker+ {...wrapperSlotProps}+ id={forwardedId}+ value={typeof ctl.value === 'string' ? ctl.value : 'default'}+ customSeed={customSeed}+ aria-label={t(field.label)}+ onSelect={(next) => {+ // Optimistic apply: paint the palette overlay synchronously and flip+ // next-themes to the palette's forced mode so `dark:` variants land+ // immediately. A built-in palette forces light (Catppuccin Latte) or+ // dark; `custom` follows its seed. `default` is system-kind, so+ // `colorThemeMode` returns undefined — no flip, and the ConfigProvider+ // effect restores the user's saved light/dark mode on the round-trip.+ applyColorThemeToDom(next, customSeed);+ if (next === 'custom') {+ setTheme(customThemeKind(resolveCustomSeed(customSeed)) === 'dark' ? 'dark' : 'light');+ } else {+ const mode = colorThemeMode(next);+ if (mode) setTheme(mode);+ }+ ctl.onChange(next);+ onCommit();+ }}+ />+ );+ }if (typeTag === 'boolean') {return (<Switch@@ -1492,17 +1593,21 @@ function StringArrayControlBody({);}-function SavedIndicator({ visible }: { visible: boolean }) {+function SavedIndicator({ visible, srOnly = false }: { visible: boolean; srOnly?: boolean }) {// Live region — auto-save replaces an explicit Save button, so this// checkmark IS the save confirmation. Polite announcement so screen// readers say "Saved" without interrupting other speech (WCAG 4.1.3).// Always render the wrapper so the SR-only text node is present at// mount time; the visible checkmark is the only thing that toggles.+ // `srOnly` keeps the announcement but never paints the checkmark — for+ // controls whose committed value is already visually self-evident (the+ // theme tiles repaint the whole app) and whose full-width layout the+ // appearing icon would momentarily compress.return (<span role="status" aria-live="polite" className="text-emerald-600">{visible ? (<>- <Check aria-hidden="true" className="size-3.5" />+ {srOnly ? null : <Check aria-hidden="true" className="size-3.5" />}<span className="sr-only"><Trans>Saved</Trans></span>diff --git a/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsxindex bf661dd1d..669816987 100644--- a/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx@@ -87,6 +87,9 @@ let mockCollabUrl: string | null = 'ws://test.invalid';let mockDesktopPresent = false;let mockBodyMode: BodyMode = 'probe';let mockShowInstallSkill = true;+// markdownlint is opt-in (off by default); the default mock represents a+// project that has enabled it, so the Plugins group lists its panel.+let mockProjectConfig: unknown = { contentRules: { markdownlint: { enabled: true } } };mock.module('@inkeep/open-knowledge-core', () => ({get SHOW_INSTALL_SKILL() {@@ -117,7 +120,7 @@ mock.module('@/lib/config-provider', () => ({okignoreBinding: mockOkignoreBinding,okignoreSynced: mockOkignoreSynced,userConfig: null,- projectConfig: null,+ projectConfig: mockProjectConfig,projectLocalConfig: null,projectLocalSynced: false,merged: null,@@ -159,6 +162,7 @@ describe('SettingsDialogShell userBinding gating (Tier-3 mount)', () => {mockDesktopPresent = false;mockBodyMode = 'probe';mockShowInstallSkill = true;+ mockProjectConfig = { contentRules: { markdownlint: { enabled: true } } };consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});});@@ -238,7 +242,28 @@ describe('SettingsDialogShell userBinding gating (Tier-3 mount)', () => {expect(sync.disabled).toBe(true);expect(sync.getAttribute('aria-disabled')).toBe('true');expect(sync.getAttribute('aria-describedby')).toBe('settings-group-project-caption');- expect(screen.getByText('Open a project to edit.')).toBeTruthy();+ // The project group gates on a loaded project (its caption renders); the+ // Plugins group no longer gates — the user-scope theme plugin keeps it shown.+ expect(screen.getAllByText('Open a project to edit.').length).toBeGreaterThan(0);+ });++ test('the Plugins group always lists the theme plugin, even with no project', () => {+ mockCollabUrl = null;+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);+ // Themes is user-scope (no project required), so its panel shows in the+ // Plugins group even when the project-scope items are gated.+ expect(screen.getByTestId('settings-sidebar-item-plugin:theme')).toBeTruthy();+ expect(screen.getByText('Themes')).toBeTruthy();+ });++ test('has a per-scope Plugins manage item under both User and This project', () => {+ // Default mock has a project (mockCollabUrl set) with markdownlint enabled.+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);+ // Two manage entries — one per scope — plus the shared Plugins panel group.+ expect(screen.getByTestId('settings-sidebar-item-user-plugins-manage')).toBeTruthy();+ expect(screen.getByTestId('settings-sidebar-item-plugins-manage')).toBeTruthy();+ expect(screen.getByTestId('settings-sidebar-item-plugin:markdownlint')).toBeTruthy();+ expect(screen.getByTestId('settings-sidebar-item-plugin:theme')).toBeTruthy();});test('hides or shows the Integrations group from desktop availability', () => {diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsxindex 21f67d1ac..4ce5dfeca 100644--- a/packages/app/src/components/settings/SettingsDialogShell.tsx+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx@@ -19,11 +19,12 @@* the body chunk is cached after the first open.** Sidebar IA:- * USER → Preferences, Hotkeys, Account, AI tools & CLI (Electron- * host only)- * THIS PROJECT → Sync, Search, Link previews (hidden on the packaged- * file:// renderer), Templates, Ignore patterns, Config- * sharing+ * USER → Preferences, Hotkeys, Account, Plugins (user-scope manage),+ * AI tools & CLI (Electron host only)+ * THIS PROJECT → Sync, Search, Plugins (project-scope manage), Link previews+ * (hidden on the packaged file:// renderer), Templates, Ignore+ * patterns, Config sharing+ * PLUGINS → one panel per enabled plugin (project + user, side by side)* INTEGRATIONS → Claude Desktop (hidden when desktopPresent === false)*/@@ -40,6 +41,7 @@ import { useConfigContext } from '@/lib/config-provider';import { isFileProtocolPage } from '@/lib/file-protocol-page';import { useClaudeDesktopIntegration } from '@/lib/handoff/use-claude-desktop-integration';import { cn } from '@/lib/utils';+import { LINT_PLUGIN_META } from './lint-plugin-meta';/*** GitHub Releases tag URL — mirrors `releaseUrlFor` in the desktop main@@ -59,7 +61,7 @@ interface SidebarItem {}interface SidebarGroup {- id: 'user' | 'project' | 'integrations';+ id: 'user' | 'project' | 'plugins' | 'integrations';label: string;/*** `false` renders the group disabled (no-project state for THIS@@ -78,7 +80,8 @@ interface SettingsDialogShellProps {export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellProps) {const { t } = useLingui();const { collabUrl } = useDocumentContext();- const { userBinding, userSynced, okignoreBinding, okignoreSynced } = useConfigContext();+ const { userBinding, userSynced, okignoreBinding, okignoreSynced, projectConfig, merged } =+ useConfigContext();const { desktopPresent } = useClaudeDesktopIntegration();// Always default to USER → Preferences on each fresh open. No@@ -100,6 +103,18 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP// its per-project revoke toggle only appears under the Electron preload.const isOkDesktopHost = typeof window !== 'undefined' && window.okDesktop != null;+ // One sidebar item per ENABLED project-scope plugin. These populate the+ // "Project plugins" sidebar group; the manage page (which toggles membership)+ // lives under "This project".+ const enabledPluginItems: SidebarItem[] = LINT_PLUGIN_META.filter(+ (p) => projectConfig?.contentRules?.[p.id]?.enabled === true,+ ).map((p) => ({ id: `plugin:${p.id}`, label: p.label }));++ // The theme is a user-scope plugin, toggled on the Plugins-manage page+ // (`appearance.colorThemeEnabled`, default on). When off it drops out of the+ // "User plugins" sidebar group.+ const themeEnabled = merged?.appearance?.colorThemeEnabled !== false;+// The packaged desktop renderer loads over file:// (desktop main's// loadFile), so its POST /api/link-preview requests carry Origin: null,// which the route's anti-proxy gate rejects by design (see@@ -120,6 +135,8 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP{ id: 'preferences', label: t`Preferences` },{ id: 'hotkeys', label: t`Hotkeys` },{ id: 'account', label: t`Account` },+ // User-scope plugin management (toggle personal plugins like Themes).+ { id: 'user-plugins-manage', label: t`Plugins` },// Machine-level OK footprint (per-editor MCP entries, Agent Skills,// the ok PATH command) — user-scoped, and desktop-only because the// install actors live in the Electron main process.@@ -133,6 +150,7 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellPitems: [{ id: 'sync', label: t`Sync` },{ id: 'search', label: t`Search` },+ { id: 'plugins-manage', label: t`Plugins` },...(isFileProtocolRenderer ? [] : [{ id: 'link-previews', label: t`Link previews` }]),...(isOkDesktopHost ? [{ id: 'terminal', label: t`Terminal` }] : []),// Per-project MCP wiring + runtime skill — desktop-only because the@@ -144,6 +162,19 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP{ id: 'sharing', label: t`Config sharing` },],},+ // Dedicated group listing every ENABLED plugin's own panel — project-scope+ // lint plugins (shown when a project is open) and the user-scope theme+ // plugin, side by side. Membership is toggled on the per-scope Plugins+ // manage pages (User → Plugins, This project → Plugins).+ {+ id: 'plugins',+ label: t`Plugins`,+ enabled: true,+ items: [+ ...(hasProject ? enabledPluginItems : []),+ ...(themeEnabled ? [{ id: 'plugin:theme', label: t`Themes` }] : []),+ ],+ },{id: 'integrations',label: t`Integrations`,diff --git a/packages/app/src/components/settings/lint-plugin-meta.test.ts b/packages/app/src/components/settings/lint-plugin-meta.test.tsnew file mode 100644index 000000000..b626763f2--- /dev/null+++ b/packages/app/src/components/settings/lint-plugin-meta.test.ts@@ -0,0 +1,27 @@+/**+ * Drift guard: the settings sidebar list (`LINT_PLUGIN_META`) must cover exactly+ * the lint plugin registry. The list is hand-authored (kept free of heavy core+ * imports so the settings shell stays light — deriving it from LINT_PLUGINS would+ * pull the lint engines into the shell bundle), so a forgotten entry would+ * silently drop a plugin's panel from the sidebar. The id→Section map in+ * `lint-plugins.tsx` is already compile-time complete (`Record<LintPluginId>`);+ * this covers the remaining array.+ */++import { describe, expect, test } from 'bun:test';+import { LINT_PLUGINS } from '@inkeep/open-knowledge-core';+import { LINT_PLUGIN_META } from './lint-plugin-meta.ts';++describe('LINT_PLUGIN_META ⟷ plugin registry', () => {+ test('covers exactly the registered plugin ids (settings list stays in sync)', () => {+ expect(LINT_PLUGIN_META.map((meta) => meta.id).sort()).toEqual(+ LINT_PLUGINS.map((plugin) => plugin.id).sort(),+ );+ });++ test('every entry has a non-empty label', () => {+ for (const meta of LINT_PLUGIN_META) {+ expect(meta.label.length).toBeGreaterThan(0);+ }+ });+});diff --git a/packages/app/src/components/settings/lint-plugin-meta.ts b/packages/app/src/components/settings/lint-plugin-meta.tsnew file mode 100644index 000000000..709117892--- /dev/null+++ b/packages/app/src/components/settings/lint-plugin-meta.ts@@ -0,0 +1,16 @@+/**+ * Lightweight lint-plugin metadata (id + label), the single source of truth for+ * the plugin list. Kept free of React + section-component imports so the+ * settings SHELL can build its sidebar from it without eagerly pulling the heavy+ * per-plugin panels (and their core/editor deps) into its module graph — the+ * full id→Section registry lives in `lint-plugins.tsx`, imported by the body.+ */+import type { LintPluginId } from '@inkeep/open-knowledge-core';++export interface LintPluginMeta {+ id: LintPluginId;+ /** Sidebar + panel-header label (brand names — intentionally not translated). */+ label: string;+}++export const LINT_PLUGIN_META: LintPluginMeta[] = [{ id: 'markdownlint', label: 'markdownlint' }];diff --git a/packages/app/src/components/settings/lint-plugins.tsx b/packages/app/src/components/settings/lint-plugins.tsxnew file mode 100644index 000000000..8d8daa57d--- /dev/null+++ b/packages/app/src/components/settings/lint-plugins.tsx@@ -0,0 +1,25 @@+/**+ * App-side lint-plugin registry: id → display label → settings panel. The body+ * dispatches `plugin:<id>` to the right panel via this. The id+label come from+ * the lightweight `LINT_PLUGIN_META` (shared with the sidebar); this module adds+ * the Section components, so importing it eagerly pulls the panels in. Adding a+ * future plugin's GUI = one `LINT_PLUGIN_META` entry + its Section in the map.+ */+import type { ReactNode } from 'react';+import { MarkdownlintPluginSection } from './LintingSection';+import { LINT_PLUGIN_META, type LintPluginMeta } from './lint-plugin-meta';++type PluginSection = () => ReactNode;++const SECTIONS: Record<LintPluginMeta['id'], PluginSection> = {+ markdownlint: MarkdownlintPluginSection,+};++export interface LintPluginUi extends LintPluginMeta {+ Section: PluginSection;+}++export const LINT_PLUGIN_UI: LintPluginUi[] = LINT_PLUGIN_META.map((meta) => ({+ ...meta,+ Section: SECTIONS[meta.id],+}));diff --git a/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsx b/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsxnew file mode 100644index 000000000..5cff28019--- /dev/null+++ b/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsx@@ -0,0 +1,407 @@+/**+ * RTL mount tests for the full-catalog markdownlint rule browser: every+ * generated-catalog rule renders grouped by display category; row state+ * derives from the resolved governing config (alias-aware, case-insensitive,+ * last-matching-key-wins entry, else `default`, else on — the engine's own+ * resolution order); search and the only-modified filter narrow the list+ * client-side; toggles,+ * resets, and expanded-row option edits write through the lint-config client.+ */++import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import {+ DEFAULT_MARKDOWNLINT_CONFIG,+ MARKDOWNLINT_RULE_CATALOG,+} from '@inkeep/open-knowledge-core';+import { cleanup, render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { TooltipProvider } from '@/components/ui/tooltip';++// Radix primitives reach for DOM globals the jsdom preload doesn't expose;+// hoist the same shims the sibling settings DOM tests use.+type WindowGlobals = { NodeFilter?: typeof NodeFilter };+type GlobalWithDomShims = typeof globalThis &+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };+const globalWithDomShims = globalThis as GlobalWithDomShims;+if (+ globalWithDomShims.NodeFilter === undefined &&+ globalWithDomShims.window?.NodeFilter !== undefined+) {+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;+}+if (globalWithDomShims.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalWithDomShims.ResizeObserver = NoopResizeObserver;+}++let mockProjectLintData: unknown = null;+const writeCalls: Array<[string, unknown]> = [];+// Default write outcome; a test overrides this to exercise the failure toast.+let mockWriteResult: { ok: boolean; errorDetail?: string; response?: unknown } | null = null;+const toastErrors: string[] = [];++function lintData(rules: Record<string, unknown>, configFile?: string): unknown {+ return {+ ...(configFile ? { configFile } : {}),+ effective: {+ enabled: true,+ plugins: {+ markdownlint: { enabled: true, rules },+ },+ },+ };+}++mock.module('@/editor/lint-config-client', () => ({+ emitLintConfigChanged: () => {},+ subscribeToLintConfigChanged: () => () => {},+ runLintAudit: async () => null,+ useDocLintConfig: () => ({ data: null }),+ useProjectLintConfig: () => ({ data: mockProjectLintData }),+ fetchEffectiveLintConfig: async () => null,+ writeMarkdownlintRule: async (ruleId: string, value: unknown) => {+ writeCalls.push([ruleId, value]);+ return mockWriteResult ?? { ok: true, response: mockProjectLintData };+ },+}));++mock.module('sonner', () => ({+ toast: {+ error: (msg: string) => {+ toastErrors.push(msg);+ },+ success: () => {},+ },+}));++const { MarkdownlintRuleBrowser } = await import('./markdownlint-rule-browser');++function renderBrowser() {+ return render(+ <TooltipProvider>+ <MarkdownlintRuleBrowser />+ </TooltipProvider>,+ );+}++function ruleRows(): HTMLElement[] {+ return screen.queryAllByTestId(/^markdownlint-rule-row-/);+}++beforeEach(() => {+ mockProjectLintData = lintData({ ...DEFAULT_MARKDOWNLINT_CONFIG });+ writeCalls.length = 0;+ mockWriteResult = null;+ toastErrors.length = 0;+});++afterEach(() => {+ cleanup();+});++describe('MarkdownlintRuleBrowser — no-file disclaimer', () => {+ test('shows the create-file disclaimer only when no config file governs', () => {+ // Default mock has no configFile → no-file state.+ renderBrowser();+ expect(screen.getByTestId('markdownlint-no-file-disclaimer')).toBeDefined();+ cleanup();++ mockProjectLintData = lintData({ default: true }, '.markdownlint.json');+ renderBrowser();+ expect(screen.queryByTestId('markdownlint-no-file-disclaimer')).toBeNull();+ });+});++describe('MarkdownlintRuleBrowser — full-catalog listing', () => {+ test('renders every generated-catalog rule grouped into category sections', () => {+ renderBrowser();+ expect(ruleRows().length).toBe(MARKDOWNLINT_RULE_CATALOG.length);+ for (const slug of ['headings', 'lists', 'whitespace', 'code', 'links-images', 'style']) {+ expect(screen.getByTestId(`markdownlint-rule-category-${slug}`)).toBeDefined();+ }+ });++ test('row state follows rules[id] ?? default ?? true; tuned defaults are not Modified', () => {+ renderBrowser();+ // MD013 is in OK's tuned disable list; MD001 falls back to `default: true`.+ expect(screen.getByTestId('markdownlint-rule-toggle-MD013').getAttribute('aria-checked')).toBe(+ 'false',+ );+ expect(screen.getByTestId('markdownlint-rule-toggle-MD001').getAttribute('aria-checked')).toBe(+ 'true',+ );+ // No governing file → the resolved keys are OK defaults, not user overrides.+ expect(screen.queryAllByTestId(/^markdownlint-rule-modified-/).length).toBe(0);+ });++ test('a config default:false turns non-overridden rows off', () => {+ mockProjectLintData = lintData({ default: false, MD010: true }, '.markdownlint.json');+ renderBrowser();+ expect(screen.getByTestId('markdownlint-rule-toggle-MD001').getAttribute('aria-checked')).toBe(+ 'false',+ );+ expect(screen.getByTestId('markdownlint-rule-toggle-MD010').getAttribute('aria-checked')).toBe(+ 'true',+ );+ });++ test('keys set by the governing file render the Modified badge', () => {+ mockProjectLintData = lintData({ default: true, MD001: false }, '.markdownlint.json');+ renderBrowser();+ expect(screen.getByTestId('markdownlint-rule-modified-MD001')).toBeDefined();+ expect(screen.queryByTestId('markdownlint-rule-modified-MD003')).toBeNull();+ });+});++describe('MarkdownlintRuleBrowser — alias-keyed config entries', () => {+ test('an alias-keyed entry governs its rule row and reads as Modified', () => {+ mockProjectLintData = lintData({ default: true, 'line-length': false }, '.markdownlint.json');+ renderBrowser();+ expect(screen.getByTestId('markdownlint-rule-toggle-MD013').getAttribute('aria-checked')).toBe(+ 'false',+ );+ expect(screen.getByTestId('markdownlint-rule-modified-MD013')).toBeDefined();+ });++ test('config keys match case-insensitively, like the engine', () => {+ mockProjectLintData = lintData({ default: true, 'LINE-LENGTH': false }, '.markdownlint.json');+ renderBrowser();+ expect(screen.getByTestId('markdownlint-rule-toggle-MD013').getAttribute('aria-checked')).toBe(+ 'false',+ );+ expect(screen.getByTestId('markdownlint-rule-modified-MD013')).toBeDefined();+ });++ test('when id and alias both address a rule, the last key wins', () => {+ mockProjectLintData = lintData(+ { default: true, MD013: false, 'line-length': true },+ '.markdownlint.json',+ );+ renderBrowser();+ expect(screen.getByTestId('markdownlint-rule-toggle-MD013').getAttribute('aria-checked')).toBe(+ 'true',+ );+ expect(screen.getByTestId('markdownlint-rule-modified-MD013')).toBeDefined();+ });++ test('the only-modified filter includes alias-keyed rules', async () => {+ mockProjectLintData = lintData({ default: true, 'line-length': false }, '.markdownlint.json');+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-only-modified'));+ expect(ruleRows().map((row) => row.getAttribute('data-testid'))).toEqual([+ 'markdownlint-rule-row-MD013',+ ]);+ });+});++describe('MarkdownlintRuleBrowser — search and only-modified', () => {+ test('search narrows by id, alias, and name; empty sections disappear', async () => {+ renderBrowser();+ const search = screen.getByTestId('markdownlint-rule-search');++ await userEvent.type(search, 'single-title');+ expect(ruleRows().map((row) => row.getAttribute('data-testid'))).toEqual([+ 'markdownlint-rule-row-MD025',+ ]);+ // MD025 is a Headings rule — the other category sections are gone.+ expect(screen.queryByTestId('markdownlint-rule-category-style')).toBeNull();++ await userEvent.clear(search);+ await userEvent.type(search, 'md013');+ expect(screen.getByTestId('markdownlint-rule-row-MD013')).toBeDefined();+ expect(screen.queryByTestId('markdownlint-rule-row-MD025')).toBeNull();+ });++ test('a query matching nothing shows the filtered empty state', async () => {+ renderBrowser();+ await userEvent.type(screen.getByTestId('markdownlint-rule-search'), 'zzz-no-such-rule');+ expect(ruleRows().length).toBe(0);+ expect(screen.getByTestId('markdownlint-rule-browser-empty')).toBeDefined();+ });++ test('only-modified shows exactly the file-set rules, never meta-keys', async () => {+ mockProjectLintData = lintData(+ { default: true, MD001: false, MD010: 'error' },+ '.markdownlint.json',+ );+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-only-modified'));+ expect(+ ruleRows()+ .map((row) => row.getAttribute('data-testid'))+ .sort(),+ ).toEqual(['markdownlint-rule-row-MD001', 'markdownlint-rule-row-MD010']);+ });++ test('only-modified with no governing file shows the empty state', async () => {+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-only-modified'));+ expect(ruleRows().length).toBe(0);+ expect(screen.getByTestId('markdownlint-rule-browser-empty')).toBeDefined();+ });+});++describe('MarkdownlintRuleBrowser — writes', () => {+ test('toggling a default-on rule absent from the file writes a bare boolean off', async () => {+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-toggle-MD001'));+ expect(writeCalls).toContainEqual(['MD001', false]);+ });++ test('toggling preserves an option-carrying value via enabled:false', async () => {+ mockProjectLintData = lintData(+ { default: true, MD013: { line_length: 100 } },+ '.markdownlint.json',+ );+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-toggle-MD013'));+ expect(writeCalls).toContainEqual(['MD013', { line_length: 100, enabled: false }]);+ });++ test('reset clears a modified rule back to the default', async () => {+ mockProjectLintData = lintData({ default: true, MD001: false }, '.markdownlint.json');+ renderBrowser();+ await userEvent.click(screen.getByLabelText('Reset MD001 to default'));+ expect(writeCalls).toContainEqual(['MD001', null]);+ });++ test('a declined write surfaces the server detail as an error toast', async () => {+ mockWriteResult = {+ ok: false,+ errorDetail: 'The native markdownlint config (.markdownlint.cjs) cannot be rewritten',+ };+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-toggle-MD001'));+ expect(toastErrors).toContainEqual(+ 'The native markdownlint config (.markdownlint.cjs) cannot be rewritten',+ );+ });++ // Regression: the toggle must keep its own `data-state`, not inherit the+ // wrapping tooltip's open/closed state. When the tooltip trigger clobbers it,+ // `data-checked:bg-primary` stops matching and an on rule renders invisibly.+ test('an on rule keeps data-state=checked (tooltip does not clobber the switch)', () => {+ renderBrowser();+ const onToggle = screen.getByTestId('markdownlint-rule-toggle-MD001');+ expect(onToggle.getAttribute('data-state')).toBe('checked');+ });++ test('an off rule keeps data-state=unchecked', () => {+ mockProjectLintData = lintData({ default: true, MD001: false }, '.markdownlint.json');+ renderBrowser();+ const offToggle = screen.getByTestId('markdownlint-rule-toggle-MD001');+ expect(offToggle.getAttribute('data-state')).toBe('unchecked');+ });+});++describe('MarkdownlintRuleBrowser — expanded-row option editing', () => {+ test('expanding a row reveals the doc link and typed option fields with effective values', async () => {+ mockProjectLintData = lintData(+ { default: true, MD013: { line_length: 120 } },+ '.markdownlint.json',+ );+ renderBrowser();+ // Collapsed rows keep their option editors out of the DOM.+ expect(screen.queryByLabelText('line_length')).toBeNull();++ await userEvent.click(screen.getByTestId('markdownlint-rule-expand-MD013'));+ const md013 = MARKDOWNLINT_RULE_CATALOG.find((rule) => rule.id === 'MD013');+ if (md013 === undefined) throw new Error('MD013 missing from the generated catalog');+ const docLink = screen.getByRole('link', {+ name: 'Documentation for MD013 (opens in browser)',+ });+ expect(docLink.getAttribute('href')).toBe(md013.docUrl);+ // The file's value backs the field; unset options fall back to defaults.+ expect((screen.getByLabelText('line_length') as HTMLInputElement).value).toBe('120');+ expect(screen.getByLabelText('code_blocks').getAttribute('aria-checked')).toBe('true');+ });++ test('the MDxxx · alias identifier lives in the expanded detail, not the collapsed row', async () => {+ mockProjectLintData = lintData({ default: true }, '.markdownlint.json');+ renderBrowser();+ // Collapsed: the row shows only the rule name; the identifier is hidden to+ // keep the row uncrowded (CollapsibleContent is unmounted while closed).+ expect(screen.queryByText('MD013 · line-length')).toBeNull();++ await userEvent.click(screen.getByTestId('markdownlint-rule-expand-MD013'));+ // Expanded: the id · alias appears in the detail alongside the doc link.+ expect(screen.getByText('MD013 · line-length')).toBeDefined();+ });++ test('editing one option writes the composed full value, preserving sibling keys', async () => {+ mockProjectLintData = lintData(+ { default: true, MD013: { line_length: 120, code_blocks: false, unknown_key: 'x' } },+ '.markdownlint.json',+ );+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-expand-MD013'));+ const field = screen.getByLabelText('line_length') as HTMLInputElement;+ await userEvent.clear(field);+ await userEvent.type(field, '100');+ await userEvent.tab();+ expect(writeCalls).toContainEqual([+ 'MD013',+ { line_length: 100, code_blocks: false, unknown_key: 'x' },+ ]);+ });++ test('MD043 headings are editable through the generic string-array field', async () => {+ mockProjectLintData = lintData(+ { default: true, MD043: { headings: ['## Summary'] } },+ '.markdownlint.json',+ );+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-expand-MD043'));+ const input = screen.getByLabelText('headings') as HTMLInputElement;+ await userEvent.type(input, '## Details{enter}');+ expect(writeCalls).toContainEqual(['MD043', { headings: ['## Summary', '## Details'] }]);+ });++ test('a rule with no options still expands to its doc link', async () => {+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-expand-MD045'));+ expect(+ screen.getByRole('link', { name: 'Documentation for MD045 (opens in browser)' }),+ ).toBeDefined();+ expect(screen.queryAllByTestId(/^rule-option-MD045-/).length).toBe(0);+ });+});++describe('MarkdownlintRuleBrowser — severity strings and disclosure', () => {+ test('a severity-string value renders enabled + Modified with a read-only chip', () => {+ mockProjectLintData = lintData({ default: true, MD010: 'error' }, '.markdownlint.json');+ renderBrowser();+ const row = screen.getByTestId('markdownlint-rule-row-MD010');+ expect(+ within(row).getByTestId('markdownlint-rule-toggle-MD010').getAttribute('aria-checked'),+ ).toBe('true');+ expect(within(row).getByTestId('markdownlint-rule-severity-MD010').textContent).toBe('error');+ expect(within(row).getByTestId('markdownlint-rule-modified-MD010')).toBeDefined();+ // No chip on rows without a severity-string value.+ expect(screen.queryByTestId('markdownlint-rule-severity-MD001')).toBeNull();+ });++ test('toggling a severity-string rule replaces it with a bare boolean', async () => {+ mockProjectLintData = lintData({ default: true, MD010: 'warning' }, '.markdownlint.json');+ renderBrowser();+ await userEvent.click(screen.getByTestId('markdownlint-rule-toggle-MD010'));+ expect(writeCalls).toContainEqual(['MD010', false]);+ });++ test('the toggle carries an accessible label and shows no hover tooltip', async () => {+ mockProjectLintData = lintData({ default: true, MD010: 'error' }, '.markdownlint.json');+ renderBrowser();+ const toggle = screen.getByTestId('markdownlint-rule-toggle-MD010');+ // The on/off control names itself via aria-label — it lost the visible Label+ // when the rule name became the disclosure trigger.+ expect(toggle.getAttribute('aria-label')).toBeTruthy();+ // The old "Edits replace this rule's entire value…" tooltip was removed.+ await userEvent.hover(toggle);+ await Promise.resolve();+ expect(screen.queryByRole('tooltip')).toBeNull();+ });+});diff --git a/packages/app/src/components/settings/markdownlint-rule-browser.tsx b/packages/app/src/components/settings/markdownlint-rule-browser.tsxnew file mode 100644index 000000000..1d55fc844--- /dev/null+++ b/packages/app/src/components/settings/markdownlint-rule-browser.tsx@@ -0,0 +1,476 @@+/**+ * Full-catalog markdownlint rule browser (Settings → Plugins → markdownlint).+ * Renders every rule in the generated catalog — not just the keys the native+ * file sets — grouped by display category, with client-side search and a+ * modified-only filter, so rules that run by default are visible and+ * toggleable. Expanding a row reveals the rule's doc link and its typed+ * option editors (`rule-option-field`), driven entirely by the generated+ * catalog's option specs. Single-rule edits write back to the project's+ * native `.markdownlint.*` file (format-preserving row-replace) via the+ * markdownlint-config endpoint.+ */+import {+ displayCategoryForRule,+ findRuleConfigEntry,+ MARKDOWNLINT_RULE_CATALOG,+ type MarkdownlintRuleSetting,+ type MarkdownlintRuleSeverity,+ type MarkdownlintRuleWriteValue,+ RULE_DISPLAY_CATEGORIES,+ type RuleCatalogEntry,+ type RuleDisplayCategory,+} from '@inkeep/open-knowledge-core';+import { Plural, Trans, useLingui } from '@lingui/react/macro';+import { ArrowUpRight, ChevronRight, Info, RotateCcw } from 'lucide-react';+import { useState } from 'react';+import { toast } from 'sonner';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Skeleton } from '@/components/ui/skeleton';+import { Switch } from '@/components/ui/switch';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import {+ emitLintConfigChanged,+ useProjectLintConfig,+ writeMarkdownlintRule,+} from '@/editor/lint-config-client';+import { dispatchExternalLinkClick } from '@/lib/external-link';+import { RuleOptionField, type RuleOptionValue } from './rule-option-field';++type RuleValues = Record<string, MarkdownlintRuleSetting>;++export function MarkdownlintRuleBrowser() {+ const { t } = useLingui();+ const { data } = useProjectLintConfig();+ const ready = data !== null;+ const rules: RuleValues = data?.effective.plugins.markdownlint.rules ?? {};+ const configFile = data?.configFile ?? null;+ const [search, setSearch] = useState('');+ const [onlyModified, setOnlyModified] = useState(false);+ const [collapsed, setCollapsed] = useState<readonly RuleDisplayCategory[]>([]);++ function setRule(ruleId: string, value: MarkdownlintRuleWriteValue | null) {+ void writeMarkdownlintRule(ruleId, value).then((res) => {+ if (!res.ok) {+ toast.error(res.errorDetail ?? t`Failed to update markdownlint rules`);+ return;+ }+ // Refresh this panel + re-lint open editors.+ emitLintConfigChanged();+ });+ }++ const filtersActive = search.trim() !== '' || onlyModified;+ const visible = MARKDOWNLINT_RULE_CATALOG.filter(+ (rule) =>+ ruleMatchesSearch(rule, search) &&+ (!onlyModified || isRuleModified(rules, configFile, rule.id)),+ );+ const sections = RULE_DISPLAY_CATEGORIES.map((category) => ({+ category,+ entries: visible.filter((rule) => displayCategoryForRule(rule) === category),+ })).filter((section) => section.entries.length > 0);++ return (+ <div className="space-y-3" data-testid="settings-linting-markdownlint-rules">+ {!ready ? (+ // Stable placeholder while the project config loads. Rendering either the+ // has-file or no-file copy before we know which one is correct causes a+ // visible reflow when the fetch resolves (the no-file state is a taller+ // two-paragraph + callout block); the skeleton reserves height instead.+ <div+ className="space-y-2"+ aria-busy="true"+ data-testid="markdownlint-rule-browser-config-loading"+ >+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ ) : configFile ? (+ <p className="text-sm text-muted-foreground">+ <Trans>+ These rules come from your project's{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">{configFile}</code>{' '}+ file, which fully governs linting for this project. Turn rules on or off and edit their+ options here; changes write back to the file.+ </Trans>+ </p>+ ) : (+ <div className="space-y-2">+ <p className="text-sm text-muted-foreground">+ <Trans>+ No{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">+ .markdownlint.*+ </code>{' '}+ file yet — every rule runs on the same defaults as the VS Code markdownlint extension:+ all on, except line length.+ </Trans>+ </p>+ <p+ className="flex items-start gap-1.5 rounded-md border border-dashed p-2.5 text-sm text-muted-foreground"+ data-testid="markdownlint-no-file-disclaimer"+ >+ <Info aria-hidden className="mt-0.5 size-4 shrink-0" />+ <span>+ <Trans>+ Heads up: editing any rule or option here creates a{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">+ .markdownlint.json+ </code>{' '}+ file in your project to save your changes.+ </Trans>+ </span>+ </p>+ </div>+ )}++ <p className="text-sm text-muted-foreground" data-testid="markdownlint-rule-browser-legend">+ <Trans>+ A <span className="font-medium text-foreground">Modified</span> badge marks rules your+ config sets explicitly — directly, or inherited through{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">extends</code>. Unmarked+ rules keep their default state.+ </Trans>+ </p>++ <div className="flex items-center gap-4">+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t`Search rules`}+ aria-label={t`Search rules by id, alias, or name`}+ className="h-8"+ data-testid="markdownlint-rule-search"+ />+ <div className="flex shrink-0 items-center gap-2">+ <Checkbox+ id="markdownlint-only-modified"+ checked={onlyModified}+ onCheckedChange={(next) => setOnlyModified(next === true)}+ data-testid="markdownlint-only-modified"+ />+ <Label htmlFor="markdownlint-only-modified" className="text-sm font-normal">+ <Trans>Only modified</Trans>+ </Label>+ </div>+ </div>++ {sections.length === 0 ? (+ <p+ className="rounded-md border border-dashed p-3 text-sm text-muted-foreground"+ data-testid="markdownlint-rule-browser-empty"+ >+ <Trans>No rules match your filters.</Trans>+ </p>+ ) : (+ <div className="space-y-2">+ {sections.map(({ category, entries }) => {+ const enabledCount = entries.filter((rule) =>+ ruleEnabled(governingRuleValue(rules, rule.id)),+ ).length;+ return (+ <Collapsible+ key={category}+ // While a filter is active every section is forced open — a+ // match inside a collapsed section would otherwise be invisible.+ open={filtersActive || !collapsed.includes(category)}+ onOpenChange={(open) =>+ setCollapsed(+ open ? collapsed.filter((c) => c !== category) : [...collapsed, category],+ )+ }+ >+ <CollapsibleTrigger+ className="group flex w-full items-center gap-2 rounded-md px-1.5 py-1.5 text-sm font-medium hover:bg-muted/50"+ data-testid={`markdownlint-rule-category-${categorySlug(category)}`}+ >+ <ChevronRight className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-90 motion-reduce:transition-none" />+ <CategoryLabel category={category} />+ <span className="ms-auto text-xs font-normal text-muted-foreground tabular-nums">+ <Trans>+ {enabledCount}/{entries.length} on+ </Trans>+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="mt-1 divide-y rounded-md border">+ {entries.map((rule) => (+ <RuleRow+ key={rule.id}+ rule={rule}+ value={governingRuleValue(rules, rule.id)}+ modified={isRuleModified(rules, configFile, rule.id)}+ ready={ready}+ onWrite={(value) => setRule(rule.id, value)}+ />+ ))}+ </div>+ </CollapsibleContent>+ </Collapsible>+ );+ })}+ </div>+ )}+ </div>+ );+}++function RuleRow({+ rule,+ value,+ modified,+ ready,+ onWrite,+}: {+ rule: RuleCatalogEntry;+ value: MarkdownlintRuleSetting;+ modified: boolean;+ ready: boolean;+ onWrite: (value: MarkdownlintRuleWriteValue | null) => void;+}) {+ const { t } = useLingui();+ const enabled = ruleEnabled(value);+ const severity = ruleSeverity(value);+ const opts = optionKeys(value);++ return (+ <Collapsible data-testid={`markdownlint-rule-row-${rule.id}`}>+ <div className="flex items-center justify-between gap-3 px-3 py-2">+ {/* The whole left cluster (chevron + name + id) is the disclosure+ trigger so clicking the row body expands it; the interactive controls+ (reset, Switch) stay outside the trigger as independent siblings. */}+ <CollapsibleTrigger+ className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-0.5 text-left hover:bg-muted/50"+ data-testid={`markdownlint-rule-expand-${rule.id}`}+ >+ <ChevronRight className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-90 motion-reduce:transition-none" />+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{rule.name}</span>+ </CollapsibleTrigger>+ <div className="flex shrink-0 items-center gap-2">+ {opts.length > 0 ? (+ <span+ id={`settings-linting-markdownlint-options-${rule.id}`}+ className="text-xs text-muted-foreground"+ title={opts.join(', ')}+ data-testid={`settings-linting-markdownlint-options-${rule.id}`}+ >+ <Plural value={opts.length} one="# option set" other="# options set" />+ </span>+ ) : null}+ {severity !== null ? (+ <Badge variant="gray" data-testid={`markdownlint-rule-severity-${rule.id}`}>+ {severity}+ </Badge>+ ) : null}+ {modified ? (+ <Badge variant="outline" data-testid={`markdownlint-rule-modified-${rule.id}`}>+ <Trans>Modified</Trans>+ </Badge>+ ) : null}+ {modified ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-5 w-5 shrink-0 text-muted-foreground opacity-60 hover:opacity-100"+ disabled={!ready}+ aria-label={t`Reset ${rule.id} to default`}+ onClick={() => onWrite(null)}+ >+ <RotateCcw className="size-3.5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Reset to default</Trans>+ </TooltipContent>+ </Tooltip>+ ) : null}+ <Switch+ id={`markdownlint-rule-toggle-${rule.id}`}+ checked={enabled}+ disabled={!ready}+ aria-label={enabled ? t`Disable ${rule.name}` : t`Enable ${rule.name}`}+ aria-describedby={+ opts.length > 0 ? `settings-linting-markdownlint-options-${rule.id}` : undefined+ }+ onCheckedChange={(next) => onWrite(toggledRuleValue(value, next))}+ data-testid={`markdownlint-rule-toggle-${rule.id}`}+ />+ </div>+ </div>+ <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">+ <div className="space-y-3 px-3 pb-3 pt-1">+ <p className="text-1sm text-muted-foreground">+ <span className="font-mono">+ {rule.id} · {rule.alias}+ </span>+ {' · '}+ <a+ href={rule.docUrl}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => dispatchExternalLinkClick(e, rule.docUrl)}+ onAuxClick={(e) => dispatchExternalLinkClick(e, rule.docUrl)}+ aria-label={t`Documentation for ${rule.id} (opens in browser)`}+ className="inline-flex items-center gap-0.5 text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ <Trans>Documentation</Trans>+ <ArrowUpRight aria-hidden className="size-3" />+ </a>+ </p>+ {rule.options.map((spec) => (+ <RuleOptionField+ key={spec.key}+ ruleId={rule.id}+ spec={spec}+ value={ruleOptionValueOf(value, spec.key)}+ disabled={!ready}+ onChange={(next) => onWrite(ruleValueWithOption(value, spec.key, next))}+ />+ ))}+ </div>+ </CollapsibleContent>+ </Collapsible>+ );+}++/** Display-category heading, routed through Lingui (categories are UI copy). */+function CategoryLabel({ category }: { category: RuleDisplayCategory }) {+ switch (category) {+ case 'Headings':+ return <Trans>Headings</Trans>;+ case 'Lists':+ return <Trans>Lists</Trans>;+ case 'Whitespace':+ return <Trans>Whitespace</Trans>;+ case 'Code':+ return <Trans>Code</Trans>;+ case 'Links & images':+ return <Trans>Links & images</Trans>;+ case 'Style':+ return <Trans>Style</Trans>;+ default:+ return category satisfies never;+ }+}++/** Stable testid fragment for a display category (`Links & images` → `links-images`). */+function categorySlug(category: RuleDisplayCategory): string {+ return category+ .toLowerCase()+ .replace(/[^a-z]+/g, '-')+ .replace(/^-|-$/g, '');+}++/**+ * The value governing a rule row — markdownlint's own fallback order: the+ * rule's key (id or any alias, case-insensitive, last matching key wins —+ * resolved via `findRuleConfigEntry`), else the config's `default` key, else+ * the engine built-in (on).+ */+export function governingRuleValue(rules: RuleValues, ruleId: string): MarkdownlintRuleSetting {+ const entry = findRuleConfigEntry(rules, ruleId);+ if (entry !== undefined) return entry.value as MarkdownlintRuleSetting;+ return rules.default ?? true;+}++/**+ * Whether the governing native file explicitly sets this rule under any of+ * its keys (id or alias, case-insensitive). With no governing file the+ * resolved config is OK's tuned defaults, so nothing reads as modified;+ * meta-keys (`default`, `extends`, `$schema`) never match because they map to+ * no catalog rule.+ */+export function isRuleModified(+ rules: RuleValues,+ configFile: string | null,+ ruleId: string,+): boolean {+ return configFile !== null && findRuleConfigEntry(rules, ruleId) !== undefined;+}++/** The read-only severity chip value (a `"error"`/`"warning"` file value). */+export function ruleSeverity(value: MarkdownlintRuleSetting): MarkdownlintRuleSeverity | null {+ return typeof value === 'string' ? value : null;+}++/** Case-insensitive substring match on id, alias, or upstream name; empty query matches all. */+export function ruleMatchesSearch(rule: RuleCatalogEntry, query: string): boolean {+ const q = query.trim().toLowerCase();+ if (q === '') return true;+ return (+ rule.id.toLowerCase().includes(q) ||+ rule.alias.toLowerCase().includes(q) ||+ rule.name.toLowerCase().includes(q)+ );+}++/**+ * A rule's effective on/off state. An object-valued rule is ON unless it+ * explicitly sets `enabled: false` (markdownlint treats an absent `enabled` as+ * enabled), so a rule that only carries options still reads as enabled.+ */+export function ruleEnabled(value: MarkdownlintRuleSetting): boolean {+ if (typeof value !== 'object' || value === null) return value !== false;+ return (value as { enabled?: unknown }).enabled !== false;+}++/** An object-valued rule's option keys, excluding the `enabled` on/off flag. */+export function optionKeys(value: MarkdownlintRuleSetting): string[] {+ if (typeof value !== 'object' || value === null) return [];+ return Object.keys(value).filter((key) => key !== 'enabled');+}++/**+ * The value to write when toggling a rule on/off, preserving any options the+ * rule already carries. A bare boolean stays bare; an object keeps its option+ * keys and flips `enabled` (dropped entirely when re-enabling, since absent+ * means on — keeps the file minimal). An object with no options collapses to a+ * bare boolean, and so does a severity-string value — the GUI never writes+ * severity strings, so toggling one replaces it. This is what lets the GUI+ * expose on/off for a rule whose options it can't edit, without discarding+ * those options.+ */+export function toggledRuleValue(+ value: MarkdownlintRuleSetting,+ nextEnabled: boolean,+): MarkdownlintRuleWriteValue {+ if (typeof value !== 'object' || value === null) return nextEnabled;+ const rest: Record<string, unknown> = {};+ for (const key of Object.keys(value)) {+ if (key !== 'enabled') rest[key] = (value as Record<string, unknown>)[key];+ }+ if (Object.keys(rest).length === 0) return nextEnabled;+ return nextEnabled ? rest : { ...rest, enabled: false };+}++/**+ * The value to write when editing one option: the rule's full params object,+ * composed by spreading the existing value before applying the edited key, so+ * sibling options — including keys the GUI doesn't model — and an+ * `enabled: false` flag survive. A bare `false` becomes `enabled: false`+ * (editing options never flips a rule on); `true` and severity strings carry+ * no keys, so they start a fresh object (severity is read-only vocabulary —+ * the row-replace is disclosed in the row tooltip).+ */+export function ruleValueWithOption(+ value: MarkdownlintRuleSetting,+ key: string,+ optionValue: RuleOptionValue,+): MarkdownlintRuleWriteValue {+ if (typeof value === 'object' && value !== null) return { ...value, [key]: optionValue };+ if (value === false) return { enabled: false, [key]: optionValue };+ return { [key]: optionValue };+}++/** One option's current value from the rule's params (non-object values set no options). */+function ruleOptionValueOf(value: MarkdownlintRuleSetting, key: string): unknown {+ if (typeof value !== 'object' || value === null) return undefined;+ return (value as Record<string, unknown>)[key];+}diff --git a/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts b/packages/app/src/components/settings/markdownlint-rule-toggle.test.tsnew file mode 100644index 000000000..36e2ec59b--- /dev/null+++ b/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts@@ -0,0 +1,204 @@+/**+ * Unit contract for the markdownlint rule value model behind the rule browser:+ * the on/off toggle and the option-edit composition that preserve keys they+ * don't edit, plus the row-state derivation (governing value, modified marker,+ * severity chip, search match). The DOM test covers rendering; this pins the+ * value computation.+ */++import { describe, expect, test } from 'bun:test';+import { MARKDOWNLINT_RULE_CATALOG } from '@inkeep/open-knowledge-core';+import {+ governingRuleValue,+ isRuleModified,+ optionKeys,+ ruleEnabled,+ ruleMatchesSearch,+ ruleSeverity,+ ruleValueWithOption,+ toggledRuleValue,+} from './markdownlint-rule-browser';++describe('ruleEnabled', () => {+ test('bare booleans map to themselves', () => {+ expect(ruleEnabled(true)).toBe(true);+ expect(ruleEnabled(false)).toBe(false);+ });++ test('an object with no enabled flag reads as enabled', () => {+ expect(ruleEnabled({ line_length: 100 })).toBe(true);+ });++ test('enabled:false disables regardless of other options', () => {+ expect(ruleEnabled({ line_length: 100, enabled: false })).toBe(false);+ expect(ruleEnabled({ enabled: true })).toBe(true);+ });++ test('severity strings read as enabled', () => {+ expect(ruleEnabled('error')).toBe(true);+ expect(ruleEnabled('warning')).toBe(true);+ });+});++describe('optionKeys', () => {+ test('excludes the enabled flag, keeps real options', () => {+ expect(optionKeys({ line_length: 100, enabled: false })).toEqual(['line_length']);+ });++ test('a bare boolean has no options', () => {+ expect(optionKeys(true)).toEqual([]);+ expect(optionKeys(false)).toEqual([]);+ });++ test('an enabled-only object has no options', () => {+ expect(optionKeys({ enabled: false })).toEqual([]);+ });++ test('a severity string has no options', () => {+ expect(optionKeys('error')).toEqual([]);+ });+});++describe('toggledRuleValue', () => {+ test('bare booleans stay bare', () => {+ expect(toggledRuleValue(true, false)).toBe(false);+ expect(toggledRuleValue(false, true)).toBe(true);+ });++ test('disabling an option-carrying rule preserves options and adds enabled:false', () => {+ expect(toggledRuleValue({ line_length: 100 }, false)).toEqual({+ line_length: 100,+ enabled: false,+ });+ });++ test('re-enabling drops the enabled flag but keeps options (minimal file)', () => {+ expect(toggledRuleValue({ line_length: 100, enabled: false }, true)).toEqual({+ line_length: 100,+ });+ });++ test('an enabled-only object collapses to a bare boolean', () => {+ expect(toggledRuleValue({ enabled: true }, false)).toBe(false);+ expect(toggledRuleValue({ enabled: false }, true)).toBe(true);+ });++ test('MD043-style headings are preserved across a toggle round-trip', () => {+ const disabled = toggledRuleValue({ headings: ['# A', '## B'] }, false);+ expect(disabled).toEqual({ headings: ['# A', '## B'], enabled: false });+ expect(toggledRuleValue(disabled, true)).toEqual({ headings: ['# A', '## B'] });+ });++ test('a severity-string value collapses to a bare boolean (never written back)', () => {+ expect(toggledRuleValue('error', false)).toBe(false);+ expect(toggledRuleValue('warning', true)).toBe(true);+ });+});++describe('ruleValueWithOption', () => {+ test('unknown sibling keys in the existing value survive an option edit', () => {+ expect(ruleValueWithOption({ line_length: 120, unknown_key: 'x' }, 'line_length', 100)).toEqual(+ { line_length: 100, unknown_key: 'x' },+ );+ });++ test('a new option key lands alongside the existing ones', () => {+ expect(ruleValueWithOption({ line_length: 100 }, 'code_blocks', false)).toEqual({+ line_length: 100,+ code_blocks: false,+ });+ });++ test('an enabled:false flag survives, so editing options keeps the rule off', () => {+ expect(ruleValueWithOption({ enabled: false, line_length: 80 }, 'line_length', 100)).toEqual({+ enabled: false,+ line_length: 100,+ });+ });++ test('a bare-true value starts a fresh params object', () => {+ expect(ruleValueWithOption(true, 'line_length', 100)).toEqual({ line_length: 100 });+ });++ test('a bare-false value starts a params object that stays off', () => {+ expect(ruleValueWithOption(false, 'line_length', 100)).toEqual({+ enabled: false,+ line_length: 100,+ });+ });++ test('a severity-string value is replaced by the params object (row-replace)', () => {+ expect(ruleValueWithOption('error', 'line_length', 100)).toEqual({ line_length: 100 });+ });++ test('string-array option values pass through intact', () => {+ expect(ruleValueWithOption({ match_case: true }, 'headings', ['*', '## Summary'])).toEqual({+ match_case: true,+ headings: ['*', '## Summary'],+ });+ });+});++describe('governingRuleValue', () => {+ test('the rule key wins over the config default', () => {+ expect(governingRuleValue({ MD001: false, default: true }, 'MD001')).toBe(false);+ });++ test('falls back to the config default key', () => {+ expect(governingRuleValue({ default: false }, 'MD001')).toBe(false);+ });++ test('falls back to the engine built-in (on) when neither is set', () => {+ expect(governingRuleValue({}, 'MD001')).toBe(true);+ });+});++describe('isRuleModified', () => {+ test('a key set by a governing file marks the rule modified', () => {+ expect(isRuleModified({ MD001: false }, '.markdownlint.json', 'MD001')).toBe(true);+ });++ test('tuned-default keys without a governing file are not modified', () => {+ expect(isRuleModified({ MD013: false, default: true }, null, 'MD013')).toBe(false);+ });++ test('a rule absent from the governing file is not modified', () => {+ expect(isRuleModified({ default: true }, '.markdownlint.json', 'MD001')).toBe(false);+ });+});++describe('ruleSeverity', () => {+ test('severity strings surface; other value shapes do not', () => {+ expect(ruleSeverity('error')).toBe('error');+ expect(ruleSeverity('warning')).toBe('warning');+ expect(ruleSeverity(true)).toBeNull();+ expect(ruleSeverity(false)).toBeNull();+ expect(ruleSeverity({ line_length: 100 })).toBeNull();+ });+});++describe('ruleMatchesSearch', () => {+ const md025 = MARKDOWNLINT_RULE_CATALOG.find((rule) => rule.id === 'MD025');+ if (md025 === undefined) throw new Error('MD025 missing from the generated catalog');++ test('an empty or whitespace query matches every rule', () => {+ expect(ruleMatchesSearch(md025, '')).toBe(true);+ expect(ruleMatchesSearch(md025, ' ')).toBe(true);+ });++ test('matches the id case-insensitively', () => {+ expect(ruleMatchesSearch(md025, 'md025')).toBe(true);+ });++ test('matches the primary alias', () => {+ expect(ruleMatchesSearch(md025, 'single-title')).toBe(true);+ });++ test('matches a fragment of the upstream name', () => {+ expect(ruleMatchesSearch(md025, 'top-level heading')).toBe(true);+ });++ test('rejects a query matching none of id, alias, or name', () => {+ expect(ruleMatchesSearch(md025, 'zzz-no-such-rule')).toBe(false);+ });+});diff --git a/packages/app/src/components/settings/rule-option-field.dom.test.tsx b/packages/app/src/components/settings/rule-option-field.dom.test.tsxnew file mode 100644index 000000000..40aa87e01--- /dev/null+++ b/packages/app/src/components/settings/rule-option-field.dom.test.tsx@@ -0,0 +1,382 @@+/**+ * Behavior tests for the generic rule-option widget vocabulary+ * (`RuleOptionField`): each `RuleOptionSpec.type` dispatches to its control+ * and edits emit typed values. Specs come from the real generated catalog so+ * the vocabulary is exercised against what ships — including MD022, whose+ * union-typed `lines_above`/`lines_below` must fall back to the read-only+ * chip while its sibling `include_front_matter` stays editable.+ */+import { afterEach, describe, expect, mock, test } from 'bun:test';+import { MARKDOWNLINT_RULE_CATALOG, type RuleOptionSpec } from '@inkeep/open-knowledge-core';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { RULE_OPTION_WIDGET_OVERRIDES, RuleOptionField } from './rule-option-field';++// Radix primitives reach for pointer-capture and scroll APIs the jsdom+// preload doesn't expose; hoist the same shims the sibling DOM tests use.+const ElementProto = Element.prototype as Element & {+ hasPointerCapture?: () => boolean;+ releasePointerCapture?: () => void;+ scrollIntoView?: () => void;+};+ElementProto.hasPointerCapture ??= () => false;+ElementProto.releasePointerCapture ??= () => {};+ElementProto.scrollIntoView ??= () => {};+type GlobalWithDomShims = typeof globalThis & { ResizeObserver?: unknown };+const globalWithDomShims = globalThis as GlobalWithDomShims;+if (globalWithDomShims.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalWithDomShims.ResizeObserver = NoopResizeObserver;+}++function catalogSpec(ruleId: string, key: string): RuleOptionSpec {+ const rule = MARKDOWNLINT_RULE_CATALOG.find((r) => r.id === ruleId);+ const spec = rule?.options.find((o) => o.key === key);+ if (!spec) throw new Error(`generated catalog is missing ${ruleId}.${key}`);+ return spec;+}++afterEach(() => {+ cleanup();+});++describe('RuleOptionField — boolean', () => {+ test('renders a Switch seeded from the spec default and emits the flipped boolean', async () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD022"+ spec={catalogSpec('MD022', 'include_front_matter')}+ value={undefined}+ onChange={onChange}+ />,+ );+ const control = screen.getByLabelText('include_front_matter');+ expect(control.getAttribute('role')).toBe('switch');+ expect(control.getAttribute('aria-checked')).toBe('false');+ await userEvent.click(control);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(true);+ });++ test('a set value wins over the spec default and toggles back off', async () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD022"+ spec={catalogSpec('MD022', 'include_front_matter')}+ value={true}+ onChange={onChange}+ />,+ );+ const control = screen.getByLabelText('include_front_matter');+ expect(control.getAttribute('aria-checked')).toBe('true');+ await userEvent.click(control);+ expect(onChange).toHaveBeenCalledWith(false);+ });++ test('shows the option description and default, associated to the control', () => {+ render(+ <RuleOptionField+ ruleId="MD022"+ spec={catalogSpec('MD022', 'include_front_matter')}+ value={undefined}+ onChange={() => {}}+ />,+ );+ const control = screen.getByLabelText('include_front_matter');+ const describedBy = control.getAttribute('aria-describedby');+ expect(describedBy).not.toBeNull();+ const description = document.getElementById(describedBy as string);+ expect(description?.textContent).toContain('Include front matter content');+ expect(description?.textContent).toContain('Default:');+ expect(description?.textContent).toContain('false');+ });++ test('disabled renders an inert control', () => {+ render(+ <RuleOptionField+ ruleId="MD022"+ spec={catalogSpec('MD022', 'include_front_matter')}+ value={undefined}+ disabled+ onChange={() => {}}+ />,+ );+ expect((screen.getByLabelText('include_front_matter') as HTMLButtonElement).disabled).toBe(+ true,+ );+ });+});++describe('RuleOptionField — unsupported fallback (MD022)', () => {+ test('lines_above/lines_below render the read-only chip while include_front_matter stays a Switch', () => {+ const md022 = MARKDOWNLINT_RULE_CATALOG.find((r) => r.id === 'MD022');+ if (!md022) throw new Error('generated catalog is missing MD022');+ render(+ <div>+ {md022.options.map((spec) => (+ <RuleOptionField+ key={spec.key}+ ruleId="MD022"+ spec={spec}+ value={undefined}+ onChange={() => {}}+ />+ ))}+ </div>,+ );+ expect(screen.getByLabelText('include_front_matter').getAttribute('role')).toBe('switch');+ for (const key of ['lines_above', 'lines_below']) {+ const chip = screen.getByTestId(`rule-option-MD022-${key}-unsupported`);+ expect(chip.textContent).toBe('Edit in config file');+ // Read-only: the field offers no editing control.+ const field = screen.getByTestId(`rule-option-MD022-${key}`);+ expect(field.querySelector('input, button, select, textarea')).toBeNull();+ }+ });++ test('the chip field still shows the option description and default', () => {+ render(+ <RuleOptionField+ ruleId="MD022"+ spec={catalogSpec('MD022', 'lines_above')}+ value={undefined}+ onChange={() => {}}+ />,+ );+ const field = screen.getByTestId('rule-option-MD022-lines_above');+ expect(field.textContent).toContain('lines_above');+ expect(field.textContent).toContain('Blank lines above heading');+ expect(field.textContent).toContain('Default:');+ expect(field.textContent).toContain('1');+ });+});++describe('RuleOptionField — integer', () => {+ test('shows the spec default when unset and emits the typed number on blur', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD013"+ spec={catalogSpec('MD013', 'line_length')}+ value={undefined}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('line_length') as HTMLInputElement;+ expect(input.value).toBe('80');+ fireEvent.change(input, { target: { value: '120' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(120);+ });++ test('a set value wins over the default and Enter commits', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD013"+ spec={catalogSpec('MD013', 'line_length')}+ value={100}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('line_length') as HTMLInputElement;+ expect(input.value).toBe('100');+ fireEvent.change(input, { target: { value: '90' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(90);+ });++ test('honors the schema minimum by clamping the committed value', () => {+ // MD013 line_length carries minimum 1 in the vendored schema.+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD013"+ spec={catalogSpec('MD013', 'line_length')}+ value={80}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('line_length') as HTMLInputElement;+ expect(input.min).toBe('1');+ fireEvent.change(input, { target: { value: '0' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledWith(1);+ expect(input.value).toBe('1');+ });++ test('an emptied input reverts to the committed value without emitting', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD013"+ spec={catalogSpec('MD013', 'line_length')}+ value={100}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('line_length') as HTMLInputElement;+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledTimes(0);+ expect(input.value).toBe('100');+ });++ test('re-committing the unchanged value does not emit', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD013"+ spec={catalogSpec('MD013', 'line_length')}+ value={100}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('line_length') as HTMLInputElement;+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledTimes(0);+ });+});++describe('RuleOptionField — string', () => {+ test('shows the spec default when unset and emits the edited string on blur', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD001"+ spec={catalogSpec('MD001', 'front_matter_title')}+ value={undefined}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('front_matter_title') as HTMLInputElement;+ expect(input.value).toBe('^\\s*title\\s*[:=]');+ fireEvent.change(input, { target: { value: '^title:' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith('^title:');+ });++ test('an emptied string commits (a meaningful markdownlint value)', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD001"+ spec={catalogSpec('MD001', 'front_matter_title')}+ value={'^title:'}+ onChange={onChange}+ />,+ );+ const input = screen.getByLabelText('front_matter_title') as HTMLInputElement;+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);+ expect(onChange).toHaveBeenCalledWith('');+ });+});++describe('RuleOptionField — enum', () => {+ test('renders a Select showing the effective value and emits the chosen literal', async () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD003"+ spec={catalogSpec('MD003', 'style')}+ value={undefined}+ onChange={onChange}+ />,+ );+ const trigger = screen.getByLabelText('style');+ expect(trigger.textContent).toContain('consistent');+ await userEvent.click(trigger);+ await userEvent.click(await screen.findByRole('option', { name: 'atx' }));+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith('atx');+ });++ test('lists every enum literal from the schema', async () => {+ render(+ <RuleOptionField+ ruleId="MD003"+ spec={catalogSpec('MD003', 'style')}+ value={'atx'}+ onChange={() => {}}+ />,+ );+ const trigger = screen.getByLabelText('style');+ expect(trigger.textContent).toContain('atx');+ await userEvent.click(trigger);+ const options = await screen.findAllByRole('option');+ expect(options.map((o) => o.textContent)).toEqual([+ 'consistent',+ 'atx',+ 'atx_closed',+ 'setext',+ 'setext_with_atx',+ 'setext_with_atx_closed',+ ]);+ });+});++describe('RuleOptionField — string-array', () => {+ test('renders existing entries as pills and commits grammar-free values verbatim', () => {+ // MD043 headings hold values like `## Summary` — spaces and a leading+ // `#` must survive (the frontmatter tag grammar would reject/mangle).+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD043"+ spec={catalogSpec('MD043', 'headings')}+ value={['*']}+ onChange={onChange}+ />,+ );+ const field = screen.getByTestId('rule-option-MD043-headings');+ expect(field.textContent).toContain('*');+ expect(field.querySelectorAll('[data-tag-invalid="true"]')).toHaveLength(0);+ const input = screen.getByLabelText('headings') as HTMLInputElement;+ fireEvent.change(input, { target: { value: '## Summary' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(['*', '## Summary']);+ });++ test('removing a pill emits the shortened array', () => {+ const onChange = mock(() => {});+ render(+ <RuleOptionField+ ruleId="MD043"+ spec={catalogSpec('MD043', 'headings')}+ value={['*', '## Summary']}+ onChange={onChange}+ />,+ );+ fireEvent.click(screen.getByLabelText('Remove ## Summary'));+ expect(onChange).toHaveBeenCalledWith(['*']);+ });++ test('unset value starts from the spec default (empty list)', () => {+ render(+ <RuleOptionField+ ruleId="MD043"+ spec={catalogSpec('MD043', 'headings')}+ value={undefined}+ onChange={() => {}}+ />,+ );+ const field = screen.getByTestId('rule-option-MD043-headings');+ expect(field.querySelectorAll('[data-slot="tag-pill-input"] .font-mono')).toHaveLength(0);+ });+});++describe('RuleOptionField — per-rule override escape hatch', () => {+ test('the override map ships empty', () => {+ expect(Object.keys(RULE_OPTION_WIDGET_OVERRIDES)).toHaveLength(0);+ });+});diff --git a/packages/app/src/components/settings/rule-option-field.tsx b/packages/app/src/components/settings/rule-option-field.tsxnew file mode 100644index 000000000..39de021d5--- /dev/null+++ b/packages/app/src/components/settings/rule-option-field.tsx@@ -0,0 +1,368 @@+/**+ * Generic editor for one markdownlint rule option. Dispatches the generated+ * catalog's `RuleOptionSpec.type` to a shadcn control, so every rule's+ * options render with zero per-rule UI code; option shapes outside the+ * vocabulary (`unsupported`) render as a read-only chip pointing at the+ * config file. Option values are native markdownlint config values and may+ * come from a hand-edited `.markdownlint.*` file, so every control narrows+ * its `value` before trusting the shape.+ */+import type { RuleOptionSpec } from '@inkeep/open-knowledge-core';+import { Trans } from '@lingui/react/macro';+import { type ComponentType, type ReactNode, useEffect, useRef, useState } from 'react';+import { Badge } from '@/components/ui/badge';+import { FieldDescription } from '@/components/ui/field';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Switch } from '@/components/ui/switch';+import { TagPillInput } from '@/components/ui/tag-pill-input';++/** A value the generic widgets can emit — one key's worth of a rule's params object. */+export type RuleOptionValue = boolean | number | string | string[];++export interface RuleOptionFieldProps {+ /** Rule id (`MD013`) — namespaces control ids and the override lookup. */+ ruleId: string;+ spec: RuleOptionSpec;+ /** The option's current value from the rule's effective params (undefined = unset). */+ value: unknown;+ disabled?: boolean;+ /** Fires with the option's new typed value when the user commits an edit. */+ onChange: (next: RuleOptionValue) => void;+}++/**+ * Escape hatch: a rule id mapped here renders its option fields through the+ * given component instead of the generic dispatch. Ships empty — the+ * vocabulary covers every current rule's supported options; add an entry+ * only when a rule needs bespoke option UI the vocabulary can't express.+ */+export const RULE_OPTION_WIDGET_OVERRIDES: Readonly<+ Record<string, ComponentType<RuleOptionFieldProps>>+> = {};++export function RuleOptionField(props: RuleOptionFieldProps) {+ const Override = RULE_OPTION_WIDGET_OVERRIDES[props.ruleId];+ if (Override !== undefined) return <Override {...props} />;+ return <GenericRuleOptionField {...props} />;+}++function GenericRuleOptionField({ ruleId, spec, value, disabled, onChange }: RuleOptionFieldProps) {+ const controlId = `rule-option-${ruleId}-${spec.key}`;+ const descriptionId = `${controlId}-description`;++ const header = (+ <div className="min-w-0 space-y-0.5">+ {spec.type === 'unsupported' ? (+ // No form control to label — keep the key out of label semantics.+ <span className="font-mono text-sm font-medium">{spec.key}</span>+ ) : (+ <Label htmlFor={controlId} className="font-mono text-sm font-medium">+ {spec.key}+ </Label>+ )}+ <FieldDescription id={descriptionId}>+ {spec.description}+ {spec.default !== undefined ? (+ <>+ {' · '}+ <Trans>+ Default: <code className="font-mono">{formatOptionConfigValue(spec.default)}</code>+ </Trans>+ </>+ ) : null}+ </FieldDescription>+ </div>+ );++ const shared = { controlId, descriptionId, disabled: disabled === true, onChange };++ switch (spec.type) {+ case 'boolean':+ return (+ <FieldRow testId={controlId} header={header}>+ <BooleanOptionControl {...shared} spec={spec} value={value} />+ </FieldRow>+ );+ case 'enum':+ return (+ <FieldRow testId={controlId} header={header}>+ <EnumOptionControl {...shared} spec={spec} value={value} />+ </FieldRow>+ );+ case 'integer':+ return (+ <FieldRow testId={controlId} header={header}>+ <IntegerOptionControl {...shared} spec={spec} value={value} />+ </FieldRow>+ );+ case 'string':+ return (+ <FieldStack testId={controlId} header={header}>+ <StringOptionControl {...shared} spec={spec} value={value} />+ </FieldStack>+ );+ case 'string-array':+ return (+ <FieldStack testId={controlId} header={header}>+ <StringArrayOptionControl {...shared} spec={spec} value={value} />+ </FieldStack>+ );+ case 'unsupported':+ return (+ <FieldRow testId={controlId} header={header}>+ <Badge variant="gray" data-testid={`${controlId}-unsupported`}>+ <Trans>Edit in config file</Trans>+ </Badge>+ </FieldRow>+ );+ default:+ return spec satisfies never;+ }+}++/** Compact controls sit beside the label; the header keeps layout priority. */+function FieldRow({+ testId,+ header,+ children,+}: {+ testId: string;+ header: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="flex items-start justify-between gap-3" data-testid={testId}>+ {header}+ <div className="shrink-0">{children}</div>+ </div>+ );+}++/** Wide controls (text, pill lists) stack under the label at full width. */+function FieldStack({+ testId,+ header,+ children,+}: {+ testId: string;+ header: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="space-y-1.5" data-testid={testId}>+ {header}+ {children}+ </div>+ );+}++/**+ * Render an option value as the config-file literal it round-trips to+ * (`80`, `"atx"`, `[]`) — unambiguous for users who also hand-edit the file.+ * Defaults come from the vendored JSON schema, so they are always+ * JSON-representable.+ */+function formatOptionConfigValue(value: unknown): string {+ return JSON.stringify(value);+}++interface OptionControlProps<S extends RuleOptionSpec> {+ spec: S;+ value: unknown;+ controlId: string;+ descriptionId: string;+ disabled: boolean;+ onChange: (next: RuleOptionValue) => void;+}++type SpecOf<T extends RuleOptionSpec['type']> = Extract<RuleOptionSpec, { type: T }>;++function BooleanOptionControl({+ spec,+ value,+ controlId,+ descriptionId,+ disabled,+ onChange,+}: OptionControlProps<SpecOf<'boolean'>>) {+ const checked = typeof value === 'boolean' ? value : (spec.default ?? false);+ return (+ <Switch+ id={controlId}+ checked={checked}+ disabled={disabled}+ aria-describedby={descriptionId}+ onCheckedChange={(next) => onChange(next)}+ />+ );+}++function EnumOptionControl({+ spec,+ value,+ controlId,+ descriptionId,+ disabled,+ onChange,+}: OptionControlProps<SpecOf<'enum'>>) {+ const current = typeof value === 'string' ? value : (spec.default ?? '');+ return (+ <Select value={current} onValueChange={(next) => onChange(next)} disabled={disabled}>+ <SelectTrigger id={controlId} aria-describedby={descriptionId} className="w-48">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {spec.enum.map((option) => (+ <SelectItem key={option} value={option}>+ {option}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++/**+ * Number input over a string presentation buffer (the user can hold+ * intermediate text like `12` on the way to `120` without premature+ * parsing), matching the Settings number-control pattern. Commits on+ * blur/Enter: empty or unparseable text reverts to the committed value;+ * a parseable value is rounded, clamped into the schema's+ * `minimum`/`maximum`, and emitted only when it actually changed.+ */+function IntegerOptionControl({+ spec,+ value,+ controlId,+ descriptionId,+ disabled,+ onChange,+}: OptionControlProps<SpecOf<'integer'>>) {+ const committed = typeof value === 'number' ? value : spec.default;+ const committedText = committed === undefined ? '' : String(committed);+ const [pendingText, setPendingText] = useState(committedText);+ const lastSyncedRef = useRef(committed);++ useEffect(() => {+ if (lastSyncedRef.current === committed) return;+ setPendingText(committed === undefined ? '' : String(committed));+ lastSyncedRef.current = committed;+ }, [committed]);++ const commit = () => {+ if (pendingText.trim() === '') {+ setPendingText(committedText);+ return;+ }+ const parsed = Number(pendingText);+ if (!Number.isFinite(parsed)) {+ setPendingText(committedText);+ return;+ }+ let next = Math.round(parsed);+ if (spec.minimum !== undefined && next < spec.minimum) next = spec.minimum;+ if (spec.maximum !== undefined && next > spec.maximum) next = spec.maximum;+ setPendingText(String(next));+ if (next === committed) return;+ onChange(next);+ };++ return (+ <Input+ id={controlId}+ type="number"+ value={pendingText}+ min={spec.minimum}+ max={spec.maximum}+ disabled={disabled}+ aria-describedby={descriptionId}+ onChange={(e) => setPendingText(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ commit();+ }+ }}+ className="h-8 w-28 text-sm tabular-nums"+ />+ );+}++/**+ * Text input committing on blur/Enter. An empty string commits — it is a+ * meaningful markdownlint value (e.g. clearing MD001's front-matter title+ * pattern disables that check).+ */+function StringOptionControl({+ spec,+ value,+ controlId,+ descriptionId,+ disabled,+ onChange,+}: OptionControlProps<SpecOf<'string'>>) {+ const committed = typeof value === 'string' ? value : (spec.default ?? '');+ const [pendingText, setPendingText] = useState(committed);+ const lastSyncedRef = useRef(committed);++ useEffect(() => {+ if (lastSyncedRef.current === committed) return;+ setPendingText(committed);+ lastSyncedRef.current = committed;+ }, [committed]);++ const commit = () => {+ if (pendingText === committed) return;+ onChange(pendingText);+ };++ return (+ <Input+ id={controlId}+ value={pendingText}+ disabled={disabled}+ aria-describedby={descriptionId}+ onChange={(e) => setPendingText(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ commit();+ }+ }}+ className="h-8 font-mono text-sm"+ />+ );+}++function StringArrayOptionControl({+ spec,+ value,+ controlId,+ descriptionId,+ disabled,+ onChange,+}: OptionControlProps<SpecOf<'string-array'>>) {+ const entries = Array.isArray(value)+ ? value.filter((entry): entry is string => typeof entry === 'string')+ : [...(spec.default ?? [])];+ return (+ <TagPillInput+ id={controlId}+ value={entries}+ grammar="free-text"+ disabled={disabled}+ aria-describedby={descriptionId}+ onChange={(next) => onChange(next)}+ />+ );+}diff --git a/packages/app/src/components/terminal-theme.test.ts b/packages/app/src/components/terminal-theme.test.tsindex e6046c009..a97eb39e5 100644--- a/packages/app/src/components/terminal-theme.test.ts+++ b/packages/app/src/components/terminal-theme.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from 'bun:test';-import { XTERM_DARK_THEME, XTERM_LIGHT_THEME, xtermThemeForMode } from './terminal-theme';+import {+ computeLiveXtermTheme,+ XTERM_DARK_THEME,+ XTERM_LIGHT_THEME,+ xtermThemeForMode,+} from './terminal-theme';/** WCAG relative luminance of a `#rrggbb` color, in [0, 1]. */function luminance(hex: string): number {@@ -94,3 +99,40 @@ describe('curated xterm palettes', () => {).toBeGreaterThanOrEqual(4.5);});});++describe('computeLiveXtermTheme', () => {+ const reader = (tokens: Record<string, string>) => (token: string) => tokens[token] ?? null;++ test('overrides surface slots from resolved theme tokens', () => {+ const theme = computeLiveXtermTheme(+ 'dark',+ reader({+ '--background': 'rgb(20, 24, 34)',+ '--foreground': 'rgb(220, 224, 234)',+ '--selection-soft': 'rgba(90, 120, 255, 0.3)',+ }),+ );+ expect(theme.background).toBe('rgb(20, 24, 34)');+ expect(theme.foreground).toBe('rgb(220, 224, 234)');+ expect(theme.cursor).toBe('rgb(220, 224, 234)');+ expect(theme.cursorAccent).toBe('rgb(20, 24, 34)');+ expect(theme.selectionBackground).toBe('rgba(90, 120, 255, 0.3)');+ });++ test('keeps the curated ANSI slots for the mode', () => {+ const theme = computeLiveXtermTheme('dark', reader({ '--background': 'rgb(1, 2, 3)' }));+ for (const slot of ANSI_16) expect(theme[slot]).toBe(XTERM_DARK_THEME[slot]);+ });++ test('falls back to the curated palette when tokens do not resolve', () => {+ expect(computeLiveXtermTheme('dark', () => null)).toEqual(XTERM_DARK_THEME);+ expect(computeLiveXtermTheme('light', () => null)).toEqual(XTERM_LIGHT_THEME);+ });++ test('partial resolution falls back per slot', () => {+ const theme = computeLiveXtermTheme('light', reader({ '--background': 'rgb(9, 9, 9)' }));+ expect(theme.background).toBe('rgb(9, 9, 9)');+ expect(theme.foreground).toBe(XTERM_LIGHT_THEME.foreground);+ expect(theme.selectionBackground).toBe(XTERM_LIGHT_THEME.selectionBackground);+ });+});diff --git a/packages/app/src/components/terminal-theme.ts b/packages/app/src/components/terminal-theme.tsindex 65bc92045..719ba3200 100644--- a/packages/app/src/components/terminal-theme.ts+++ b/packages/app/src/components/terminal-theme.ts@@ -68,3 +68,63 @@ export const XTERM_LIGHT_THEME = {export function xtermThemeForMode(resolvedTheme: string | undefined): ITheme {return resolvedTheme === 'dark' ? XTERM_DARK_THEME : XTERM_LIGHT_THEME;}++/** Resolve one design token (`--background`, …) to a concrete color, or null. */+export type TokenColorReader = (token: string) => string | null;++/**+ * Default token reader: a detached-then-attached probe span whose+ * `backgroundColor` is `var(<token>)`, read back through `getComputedStyle`.+ * The round-trip makes the browser resolve `var()` chains and relative color+ * syntax (`oklch(from var(--primary) …)`) to a concrete color string, which+ * xterm's browser build can parse via its canvas litmus. Returns null when the+ * token is unset or the environment can't resolve it (tests, SSR).+ */+function readTokenColor(token: string): string | null {+ try {+ const probe = document.createElement('span');+ probe.style.display = 'none';+ probe.style.backgroundColor = `var(${token})`;+ document.body.appendChild(probe);+ try {+ const resolved = getComputedStyle(probe).backgroundColor;+ // An unset token computes to the transparent initial value — treat as+ // absent rather than skinning the terminal invisible. A value still+ // containing `var(` means the environment didn't resolve custom+ // properties (happy-dom in tests) — also absent.+ if (!resolved || resolved === 'rgba(0, 0, 0, 0)' || resolved === 'transparent') return null;+ if (resolved.includes('var(')) return null;+ return resolved;+ } finally {+ probe.remove();+ }+ } catch {+ return null;+ }+}++/**+ * The curated mode palette with its surface slots re-derived from the live+ * theme tokens, so the terminal follows plugin/custom color themes instead of+ * only light/dark. ANSI slots stay curated by mode: the 16 ANSI colors have no+ * mapping onto the semantic token set that preserves terminal legibility, and+ * `minimumContrastRatio` lifts residual clashes. Any token that fails to+ * resolve falls back to the curated value, so this degrades to+ * `xtermThemeForMode` when no color theme is active or off-DOM.+ */+export function computeLiveXtermTheme(+ resolvedTheme: string | undefined,+ readToken: TokenColorReader = readTokenColor,+): ITheme {+ const base = xtermThemeForMode(resolvedTheme);+ const background = readToken('--background') ?? base.background;+ const foreground = readToken('--foreground') ?? base.foreground;+ return {+ ...base,+ background,+ foreground,+ cursor: foreground,+ cursorAccent: background,+ selectionBackground: readToken('--selection-soft') ?? base.selectionBackground,+ };+}diff --git a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx b/packages/app/src/components/ui/tag-pill-input.dom.test.tsxindex 929df70a1..ae1349cfb 100644--- a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx+++ b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx@@ -215,6 +215,61 @@ describe('TagPillInput — input-side grammar gate', () => {});});+describe('TagPillInput — free-text grammar', () => {+ afterEach(() => {+ cleanup();+ });++ function renderFreeText(opts: RenderOpts = {}) {+ const onChange = opts.onChange ?? mock(() => {});+ const result = render(+ <TooltipProvider>+ <TagPillInput value={opts.value ?? []} onChange={onChange} grammar="free-text" />+ </TooltipProvider>,+ );+ return { ...result, onChange };+ }++ test('commits values the tag grammar rejects, verbatim — no leading-# strip', () => {+ // markdownlint option lists hold values like MD043's `## Summary`:+ // spaces fail the tag grammar and the leading `#` would be stripped+ // by the frontmatter normalization. Free-text must preserve both.+ const onChange = mock(() => {});+ const { container } = renderFreeText({ onChange });+ const input = container.querySelector('input') as HTMLInputElement;+ fireEvent.change(input, { target: { value: '## Summary' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0]?.[0]).toEqual(['## Summary']);+ expect(input.value).toBe('');+ expect(input.getAttribute('aria-invalid')).toBeNull();+ });++ test('never flags seeded pills as invalid (no tag-grammar styling)', () => {+ const { container } = renderFreeText({ value: ['## Summary', '*', 'has spaces'] });+ expect(container.querySelectorAll('[data-tag-invalid="true"]')).toHaveLength(0);+ });++ test('still trims, drops empty drafts, and dedupes', () => {+ const onChange = mock(() => {});+ const { container } = renderFreeText({ value: ['*'], onChange });+ const input = container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: ' ' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledTimes(0);++ fireEvent.change(input, { target: { value: '*' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledTimes(0);+ expect(input.value).toBe('');++ fireEvent.change(input, { target: { value: ' ## Details ' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(['*', '## Details']);+ });+});+describe('TagPillInput — a11y id wiring (regression: PR #1288 review findings)', () => {afterEach(() => {cleanup();diff --git a/packages/app/src/components/ui/tag-pill-input.tsx b/packages/app/src/components/ui/tag-pill-input.tsxindex 4dfb53ed1..6dcf572c0 100644--- a/packages/app/src/components/ui/tag-pill-input.tsx+++ b/packages/app/src/components/ui/tag-pill-input.tsx@@ -20,6 +20,16 @@ interface TagPillInputProps {'aria-describedby'?: string;'aria-invalid'?: boolean | 'true' | 'false';disabled?: boolean;+ /**+ * Entry grammar. `frontmatter-tag` (default) enforces the frontmatter+ * `tags:` value grammar: a leading `#` is stripped on commit, invalid+ * entries are rejected with the grammar hint, and non-conforming pills+ * are flagged. `free-text` admits any non-empty entry verbatim — for+ * callers whose entries are not frontmatter tags (markdownlint option+ * lists hold values like `## Summary` that the tag grammar would+ * reject, and whose leading `#` must survive).+ */+ grammar?: 'frontmatter-tag' | 'free-text';/*** Forwarded onto the inner `<input>` so RHF's `form.setFocus(name)`* resolves through `Controller.field.ref`. Without this, `setFocus` on@@ -52,6 +62,7 @@ function TagPillInput({placeholder,id,disabled,+ grammar = 'frontmatter-tag','aria-describedby': ariaDescribedBy,'aria-invalid': ariaInvalid,ref,@@ -73,21 +84,24 @@ function TagPillInput({const grammarHintId = `${id ?? fallbackId}-grammar-hint`;const resolvedPlaceholder = placeholder ?? t`Add tag`;+ const tagGrammar = grammar === 'frontmatter-tag';+const addTag = (raw: string) => {const tag = raw.trim();if (!tag) return;- if (!isValidFrontmatterTagValue(tag)) {+ if (tagGrammar && !isValidFrontmatterTagValue(tag)) {setDraftRejected(true);return;}- // Normalize leading `#`. `isValidFrontmatterTagValue` strips- // a single leading `#` for paste tolerance (Obsidian-shape+ // Normalize leading `#` (tag grammar only). `isValidFrontmatterTagValue`+ // strips a single leading `#` for paste tolerance (Obsidian-shape// input), so `#showcase` passes the gate above — but the// committed list must hold canonical bare values. Without this,// the next on-disk YAML parse would silently re-normalize the// value (drifting display) and the dedup check below would- // miss the duplicate `#showcase` / `showcase` pair.- const normalized = tag.startsWith('#') ? tag.slice(1) : tag;+ // miss the duplicate `#showcase` / `showcase` pair. Free-text+ // entries commit verbatim (`## Summary` keeps its `#`s).+ const normalized = tagGrammar && tag.startsWith('#') ? tag.slice(1) : tag;if (value.includes(normalized)) {setDraft('');setDraftRejected(false);@@ -122,7 +136,8 @@ function TagPillInput({// source-mode editor (or programmatic seed) — surface them// with a destructive variant + grammar-hint tooltip so the// author can find and clean them up without context-switching.- const invalid = !isValidFrontmatterTagValue(tag);+ // Free-text mode has no grammar, so nothing to flag.+ const invalid = tagGrammar && !isValidFrontmatterTagValue(tag);const badge = (<Badge// Tags are unique within the list (dedup above) — `tag` itselfdiff --git a/packages/app/src/components/use-live-xterm-theme.ts b/packages/app/src/components/use-live-xterm-theme.tsnew file mode 100644index 000000000..ab6a7214a--- /dev/null+++ b/packages/app/src/components/use-live-xterm-theme.ts@@ -0,0 +1,45 @@+import type { ITheme } from '@xterm/xterm';+import { useEffect, useState } from 'react';+import { COLOR_THEME_ATTRIBUTE } from '@/lib/use-apply-config-color-theme';+import { computeLiveXtermTheme } from './terminal-theme';++function themesEqual(a: ITheme, b: ITheme): boolean {+ const keys = new Set([...Object.keys(a), ...Object.keys(b)] as (keyof ITheme)[]);+ for (const k of keys) if (a[k] !== b[k]) return false;+ return true;+}++/**+ * The xterm palette for the current app theme, kept live across BOTH theme+ * axes: light/dark mode (`resolvedTheme`) and the color-theme layer+ * (`data-color-theme` attribute + the runtime custom-palette `<style>` in+ * `<head>`). The mode axis arrives via the prop; the color-theme axis has no+ * React signal — it lands as DOM mutations from `useApplyConfigColorTheme` —+ * so a MutationObserver recomputes on those. Identity is stable across+ * recomputes that resolve to the same colors, so consumers can hang effects+ * off the returned object.+ */+export function useLiveXtermTheme(resolvedTheme: string | undefined): ITheme {+ const [theme, setTheme] = useState<ITheme>(() => computeLiveXtermTheme(resolvedTheme));++ useEffect(() => {+ const recompute = () => {+ const next = computeLiveXtermTheme(resolvedTheme);+ setTheme((prev) => (themesEqual(prev, next) ? prev : next));+ };+ // The mount/prop-change recompute also covers the first client render+ // (initial state may have computed before the FOUC script's tokens won).+ recompute();+ const observer = new MutationObserver(recompute);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: [COLOR_THEME_ATTRIBUTE, 'class'],+ });+ // The custom theme's palette lives in a <style> tag upserted into <head>;+ // watch its insertion/removal and text swaps.+ observer.observe(document.head, { childList: true, subtree: true, characterData: true });+ return () => observer.disconnect();+ }, [resolvedTheme]);++ return theme;+}diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsxindex 9c0bb05d0..5169fdb4d 100644--- a/packages/app/src/editor/SourceEditor.tsx+++ b/packages/app/src/editor/SourceEditor.tsx@@ -3,7 +3,12 @@ import { search } from '@codemirror/search';import { Compartment, EditorSelection, EditorState } from '@codemirror/state';import { placeholder as cmPlaceholder, EditorView, keymap } from '@codemirror/view';import type { HocuspocusProvider } from '@hocuspocus/provider';-import { createCodeFenceTracker } from '@inkeep/open-knowledge-core';+import {+ createCodeFenceTracker,+ DEFAULT_LINTER_CONFIG,+ type PersistedLinterConfig,+ toEffectiveBase,+} from '@inkeep/open-knowledge-core';import { isMacOS } from '@tiptap/core';import { basicSetup } from 'codemirror';import { useTheme } from 'next-themes';@@ -12,6 +17,7 @@ import { yCollab } from 'y-codemirror.next';import type * as Y from 'yjs';import { emitOpenAskAiComposer } from '@/components/ask-ai-composer-events';import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';import {createNestedCMExtensions,darkTheme,@@ -22,6 +28,7 @@ import { useConfigContext } from '@/lib/config-provider';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { createSourceClipboardExtension } from './clipboard/index.ts';import { type CmCacheEntry, mountCmEditor, parkCmEditor } from './editor-cache';+import { useDocLintConfig } from './lint-config-client';import { getMountId } from './mount-id-registry';import { markUserTyping } from './observers';import { publishSelectionContext, selectionSnapshotFromSource } from './selection-context';@@ -34,6 +41,7 @@ import {clearPendingSourceNavigation,consumePendingSourceNavigation,} from './source-editor-navigation';+import { createMarkdownLintExtension } from './source-lint/markdown-lint-source';import { createSourcePolishExtension } from './source-polish';import { FM_FENCE_LINE_RE } from './source-polish/view-plugin';import { attachTypingBurstDetector } from './typing-burst-detector';@@ -107,6 +115,27 @@ function applyRawMdxNavigation(view: EditorView, detail: RawMdxNavDetail): void});}+/** Jump to a lint diagnostic's 1-based line/column. Lines/columns are clamped —+ * the doc may shift between the click and this dispatch. */+function applyLintNavigation(view: EditorView, detail: LintNavDetail): void {+ const doc = view.state.doc;+ const lineNumber = Math.min(Math.max(detail.line, 1), doc.lines);+ const line = doc.line(lineNumber);+ const pos = Math.min(line.from + Math.max(0, detail.column - 1), line.to);+ view.dispatch({+ selection: EditorSelection.cursor(pos),+ // `y: 'start'` (not 'center'/'nearest'): in full-page source mode the editor+ // renders at content height with no internal scrollport, so CM measures the+ // target as already visible against its own scrollDOM and 'center'/'nearest'+ // never scroll the real ancestor (ScrollPreservingContainer) — the jump+ // silently no-ops whenever the doc overflows the viewport. Top-edge alignment+ // propagates to the ancestor and honors `scrollMargins`, matching the search+ // scrollToMatch + outline-nav fix above.+ effects: EditorView.scrollIntoView(pos, { y: 'start' }),+ });+ view.focus();+}+export function SourceEditor({docName,ytext,@@ -135,6 +164,21 @@ export function SourceEditor({const { merged } = useConfigContext();const sourceModeActiveRef = useRef(isSourceModeActive);const wordWrap = merged?.editor?.wordWrap ?? true;+ // Markdown-linter config. The EFFECTIVE config for this doc (project base ++ // native `.markdownlint.*` rules) comes from the server; fall back to the+ // project config from the config CRDT while it loads / on error. Like+ // theme/wordWrap, it's applied via a Compartment reconfigure (no remount); the+ // serialized key is the reconfigure effect's dependency.+ const { data: lintConfigData } = useDocLintConfig(docName);+ // The server `effective` already carries native-file markdownlint `rules`. The+ // persisted-config fallback omits them, so lift it through `toEffectiveBase`+ // (seeds empty `rules`) until the server config resolves.+ const linterConfig =+ lintConfigData?.effective ??+ (merged?.contentRules+ ? toEffectiveBase(merged.contentRules as unknown as PersistedLinterConfig)+ : DEFAULT_LINTER_CONFIG);+ const linterConfigKey = JSON.stringify(linterConfig);useEffect(() => {sourceModeActiveRef.current = isSourceModeActive;@@ -207,6 +251,7 @@ export function SourceEditor({const themeCompartment = new Compartment();const wordWrapCompartment = new Compartment();const placeholderCompartment = new Compartment();+ const lintCompartment = new Compartment();const state = EditorState.create({doc: ytext.toString(),extensions: [@@ -244,6 +289,7 @@ export function SourceEditor({currentDocName: resolvedDocName,}),createSourcePolishExtension(),+ lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),sourceClipboard,EditorView.updateListener.of((update) => {if (!update.selectionSet && !update.docChanged) return;@@ -308,6 +354,7 @@ export function SourceEditor({themeCompartment,wordWrapCompartment,placeholderCompartment,+ lintCompartment,};},});@@ -423,6 +470,21 @@ export function SourceEditor({});}, [placeholder]);+ // Re-apply the linter config (rule toggles + the enabled flag) via the+ // cache-entry compartment. Runs on mount too, so a cache-hit reattach+ // re-lints under the current config. `linterConfigKey` (serialized config)+ // is the dependency — the object identity is unstable.+ // biome-ignore lint/correctness/useExhaustiveDependencies: linterConfig is keyed by linterConfigKey+ useEffect(() => {+ const entry = cmEntryRef.current;+ if (!entry) return;+ entry.view.dispatch({+ effects: entry.lintCompartment.reconfigure(+ createMarkdownLintExtension(linterConfig, docName),+ ),+ });+ }, [linterConfigKey]);+// Outline panel click → jump to the Nth heading line in the CodeMirror doc.useEffect(() => {function onNav(e: Event) {@@ -437,6 +499,20 @@ export function SourceEditor({return () => window.removeEventListener(OUTLINE_NAV_EVENT, onNav);}, [docName, isSourceModeActive]);+ // Problems panel click → jump to the diagnostic's line in the CodeMirror doc.+ useEffect(() => {+ function onLintNav(e: Event) {+ const detail = (e as CustomEvent<LintNavDetail>).detail;+ if (!detail || !isSourceModeActive) return;+ const view = viewRef.current;+ if (!view) return;+ applyLintNavigation(view, detail);+ clearPendingSourceNavigation(docName);+ }+ window.addEventListener(LINT_NAV_EVENT, onLintNav);+ return () => window.removeEventListener(LINT_NAV_EVENT, onLintNav);+ }, [docName, isSourceModeActive]);+// Replays the most recent source-navigation intent once the editor chunk is// mounted and visible for this doc. This preserves first-open raw-MDX and// outline jumps even when SourceEditor was lazy-loaded off the initial path.@@ -453,6 +529,11 @@ export function SourceEditor({return;}+ if (pendingNavigation.kind === 'lint') {+ applyLintNavigation(view, pendingNavigation.detail);+ return;+ }+applyRawMdxNavigation(view, pendingNavigation.detail);}, [docName, isSourceModeActive]);diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 4b119f7f6..47e244ef8 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -33,6 +33,7 @@ import { wrapExtensionsWithTiming } from '@/lib/perf/cold-mount-instrumentation'import type { SidebarDragPayload } from '@/lib/sidebar-drag';import { useIdentity } from '../presence/identity';import { registerEditor, unregisterEditor } from './active-editor';+import { applyLintFixes } from './apply-lint-fix.ts';import { buildAwarenessUser } from './awareness-user';import { bindingStalenessGuardPlugin, type WedgeDetail } from './binding-staleness-guard';import { BubbleMenuBar } from './bubble-menu/BubbleMenuBar';@@ -46,6 +47,7 @@ import { useDocumentContext } from './DocumentContext';import { setEditorDocName } from './extensions/doc-context.ts';import { setEditorSourceMode } from './extensions/editor-mode-context.ts';import { FrozenTableHeaders } from './extensions/frozen-table-headers.ts';+import { MarkdownLintDecorations } from './extensions/markdown-lint-decorations.ts';import { sharedExtensions } from './extensions/shared.ts';import { uploadDecorationPlugin } from './image-upload/index.ts';import { getMountId } from './mount-id-registry';@@ -394,6 +396,15 @@ export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[]// mapping was supplied....guard,FrozenTableHeaders,+ // Block-level lint decorations (WYSIWYG): self-contained, keys off the PM+ // doc (not documentName), no Y observer — pool-safe like FrozenTableHeaders.+ // `getSource` snapshots Y.Text('source') per pass (a read, not an observer)+ // so WYSIWYG lints the same bytes as the Problems panel and source mode.+ MarkdownLintDecorations.configure({+ docName: provider.configuration.name ?? '',+ getSource: () => provider.document.getText('source').toString(),+ applyFix: (fixes) => applyLintFixes(provider, fixes),+ }),];}diff --git a/packages/app/src/editor/apply-lint-fix.test.ts b/packages/app/src/editor/apply-lint-fix.test.tsnew file mode 100644index 000000000..32498f815--- /dev/null+++ b/packages/app/src/editor/apply-lint-fix.test.ts@@ -0,0 +1,128 @@+import { describe, expect, test } from 'bun:test';+import type { LintDiagnostic, LintTextEdit } from '@inkeep/open-knowledge-core';+import * as Y from 'yjs';+import { applyLintFixes, collectFixes, LINT_SOURCE_FIXED_EVENT } from './apply-lint-fix.ts';++function docWith(source: string): Y.Doc {+ const doc = new Y.Doc();+ doc.getText('source').insert(0, source);+ return doc;+}+function edit(sl: number, sc: number, el: number, ec: number, newText: string): LintTextEdit {+ return {+ range: { start: { line: sl, character: sc }, end: { line: el, character: ec } },+ newText,+ };+}++// `applyLintFixes` dispatches LINT_SOURCE_FIXED_EVENT on `window` (guarded by+// `typeof window !== 'undefined'`). The unit tier has no DOM, so install a bare+// EventTarget as `window` for the duration of the assertion and restore after —+// keeping the no-DOM contract intact for every other unit-tier test.+function withWindowStub(run: (win: EventTarget) => void): void {+ const holder = globalThis as { window?: unknown };+ const prior = holder.window;+ const win = new EventTarget();+ holder.window = win;+ try {+ run(win);+ } finally {+ holder.window = prior;+ }+}++describe('applyLintFixes', () => {+ test('removes a trailing-space run (MD009-style, single-line delete)', () => {+ const doc = docWith('# Title\n\nParagraph here. \n');+ // line 2 (0-based), delete the 3 trailing spaces at chars 15..18.+ applyLintFixes({ document: doc }, [edit(2, 15, 2, 18, '')]);+ expect(doc.getText('source').toString()).toBe('# Title\n\nParagraph here.\n');+ });++ test('replaces a hard tab (MD010-style, insert replaces range)', () => {+ const doc = docWith('a\tb\n');+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' ')]);+ expect(doc.getText('source').toString()).toBe('a b\n');+ });++ test('applies multiple edits high→low without offset drift', () => {+ const doc = docWith('x \ny \n'); // trailing spaces on two lines+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')]);+ expect(doc.getText('source').toString()).toBe('x\ny\n');+ });++ test('applies multiple edits in a single Y.Doc transaction', () => {+ // Atomicity is observable as exactly one `update` event: Y.js batches all+ // mutations inside one `transact()` into a single update regardless of edit+ // count. Two edits landing in two transactions would fire twice.+ const doc = docWith('x \ny \n');+ let updates = 0;+ doc.on('update', () => {+ updates += 1;+ });+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')]);+ expect(updates).toBe(1);+ expect(doc.getText('source').toString()).toBe('x\ny\n');+ });++ test('empty fix list is a no-op returning false', () => {+ const doc = docWith('unchanged\n');+ expect(applyLintFixes({ document: doc }, [])).toBe(false);+ expect(doc.getText('source').toString()).toBe('unchanged\n');+ });++ test('pure insertion (from === to, non-empty newText) inserts without deleting', () => {+ // MD047 (missing trailing newline) produces a pure-insertion fix: an edit+ // whose range is empty (start === end) with non-empty newText.+ const doc = docWith('# Heading');+ applyLintFixes({ document: doc }, [edit(0, 9, 0, 9, '\n')]);+ expect(doc.getText('source').toString()).toBe('# Heading\n');+ });++ test('whole-line deletion (cross-line range) removes exactly one line', () => {+ // fixInfoToEdit emits a cross-line range for deleteCount === -1 (MD012+ // multiple-blank-lines): { start: { line: N, character: 0 }, end: { line:+ // N + 1, character: 0 } }. Exercises offsetOf's newline arithmetic across+ // a line boundary — a wrong byte count here would corrupt the shared Y.Text.+ const doc = docWith('# Title\n\npara\n\n\nextra blank\n');+ applyLintFixes({ document: doc }, [edit(3, 0, 4, 0, '')]);+ expect(doc.getText('source').toString()).toBe('# Title\n\npara\n\nextra blank\n');+ });++ test('fires LINT_SOURCE_FIXED_EVENT once after a non-empty fix', () => {+ let fired = 0;+ withWindowStub((win) => {+ win.addEventListener(LINT_SOURCE_FIXED_EVENT, () => {+ fired += 1;+ });+ applyLintFixes({ document: docWith('a\tb\n') }, [edit(0, 1, 0, 2, ' ')]);+ });+ expect(fired).toBe(1);+ });++ test('does not fire LINT_SOURCE_FIXED_EVENT for an empty fix list', () => {+ let fired = 0;+ withWindowStub((win) => {+ win.addEventListener(LINT_SOURCE_FIXED_EVENT, () => {+ fired += 1;+ });+ applyLintFixes({ document: docWith('unchanged\n') }, []);+ });+ expect(fired).toBe(0);+ });+});++describe('collectFixes', () => {+ const fixable: LintDiagnostic = {+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'x',+ fixes: [edit(0, 0, 0, 1, ' ')],+ };+ const plain: LintDiagnostic = { ...fixable, code: 'MD025', fixes: undefined };+ test('collectFixes flattens only fixable diagnostics', () => {+ expect(collectFixes([fixable, plain])).toHaveLength(1);+ });+});diff --git a/packages/app/src/editor/apply-lint-fix.ts b/packages/app/src/editor/apply-lint-fix.tsnew file mode 100644index 000000000..095343b04--- /dev/null+++ b/packages/app/src/editor/apply-lint-fix.ts@@ -0,0 +1,85 @@+/**+ * Apply markdownlint auto-fixes to `Y.Text('source')` from any surface (the+ * Problems panel, the WYSIWYG lint tooltip). Source mode gets this for free via+ * CodeMirror's lint `Action`; WYSIWYG and the panel have no CM view, so they+ * write the same `LintTextEdit`s straight to the source CRDT and let the bridge+ * repaint the fragment — mirroring how the property panel edits source via+ * `FORM_WRITE_ORIGIN`.+ */++import type { LintDiagnostic, LintPosition, LintTextEdit } from '@inkeep/open-knowledge-core';+import type * as Y from 'yjs';++/** Minimal provider shape — just the Y.Doc, so this stays test-friendly. */+export interface SourceWriteProvider {+ document: Y.Doc;+}++/**+ * Frozen local origin for lint auto-fix writes. Mirrors `FORM_WRITE_ORIGIN`'s+ * shape (single-root Y.Text writer; the server's Observer B recomposes the+ * fragment on sync). Distinct `context.origin` keeps the write's provenance+ * legible to any client-side observer that inspects origins.+ */+/**+ * Fired on `window` after a fix lands on `Y.Text('source')`. A source-only fix+ * (trailing spaces, hard tabs, blank-line runs) changes the source bytes but+ * NOT the rendered ProseMirror doc, so the WYSIWYG lint decoration — which+ * recomputes on PM-doc changes — would otherwise leave a stale squiggle until+ * the next edit. The decoration extension listens for this and re-lints.+ */+export const LINT_SOURCE_FIXED_EVENT = 'open-knowledge:lint-source-fixed';++const LINT_FIX_ORIGIN = Object.freeze({+ source: 'local' as const,+ skipStoreHooks: false,+ context: Object.freeze({ origin: 'lint-fix' as const }),+});++/** 0-based LSP line/character → absolute offset into `source`, clamped to the line. */+function offsetOf(source: string, pos: LintPosition): number {+ const lines = source.split('\n');+ let offset = 0;+ for (let i = 0; i < pos.line && i < lines.length; i += 1) offset += lines[i].length + 1;+ const lineLen = lines[Math.min(pos.line, lines.length - 1)]?.length ?? 0;+ return offset + Math.min(Math.max(pos.character, 0), lineLen);+}++/** Every auto-fix edit carried by `diagnostics`, in document order. */+export function collectFixes(diagnostics: readonly LintDiagnostic[]): LintTextEdit[] {+ return diagnostics.flatMap((d) => d.fixes ?? []);+}++/**+ * Apply `fixes` to the provider's `Y.Text('source')` in one transaction.+ * Offsets are resolved against the pre-fix source, then applied high→low so an+ * earlier edit never shifts a later one's coordinates (matches how CodeMirror+ * composes a lint fix's change set). Returns false when there is nothing to do.+ */+export function applyLintFixes(+ provider: SourceWriteProvider,+ fixes: readonly LintTextEdit[],+): boolean {+ if (fixes.length === 0) return false;+ const ytext = provider.document.getText('source');+ const source = ytext.toString();+ const edits = fixes+ .map((fix) => ({+ from: offsetOf(source, fix.range.start),+ to: offsetOf(source, fix.range.end),+ insert: fix.newText,+ }))+ .sort((a, b) => b.from - a.from);+ provider.document.transact(() => {+ for (const edit of edits) {+ if (edit.to > edit.from) ytext.delete(edit.from, edit.to - edit.from);+ if (edit.insert.length > 0) ytext.insert(edit.from, edit.insert);+ }+ }, LINT_FIX_ORIGIN);+ // Nudge any mounted WYSIWYG lint decoration to re-lint — a source-only fix+ // leaves the PM doc unchanged, so its PM-driven recompute never fires.+ if (typeof window !== 'undefined') {+ window.dispatchEvent(new CustomEvent(LINT_SOURCE_FIXED_EVENT));+ }+ return true;+}diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.tsindex 597cc98db..80b41203e 100644--- a/packages/app/src/editor/editor-cache.ts+++ b/packages/app/src/editor/editor-cache.ts@@ -264,6 +264,10 @@ export interface CmCacheEntry {/** Placeholder compartment embedded in `view`. Same per-entry rationale as* `themeCompartment` (lowest impact — placeholder only shows on empty docs). */placeholderCompartment: Compartment;+ /** Markdown-linter compartment embedded in `view`. Same per-entry rationale+ * as `themeCompartment` — reconfigured when the `contentRules.*` config changes so+ * a backgrounded doc re-lints under the new rules on reattach. */+ lintCompartment: Compartment;scrollTop: number;/** See `TiptapCacheEntry.hadFocus`. */hadFocus: boolean;@@ -300,6 +304,8 @@ interface CmFactoryResult {wordWrapCompartment: Compartment;/** Placeholder compartment embedded in `view`. See `CmCacheEntry.placeholderCompartment`. */placeholderCompartment: Compartment;+ /** Lint compartment embedded in `view`. See `CmCacheEntry.lintCompartment`. */+ lintCompartment: Compartment;}type CmFactory = (container: HTMLElement) => CmFactoryResult;@@ -946,6 +952,7 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {themeCompartment: fresh.themeCompartment,wordWrapCompartment: fresh.wordWrapCompartment,placeholderCompartment: fresh.placeholderCompartment,+ lintCompartment: fresh.lintCompartment,scrollTop: 0,hadFocus: false,activeMountKey: docName,@@ -1014,6 +1021,7 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {themeCompartment: fresh.themeCompartment,wordWrapCompartment: fresh.wordWrapCompartment,placeholderCompartment: fresh.placeholderCompartment,+ lintCompartment: fresh.lintCompartment,scrollTop: 0,hadFocus: false,activeMountKey: docName,diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.tsnew file mode 100644index 000000000..e36816931--- /dev/null+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts@@ -0,0 +1,168 @@+/**+ * Unit tests for the WYSIWYG lint→block mapping. `mapDiagnosticsToBlocks`+ * groups source-line diagnostics by the top-level mdast block they fall in,+ * which is what the plugin then maps onto top-level PM nodes (1:1 by the+ * bridge invariant — the fragment derives from parse of the same Y.Text+ * source the diagnostics were linted against).+ */++import { describe, expect, test } from 'bun:test';+import {+ sharedExtensions as coreExtensions,+ type LintDiagnostic,+ MarkdownManager,+} from '@inkeep/open-knowledge-core';+import {+ blockIndexForLine,+ computeSourceBlockSpans,+ mapDiagnosticsToBlocks,+} from './markdown-lint-decorations.ts';++const md = new MarkdownManager({ extensions: coreExtensions });++function diag(line: number, over: Partial<LintDiagnostic> = {}): LintDiagnostic {+ // `line` is 1-based (the mdast/source convention these tests reason in).+ return {+ range: { start: { line: line - 1, character: 0 }, end: { line: line - 1, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ ...over,+ };+}++describe('mapDiagnosticsToBlocks', () => {+ test('returns an empty map for no diagnostics', () => {+ expect(mapDiagnosticsToBlocks('# A\n\nbody\n', [], md).size).toBe(0);+ });++ // body:+ // 1: # Heading+ // 2:+ // 3: First paragraph.+ // 4:+ // 5: Second paragraph.+ const body = '# Heading\n\nFirst paragraph.\n\nSecond paragraph.\n';++ test('maps a diagnostic to the block index that contains its line', () => {+ // line 1 → block 0 (heading), line 3 → block 1, line 5 → block 2.+ const byBlock = mapDiagnosticsToBlocks(body, [diag(1), diag(3), diag(5)], md);+ expect([...byBlock.keys()].sort((a, b) => a - b)).toEqual([0, 1, 2]);+ expect(byBlock.get(0)?.[0]?.range.start.line).toBe(0);+ expect(byBlock.get(1)?.[0]?.range.start.line).toBe(2);+ expect(byBlock.get(2)?.[0]?.range.start.line).toBe(4);+ });++ test('groups multiple diagnostics on the same block', () => {+ const byBlock = mapDiagnosticsToBlocks(body, [diag(3), diag(3, { code: 'MD009' })], md);+ expect(byBlock.size).toBe(1);+ expect(byBlock.get(1)).toHaveLength(2);+ });++ test('maps any line within a multi-line block to that one block', () => {+ // A fenced code block spans several source lines; a diagnostic on any of+ // them belongs to the single code block.+ const codeBody = 'intro para\n\n```\nline a\nline b\n```\n';+ // lines: 1 para, 3-6 code fence+ const byBlock = mapDiagnosticsToBlocks(codeBody, [diag(4)], md);+ expect(byBlock.size).toBe(1);+ // block 0 = paragraph, block 1 = code+ expect(byBlock.has(1)).toBe(true);+ });++ test('anchors a between-block diagnostic (blank-line run) to the NEXT block', () => {+ // line 2 is the blank line between heading and paragraph — where rules+ // like MD012 (multiple blank lines) report. It anchors to the following+ // block instead of being dropped.+ const byBlock = mapDiagnosticsToBlocks(body, [diag(2, { code: 'MD012' })], md);+ expect(byBlock.size).toBe(1);+ expect(byBlock.has(1)).toBe(true);+ });++ test('anchors a trailing diagnostic (past the last block) to the LAST block', () => {+ // e.g. MD047 (file should end with a single newline) on a trailing blank.+ const byBlock = mapDiagnosticsToBlocks(body, [diag(6, { code: 'MD047' })], md);+ expect(byBlock.size).toBe(1);+ expect(byBlock.has(2)).toBe(true);+ });++ test('keeps a loose list as a single block (line-span, not blank-line split)', () => {+ // A loose list has blank lines between items but is ONE top-level block —+ // both item diagnostics must land on the same block index.+ const listBody = '- one\n\n- two\n\n- three\n';+ const byBlock = mapDiagnosticsToBlocks(listBody, [diag(1), diag(5)], md);+ expect(byBlock.size).toBe(1);+ expect(byBlock.get(0)).toHaveLength(2);+ });++ // source with frontmatter:+ // 1: ---+ // 2: title: X+ // 3: ---+ // 4: # Heading+ // 5:+ // 6: Paragraph.+ const fmSource = '---\ntitle: X\n---\n# Heading\n\nParagraph.\n';++ test('shifts block mapping under a frontmatter region (full-source lines)', () => {+ // Diagnostics carry FULL-source lines (markdownlint skips the FM region+ // itself but keeps absolute numbering): line 4 → block 0, line 6 → block 1.+ const byBlock = mapDiagnosticsToBlocks(fmSource, [diag(4), diag(6)], md);+ expect([...byBlock.keys()].sort((a, b) => a - b)).toEqual([0, 1]);+ });++ test('skips a diagnostic inside the frontmatter region (no WYSIWYG anchor)', () => {+ const byBlock = mapDiagnosticsToBlocks(fmSource, [diag(2)], md);+ expect(byBlock.size).toBe(0);+ });+});++describe('computeSourceBlockSpans', () => {+ test('spans are in full-source coordinates when frontmatter is present', () => {+ const { spans, fmLineCount } = computeSourceBlockSpans(+ '---\ntitle: X\n---\n# Heading\n\nParagraph.\n',+ md,+ );+ expect(fmLineCount).toBe(3);+ expect(spans).toEqual([+ { start: 4, end: 4 },+ { start: 6, end: 6 },+ ]);+ });++ test('no frontmatter → zero offset', () => {+ const { spans, fmLineCount } = computeSourceBlockSpans('# H\n\nP\n', md);+ expect(fmLineCount).toBe(0);+ expect(spans[0]).toEqual({ start: 1, end: 1 });+ });++ test('empty body → no spans', () => {+ expect(computeSourceBlockSpans('', md).spans).toHaveLength(0);+ });+});++describe('blockIndexForLine', () => {+ const spans = [+ { start: 1, end: 1 },+ { start: 3, end: 6 },+ { start: 8, end: 8 },+ ];++ test('line inside a span → that block', () => {+ expect(blockIndexForLine(spans, 4)).toBe(1);+ });++ test('line in a gap → the following block', () => {+ expect(blockIndexForLine(spans, 2)).toBe(1);+ expect(blockIndexForLine(spans, 7)).toBe(2);+ });++ test('line past the last span → the last block', () => {+ expect(blockIndexForLine(spans, 12)).toBe(2);+ });++ test('no spans → null', () => {+ expect(blockIndexForLine([], 1)).toBeNull();+ });+});diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.tsnew file mode 100644index 000000000..9546b3688--- /dev/null+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts@@ -0,0 +1,651 @@+/**+ * WYSIWYG markdown-lint decorations.+ *+ * Source mode shows lint diagnostics inline via `@codemirror/lint`. WYSIWYG has+ * no source lines to anchor to, so this extension marks the *block* each+ * diagnostic falls in: it lints the SAME `Y.Text('source')` bytes the Problems+ * panel and source mode lint (via the `getSource` option), re-parses the body+ * region to mdast for top-level block line spans, and maps each diagnostic's+ * source line onto the corresponding top-level PM node via a `Decoration.node`.+ *+ * Linting the raw source (not a re-serialization of the PM doc) is load-bearing:+ * serialization normalizes away exactly the byte-level constructs many rules+ * flag (hard tabs, trailing spaces, list-marker style, blank-line runs), so a+ * serialize-then-lint pass can never see them and WYSIWYG would silently show+ * fewer problems than the panel. The mdast children of `parse(body)` line up+ * 1:1 with the doc's top-level nodes by the bridge invariant (Y.Text is truth;+ * the fragment derives via parse) — a transient mid-drain mismatch is detected+ * by block-count comparison and the pass is dropped, not misanchored.+ *+ * Pool-safety: like `chunk-wrapper-decoration`, the plugin keys off `state.doc`+ * (PM structure), never `documentName`, and adds NO Y.js observer (the CLAUDE.md+ * STOP rule against unbounded observers in the Activity subtree). It recomputes+ * on a trailing debounce after real doc edits and on lint-config changes; the+ * heavy lint pass never runs on the keystroke hot path. Local-edit drain-back+ * latency (PM change → Observer A → Y.Text) is covered by a source-changed+ * re-check at the end of each pass rather than an observer.+ */++import { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom';+import {+ sharedExtensions as coreExtensions,+ type LintDiagnostic,+ type LinterConfig,+ type LintTextEdit,+ lintDocument,+ MarkdownManager,+ stripFrontmatter,+} from '@inkeep/open-knowledge-core';+import { t } from '@lingui/core/macro';+import { Extension } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state';+import { Decoration, DecorationSet } from '@tiptap/pm/view';+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';+import { collectFixes, LINT_SOURCE_FIXED_EVENT } from '@/editor/apply-lint-fix';+import {+ clearPendingSourceNavigation,+ peekPendingSourceNavigation,+} from '@/editor/source-editor-navigation';+import { fetchEffectiveLintConfig, subscribeToLintConfigChanged } from '../lint-config-client';++const markdownLintDecorationKey = new PluginKey<DecorationSet>('markdownLintDecorations');++/** CSS classes consumed by `.ProseMirror .ok-lint-block*` in globals.css. */+const OK_LINT_BLOCK_CLASS = 'ok-lint-block';+const OK_LINT_BLOCK_ERROR_CLASS = 'ok-lint-block-error';+// Modifier for textless blocks (thematic break, image) — a wavy text-decoration+// is invisible with no text to underline, so these get an outline instead.+const OK_LINT_BLOCK_ATOM_CLASS = 'ok-lint-block-atom';++const RECOMPUTE_DEBOUNCE_MS = 400;++/** 1-based inclusive line spans of top-level body blocks, in full-source coordinates. */+export interface SourceBlockSpans {+ spans: { start: number; end: number }[];+ /** Lines the frontmatter region occupies at the top of the source (0 when none). */+ fmLineCount: number;+}++/**+ * Top-level block line spans for a full `Y.Text('source')` snapshot. The body+ * region (after the FM fence) is parsed to mdast; spans are shifted back into+ * full-source coordinates so lint diagnostics (which carry full-source lines —+ * markdownlint skips the FM region itself) index into them directly.+ */+export function computeSourceBlockSpans(source: string, md: MarkdownManager): SourceBlockSpans {+ const { frontmatter, body } = stripFrontmatter(source);+ const fmLineCount = frontmatter === '' ? 0 : frontmatter.split('\n').length - 1;+ const spans = md.parseToMdast(body).children.map((child) => ({+ start: (child.position?.start.line ?? Number.POSITIVE_INFINITY) + fmLineCount,+ end: (child.position?.end.line ?? Number.NEGATIVE_INFINITY) + fmLineCount,+ }));+ return { spans, fmLineCount };+}++/**+ * Map a 1-based full-source line to a top-level block index. Lines inside a+ * block map to it; between-block lines (blank-line runs — where rules like+ * MD012 report) anchor to the NEXT block; lines past the last block anchor to+ * the last one. Null only when there are no blocks at all.+ */+export function blockIndexForLine(spans: SourceBlockSpans['spans'], line: number): number | null {+ const containing = spans.findIndex((s) => line >= s.start && line <= s.end);+ if (containing >= 0) return containing;+ const following = spans.findIndex((s) => s.start > line);+ if (following >= 0) return following;+ return spans.length > 0 ? spans.length - 1 : null;+}++/**+ * Group diagnostics by the index of the top-level block they fall in.+ * `source` is the full document text (frontmatter included); diagnostics in+ * the FM region are skipped — they have no WYSIWYG anchor (the property panel+ * owns frontmatter) and stay visible in the Problems panel.+ */+export function mapDiagnosticsToBlocks(+ source: string,+ diagnostics: LintDiagnostic[],+ md: MarkdownManager,+): Map<number, LintDiagnostic[]> {+ const byBlock = new Map<number, LintDiagnostic[]>();+ if (diagnostics.length === 0) return byBlock;+ const { spans, fmLineCount } = computeSourceBlockSpans(source, md);+ for (const diagnostic of diagnostics) {+ // mdast positions are 1-based; the diagnostic range is 0-based LSP.+ const line = diagnostic.range.start.line + 1;+ if (fmLineCount > 0 && line <= fmLineCount) continue;+ const index = blockIndexForLine(spans, line);+ if (index === null) continue;+ const existing = byBlock.get(index);+ if (existing) existing.push(diagnostic);+ else byBlock.set(index, [diagnostic]);+ }+ return byBlock;+}++/**+ * Top-level child count comparable against body block spans. A doc whose last+ * block isn't a paragraph renders with a trailing empty paragraph (the+ * type-here affordance below a final heading/list) that has NO source+ * counterpart — parse of the source never yields an empty paragraph. Without+ * this allowance the span↔doc count comparison fails PERMANENTLY on+ * heading-final docs, silently disabling decorations and navigation.+ */+function comparableChildCount(doc: PmNode): number {+ const last = doc.childCount > 0 ? doc.child(doc.childCount - 1) : null;+ const trailingEmptyParagraph =+ last !== null && last.type.name === 'paragraph' && last.content.size === 0;+ return trailingEmptyParagraph ? doc.childCount - 1 : doc.childCount;+}++/** DOM attribute that carries a block's diagnostic lines for the hover tooltip. */+const LINT_TOOLTIP_ATTR = 'data-ok-lint';+/** Marks a decorated block whose diagnostics carry auto-fixable edits. */+const LINT_FIXABLE_ATTR = 'data-ok-lint-fixable';++/**+ * Build a node decoration per top-level block that carries ≥1 diagnostic, plus+ * a block-offset → auto-fix-edits map so the hover tooltip's Fix button can+ * apply a block's fixes without re-linting.+ */+function buildDecorationSet(+ doc: PmNode,+ byBlock: Map<number, LintDiagnostic[]>,+): { set: DecorationSet; fixesByOffset: Map<number, LintTextEdit[]> } {+ const fixesByOffset = new Map<number, LintTextEdit[]>();+ if (byBlock.size === 0) return { set: DecorationSet.empty, fixesByOffset };+ const decorations: Decoration[] = [];+ let blockIndex = 0;+ doc.forEach((node, offset) => {+ const diagnostics = byBlock.get(blockIndex);+ blockIndex += 1;+ if (!diagnostics || diagnostics.length === 0) return;+ const hasError = diagnostics.some((d) => d.severity === 'error');+ // One line per diagnostic; the hover tooltip renders these with line breaks.+ const tooltip = diagnostics.map((d) => `${d.source}/${d.code}: ${d.message}`).join('\n');+ // Textless top-level blocks (thematic break, block image) render no inline+ // text, so the base class's wavy text-decoration paints nothing — flag them+ // for the outline treatment in globals.css. The base class stays on so the+ // hover tooltip's `.ok-lint-block` lookup still matches.+ const classNames = [OK_LINT_BLOCK_CLASS];+ if (node.textContent.length === 0) classNames.push(OK_LINT_BLOCK_ATOM_CLASS);+ if (hasError) classNames.push(OK_LINT_BLOCK_ERROR_CLASS);+ const attrs: Record<string, string> = {+ class: classNames.join(' '),+ [LINT_TOOLTIP_ATTR]: tooltip,+ };+ const fixes = collectFixes(diagnostics);+ if (fixes.length > 0) {+ attrs[LINT_FIXABLE_ATTR] = '1';+ fixesByOffset.set(offset, fixes);+ }+ decorations.push(Decoration.node(offset, offset + node.nodeSize, attrs));+ });+ return { set: DecorationSet.create(doc, decorations), fixesByOffset };+}++/**+ * A hover tooltip for decorated lint blocks. The native `title` attribute is+ * slow, unstyled, and clipped; this renders an OK-popover-styled box on+ * pointer-enter of any `.ok-lint-block`, positioned just above the block. When+ * the block has auto-fixable diagnostics and `applyFix` is wired, it also shows+ * a Fix button (mouse-only convenience — the Problems panel is the+ * keyboard-accessible fix path). The tooltip stays open while the pointer is+ * over it so the button is reachable.+ */+function createLintTooltip(+ view: { dom: HTMLElement },+ opts: {+ getFixes: (block: HTMLElement) => LintTextEdit[];+ applyFix?: (fixes: LintTextEdit[]) => void;+ },+): { destroy: () => void } {+ const tooltip = document.createElement('div');+ tooltip.className = 'ok-lint-tooltip';+ // Deliberately no `role="tooltip"`: pointer-triggered from non-focusable text+ // ranges with no aria-describedby association. The Problems panel is the+ // keyboard-accessible surface for the same diagnostics + fixes.+ tooltip.hidden = true;+ const message = document.createElement('div');+ message.className = 'ok-lint-tooltip-message';+ tooltip.appendChild(message);+ const fixButton = document.createElement('button');+ fixButton.type = 'button';+ fixButton.className = 'ok-lint-tooltip-fix';+ fixButton.hidden = true;+ tooltip.appendChild(fixButton);+ // Body-appended, viewport-fixed: positioned by floating-ui against a virtual+ // reference at the pointer (below), so it survives editor scroll containers.+ tooltip.style.position = 'fixed';+ tooltip.style.top = '0';+ tooltip.style.left = '0';+ document.body.appendChild(tooltip);++ let current: HTMLElement | null = null;+ let overTooltip = false;+ let hideTimer: ReturnType<typeof setTimeout> | null = null;+ let stopAutoUpdate: (() => void) | null = null;+ // Anchor point for positioning — the pointer location where the tooltip was+ // shown. Anchoring to the cursor (not the block's top-left corner) keeps the+ // tooltip next to the text the user is hovering, even in a tall block.+ let anchorX = 0;+ let anchorY = 0;+ const virtualEl = {+ getBoundingClientRect: () =>+ ({+ width: 0,+ height: 0,+ x: anchorX,+ y: anchorY,+ top: anchorY,+ left: anchorX,+ right: anchorX,+ bottom: anchorY,+ }) as DOMRect,+ };++ function cancelHide() {+ if (hideTimer !== null) {+ clearTimeout(hideTimer);+ hideTimer = null;+ }+ }++ function reallyHide() {+ cancelHide();+ current = null;+ tooltip.hidden = true;+ stopAutoUpdate?.();+ stopAutoUpdate = null;+ }++ // Grace delay: let the pointer traverse the small gap from the text to the+ // tooltip (to click Fix) without the tooltip vanishing mid-move.+ function scheduleHide() {+ if (overTooltip) return;+ cancelHide();+ hideTimer = setTimeout(reallyHide, 140);+ }++ function position() {+ computePosition(virtualEl, tooltip, {+ placement: 'top-start',+ middleware: [offset(6), flip(), shift({ padding: 8 })],+ })+ .then(({ x, y }) => {+ if (tooltip.isConnected) {+ tooltip.style.left = `${x}px`;+ tooltip.style.top = `${y}px`;+ }+ })+ .catch((err) => {+ if (tooltip.isConnected) {+ console.warn('[markdown-lint] tooltip computePosition failed', err);+ }+ });+ }++ function show(target: HTMLElement) {+ const text = target.getAttribute(LINT_TOOLTIP_ATTR);+ if (!text) {+ scheduleHide();+ return;+ }+ cancelHide();+ current = target;+ message.textContent = text;+ const fixes = opts.applyFix ? opts.getFixes(target) : [];+ if (fixes.length > 0 && opts.applyFix) {+ fixButton.hidden = false;+ fixButton.textContent = t`Fix`;+ fixButton.onclick = () => {+ opts.applyFix?.(fixes);+ overTooltip = false;+ reallyHide();+ };+ } else {+ fixButton.hidden = true;+ fixButton.onclick = null;+ }+ tooltip.hidden = false;+ stopAutoUpdate?.();+ // autoUpdate runs position() synchronously on setup (content already set) and+ // re-runs it on scroll/resize.+ stopAutoUpdate = autoUpdate(virtualEl, tooltip, position);+ }++ function onOver(event: Event) {+ const pe = event as PointerEvent;+ const target = event.target as HTMLElement | null;+ const block = target?.closest<HTMLElement>(`.${OK_LINT_BLOCK_CLASS}`) ?? null;+ if (block) {+ if (block !== current) {+ anchorX = pe.clientX;+ anchorY = pe.clientY;+ show(block);+ } else {+ // Still over the same block — keep it alive (cancel any pending hide).+ cancelHide();+ }+ } else if (current) {+ scheduleHide();+ }+ }++ function onOut(event: Event) {+ const related = (event as PointerEvent).relatedTarget as HTMLElement | null;+ // Keep the tooltip open when the pointer moves onto it (so Fix is clickable).+ if (related === tooltip || related?.closest('.ok-lint-tooltip')) {+ cancelHide();+ return;+ }+ if (!related?.closest(`.${OK_LINT_BLOCK_CLASS}`)) scheduleHide();+ }++ function onTooltipEnter() {+ overTooltip = true;+ cancelHide();+ }+ function onTooltipLeave(event: Event) {+ overTooltip = false;+ const related = (event as PointerEvent).relatedTarget as HTMLElement | null;+ if (related !== current && !related?.closest(`.${OK_LINT_BLOCK_CLASS}`)) scheduleHide();+ }++ tooltip.addEventListener('pointerenter', onTooltipEnter);+ tooltip.addEventListener('pointerleave', onTooltipLeave);+ view.dom.addEventListener('pointerover', onOver);+ view.dom.addEventListener('pointerout', onOut);++ return {+ destroy() {+ cancelHide();+ stopAutoUpdate?.();+ view.dom.removeEventListener('pointerover', onOver);+ view.dom.removeEventListener('pointerout', onOut);+ tooltip.remove();+ },+ };+}++interface MarkdownLintDecorationsOptions {+ docName: string;+ /**+ * Snapshot of the full `Y.Text('source')` text — the SAME bytes the Problems+ * panel and source mode lint. When absent (provider-less harnesses), the+ * pass falls back to serializing the PM doc, which sees only normalized+ * markdown (byte-level violations invisible).+ */+ getSource?: () => string;+ /**+ * Apply a block's auto-fix edits to `Y.Text('source')` (wired to the active+ * provider). Absent in provider-less harnesses — the tooltip then shows no+ * Fix button.+ */+ applyFix?: (fixes: LintTextEdit[]) => void;+}++/**+ * TipTap extension that surfaces markdown-lint violations as block-level node+ * decorations in the WYSIWYG editor. Self-contained: fetches its own effective+ * config and recomputes off the PM doc — no React data push.+ */+export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsOptions>({+ name: 'markdownLintDecorations',++ addOptions() {+ return { docName: '', getSource: undefined, applyFix: undefined };+ },++ addProseMirrorPlugins() {+ const { docName, getSource, applyFix } = this.options;+ // One serializer/parser for this editor's lifetime — same extension set the+ // bridge uses, so serialize→lint→parseToMdast matches the rendered content.+ const md = new MarkdownManager({ extensions: coreExtensions });++ return [+ new Plugin<DecorationSet>({+ key: markdownLintDecorationKey,+ state: {+ init: () => DecorationSet.empty,+ apply(tr, old) {+ const next = tr.getMeta(markdownLintDecorationKey) as DecorationSet | undefined;+ if (next) return next;+ return old.map(tr.mapping, tr.doc);+ },+ },+ props: {+ decorations(state) {+ return markdownLintDecorationKey.getState(state) ?? null;+ },+ },+ view(view) {+ let config: LinterConfig | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let destroyed = false;+ // Bounded retry for the bridge-invariant mismatch drop below: a+ // transient PM↔Y.Text divergence usually settles within one debounce+ // window, but nothing re-schedules a pass when the drain-back lands+ // without changing the PM doc — so the drop itself retries, capped+ // so a persistent divergence can't loop the lint pass forever.+ let mismatchRetries = 0;+ // Block-offset → auto-fix edits for the current pass; the hover+ // tooltip's Fix button reads it via posAtDOM.+ let currentFixes = new Map<number, LintTextEdit[]>();++ async function recompute() {+ if (destroyed) return;+ const sourceAtStart = getSource?.() ?? null;+ const outcome = config?.enabled+ ? await computeSet(config)+ : // Clear any stale decorations when disabled / config absent.+ {+ kind: 'ok' as const,+ set: DecorationSet.empty,+ fixesByOffset: new Map<number, LintTextEdit[]>(),+ };+ // The lint pass is async: bail if the plugin died or the doc moved+ // while it ran (a stale set's positions no longer fit; the edit+ // that moved the doc has already scheduled the next pass).+ if (destroyed || outcome.kind === 'stale') return;+ if (outcome.kind === 'mismatch') {+ if (mismatchRetries < 2) {+ mismatchRetries += 1;+ schedule();+ }+ return;+ }+ mismatchRetries = 0;+ currentFixes = outcome.fixesByOffset;+ const set = outcome.set;+ // Skip a no-op empty→empty dispatch. The common mount path (config+ // still loading, or no server) would otherwise fire a spurious+ // meta transaction in the editor's construct→mount window, which+ // can disturb the pre-warm mapping currency (walk-currency).+ const current = markdownLintDecorationKey.getState(view.state) ?? DecorationSet.empty;+ if (set.find().length > 0 || current.find().length > 0) {+ view.dispatch(view.state.tr.setMeta(markdownLintDecorationKey, set));+ }+ // A cross-doc project-scope click banks a pending intent and opens+ // this doc WITHOUT dispatching the live event (the event carries no+ // docName). Replay it now that this 'ok' outcome guarantees the doc+ // is hydrated and block-mapped (decorations painted just above);+ // clearing on success stops later edit-triggered passes from+ // re-scrolling. Mirrors SourceEditor's mount-time replay.+ if (config?.enabled) {+ const pending = peekPendingSourceNavigation(docName);+ if (pending?.kind === 'lint' && scrollToLintBlock(pending.detail)) {+ clearPendingSourceNavigation(docName);+ }+ }+ // Local W1 edits reach Y.Text via Observer A after the PM change+ // that scheduled this pass — if the source moved while we linted,+ // run once more so decorations settle on the current bytes (the+ // no-observer counterpart to useDocDiagnostics' Y.Text observe).+ if (sourceAtStart !== null && !destroyed && getSource?.() !== sourceAtStart) {+ schedule();+ }+ }++ type ComputeOutcome =+ | { kind: 'ok'; set: DecorationSet; fixesByOffset: Map<number, LintTextEdit[]> }+ | { kind: 'stale' }+ | { kind: 'mismatch' };++ async function computeSet(activeConfig: LinterConfig): Promise<ComputeOutcome> {+ const doc = view.state.doc;+ const source = getSource?.() ?? md.serialize(doc.toJSON());+ const diagnostics = await lintDocument(source, activeConfig, docName);+ if (!view.state.doc.eq(doc)) return { kind: 'stale' };+ const { spans } = computeSourceBlockSpans(source, md);+ // Bridge-invariant guard: body mdast children ↔ PM top-level nodes+ // (minus the sourceless trailing empty paragraph) must be 1:1 for+ // the index mapping to anchor correctly. A mismatch is a transient+ // mid-drain snapshot — drop the pass (keep current decorations)+ // rather than misanchor.+ if (spans.length !== comparableChildCount(doc)) return { kind: 'mismatch' };+ const byBlock = mapDiagnosticsToBlocks(source, diagnostics, md);+ return { kind: 'ok', ...buildDecorationSet(doc, byBlock) };+ }++ function schedule() {+ if (timer) clearTimeout(timer);+ // A rejected pass (serialize can throw on exotic docs) must not be+ // swallowed: log it, and leave decorations to the next scheduled+ // pass rather than silently going stale for the view's lifetime.+ timer = setTimeout(() => {+ recompute().catch((err) => {+ console.warn('[markdown-lint] decoration pass failed', err);+ });+ }, RECOMPUTE_DEBOUNCE_MS);+ }++ let configGeneration = 0;++ async function loadConfigAndRecompute() {+ // Config fetches can resolve out of order (two rapid config-changed+ // events); only the newest load may install its result — a stale+ // resolution would pin an outdated config until the next event.+ const generation = ++configGeneration;+ const next = await fetchEffectiveLintConfig(docName);+ if (destroyed || generation !== configGeneration) return;+ config = next;+ await recompute();+ }+ // Same rejection discipline as schedule(): never swallow a failed pass.+ const startPass = () => {+ loadConfigAndRecompute().catch((err) => {+ console.warn('[markdown-lint] config load/lint pass failed', err);+ });+ };++ /**+ * Problems-panel row click (WYSIWYG counterpart of SourceEditor's+ * handler): map the diagnostic's source line to its top-level block,+ * place the caret there, and scroll it into view. Only the VISIBLE+ * editor consumes — pool-hidden editors and the WYSIWYG half of a+ * source-mode doc are `display: none` (offsetParent null) and must+ * not move selection. The event carries no docName; visibility IS the+ * doc identity.+ *+ * Scroll uses the block's native `Element.scrollIntoView`, NOT the+ * transaction's `.scrollIntoView()` — the same choice as TiptapEditor's+ * outline-click and wiki-link navigation. ProseMirror's own scroll+ * ignores the scroll container's `scroll-pt-14` toolbar inset (that's+ * CSS scroll-padding, honored only by native scrollIntoView), so a+ * transaction scroll either no-ops against OK's custom scroll+ * container or lands the block behind the toolbar. `view.focus()`+ * focuses without scrolling (prosemirror-view's focusPreventScroll),+ * so the native scroll is authoritative.+ */+ function scrollToLintBlock(detail: LintNavDetail): boolean {+ if (!view.dom.isConnected || view.dom.offsetParent === null) return false;+ const source = getSource?.() ?? md.serialize(view.state.doc.toJSON());+ const { spans, fmLineCount } = computeSourceBlockSpans(source, md);+ if (spans.length !== comparableChildCount(view.state.doc)) return false;+ // Frontmatter diagnostics have no WYSIWYG anchor (property panel+ // owns that region) — leave the banked source-mode intent alive.+ if (fmLineCount > 0 && detail.line <= fmLineCount) return false;+ const index = blockIndexForLine(spans, detail.line);+ if (index === null) return false;+ let blockOffset = -1;+ view.state.doc.forEach((_node, offset, i) => {+ if (i === index) blockOffset = offset;+ });+ if (blockOffset < 0) return false;+ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.near(view.state.doc.resolve(blockOffset + 1)),+ ),+ );+ view.focus();+ const blockDom = view.nodeDOM(blockOffset);+ if (blockDom instanceof HTMLElement) {+ blockDom.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+ return true;+ }++ // Live Problems-row click for the OPEN doc. The cross-doc project+ // path banks its intent instead (replayed in recompute on mount).+ function onLintNav(event: Event) {+ const detail = (event as CustomEvent<LintNavDetail>).detail;+ if (!detail || destroyed) return;+ // Consumed here — a later flip to source mode must not replay it.+ if (scrollToLintBlock(detail)) clearPendingSourceNavigation(docName);+ }++ startPass();+ const unsubscribe = subscribeToLintConfigChanged(startPass);+ // Resolve a decorated block's DOM element to its auto-fix edits via the+ // current pass's offset map (posAtDOM → top-level block start offset).+ const getFixes = (block: HTMLElement): LintTextEdit[] => {+ if (block.getAttribute(LINT_FIXABLE_ATTR) !== '1' || currentFixes.size === 0) return [];+ let pos: number;+ try {+ pos = view.posAtDOM(block, 0);+ } catch (err) {+ // posAtDOM throws on detached/partially-recycled DOM. Returning []+ // suppresses the Fix button (the correct fallback), but log so a+ // systematic failure (e.g. after a ProseMirror upgrade) leaves a+ // signal instead of a silently dark Fix surface — matching the+ // sibling recompute/startPass catches.+ console.warn(+ '[markdown-lint] posAtDOM failed on lint block; Fix button suppressed',+ err,+ );+ return [];+ }+ const clamped = Math.min(Math.max(pos, 0), view.state.doc.content.size);+ const resolved = view.state.doc.resolve(clamped);+ const offset = resolved.depth >= 1 ? resolved.before(1) : 0;+ return currentFixes.get(offset) ?? [];+ };+ const tooltip = createLintTooltip(view, { getFixes, applyFix });+ window.addEventListener(LINT_NAV_EVENT, onLintNav);+ // Re-lint after a source-only auto-fix (which leaves the PM doc — and+ // thus the update() hook below — untouched) so the stale squiggle clears.+ const onSourceFixed = () => {+ if (!destroyed) schedule();+ };+ window.addEventListener(LINT_SOURCE_FIXED_EVENT, onSourceFixed);++ return {+ update(updatedView, prevState) {+ if (!updatedView.state.doc.eq(prevState.doc)) schedule();+ },+ destroy() {+ destroyed = true;+ if (timer) clearTimeout(timer);+ unsubscribe();+ tooltip.destroy();+ window.removeEventListener(LINT_NAV_EVENT, onLintNav);+ window.removeEventListener(LINT_SOURCE_FIXED_EVENT, onSourceFixed);+ },+ };+ },+ }),+ ];+ },+});diff --git a/packages/app/src/editor/lint-config-client.ts b/packages/app/src/editor/lint-config-client.tsnew file mode 100644index 000000000..8c4a20a31--- /dev/null+++ b/packages/app/src/editor/lint-config-client.ts@@ -0,0 +1,170 @@+/**+ * Client for the lint-config endpoints. The editor reads the doc's EFFECTIVE+ * config (project base + native `.markdownlint.*` rules) to lint with; the+ * Settings GUI reads the project config and writes native markdownlint rules.+ * A window event lets a config write re-lint the open editor live.+ */++import {+ type LintAuditResponse,+ LintAuditResponseSchema,+ type LintConfigResponse,+ LintConfigResponseSchema,+ type LinterConfig,+ type MarkdownlintRuleWriteValue,+} from '@inkeep/open-knowledge-core';+import { useEffect, useState } from 'react';++const LINT_CONFIG_CHANGED_EVENT = 'open-knowledge:lint-config-changed';++/** Signal that the lint config changed so open editors re-fetch + re-lint. */+export function emitLintConfigChanged(): void {+ window.dispatchEvent(new CustomEvent(LINT_CONFIG_CHANGED_EVENT));+}++/** Subscribe to lint-config changes (re-fetch + re-lint). */+export function subscribeToLintConfigChanged(onChange: () => void): () => void {+ const listener = () => onChange();+ window.addEventListener(LINT_CONFIG_CHANGED_EVENT, listener);+ return () => window.removeEventListener(LINT_CONFIG_CHANGED_EVENT, listener);+}++/** GET the effective lint config (optionally for a doc). null on any failure. */+async function fetchLintConfig(docName?: string): Promise<LintConfigResponse | null> {+ try {+ const query = docName !== undefined ? `?doc=${encodeURIComponent(docName)}` : '';+ const res = await fetch(`/api/lint/config${query}`);+ if (!res.ok) return null;+ const body = await res.json().catch(() => null);+ const parsed = LintConfigResponseSchema.safeParse(body);+ if (!parsed.success) {+ // Distinguish server/client schema drift from "server not running":+ // both fall back to defaults, but drift deserves a diagnostic.+ console.warn('[lint] lint-config response failed schema validation', parsed.error.issues);+ return null;+ }+ return parsed.data;+ } catch {+ return null;+ }+}++/**+ * Fetch just the EFFECTIVE config for a doc — the config the WYSIWYG decoration+ * plugin lints with. null on any failure.+ */+export async function fetchEffectiveLintConfig(docName: string): Promise<LinterConfig | null> {+ const response = await fetchLintConfig(docName);+ return response?.effective ?? null;+}++/**+ * GET a project-wide (or sub-path) lint audit. Returns every in-scope doc that+ * has at least one diagnostic, plus file/error/warning counts. null on failure.+ */+export async function runLintAudit(targetPath?: string): Promise<LintAuditResponse | null> {+ try {+ const query = targetPath ? `?path=${encodeURIComponent(targetPath)}` : '';+ const res = await fetch(`/api/lint/audit${query}`);+ if (!res.ok) return null;+ const body = await res.json().catch(() => null);+ const parsed = LintAuditResponseSchema.safeParse(body);+ if (!parsed.success) {+ // Mirror the sibling `fetchLintConfig` logging so a client/server schema+ // drift window leaves a diagnostic trail instead of a silent null.+ console.warn('[lint] audit response failed schema validation', parsed.error.issues);+ return null;+ }+ return parsed.data;+ } catch {+ return null;+ }+}++/**+ * POST one rule change to the project's native `.markdownlint.*` file (the+ * source of truth). `value: null` removes the rule (reverts to OK's default).+ * Returns the recomputed effective config. null on any failure.+ */+export async function writeMarkdownlintRule(+ ruleId: string,+ // The write vocabulary is narrower than the read-side setting: severity+ // strings are read-tolerated, never written (the server rejects them).+ value: MarkdownlintRuleWriteValue | null,+): Promise<{ ok: true; response: LintConfigResponse } | { ok: false; errorDetail: string | null }> {+ try {+ const res = await fetch('/api/lint/markdownlint-config', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ ruleId, value }),+ });+ if (!res.ok) {+ // Surface the server's problem+json title when it carries actionable+ // guidance (e.g. the 409 for an executable .cjs/.mjs config the write+ // surface refuses to rewrite) instead of flattening every failure to+ // an indistinguishable generic toast.+ const errBody = (await res.json().catch(() => null)) as { title?: unknown } | null;+ return {+ ok: false,+ errorDetail: typeof errBody?.title === 'string' ? errBody.title : null,+ };+ }+ const body = await res.json().catch(() => null);+ const parsed = LintConfigResponseSchema.safeParse(body);+ return parsed.success ? { ok: true, response: parsed.data } : { ok: false, errorDetail: null };+ } catch {+ return { ok: false, errorDetail: null };+ }+}++/**+ * Live per-doc lint config. Refetches when `docName` changes and on any+ * `lint-config-changed` event (e.g. after a native-rule write in Settings).+ */+export function useDocLintConfig(docName: string | null): {+ data: LintConfigResponse | null;+} {+ const [data, setData] = useState<LintConfigResponse | null>(null);+ useEffect(() => {+ if (!docName) {+ setData(null);+ return;+ }+ let cancelled = false;+ const load = () => {+ void fetchLintConfig(docName).then((next) => {+ if (!cancelled) setData(next);+ });+ };+ load();+ const unsub = subscribeToLintConfigChanged(load);+ return () => {+ cancelled = true;+ unsub();+ };+ }, [docName]);+ return { data };+}++/**+ * Live project-level lint config (the Settings rule editor — no doc needed).+ * Refetches on any `lint-config-changed` event.+ */+export function useProjectLintConfig(): { data: LintConfigResponse | null } {+ const [data, setData] = useState<LintConfigResponse | null>(null);+ useEffect(() => {+ let cancelled = false;+ const load = () => {+ void fetchLintConfig().then((next) => {+ if (!cancelled) setData(next);+ });+ };+ load();+ const unsub = subscribeToLintConfigChanged(load);+ return () => {+ cancelled = true;+ unsub();+ };+ }, []);+ return { data };+}diff --git a/packages/app/src/editor/source-editor-navigation.test.ts b/packages/app/src/editor/source-editor-navigation.test.tsindex 0b15785bc..6ebaa3e18 100644--- a/packages/app/src/editor/source-editor-navigation.test.ts+++ b/packages/app/src/editor/source-editor-navigation.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, setSystemTime, test } from 'bun:test';import {clearPendingSourceNavigation,clearPendingSourceNavigationsForTest,@@ -9,6 +9,7 @@ import {afterEach(() => {clearPendingSourceNavigationsForTest();+ setSystemTime();});describe('source-editor-navigation', () => {@@ -58,3 +59,50 @@ describe('source-editor-navigation', () => {expect(consumePendingSourceNavigation('doc-a')).toBeNull();});});++describe('pending-intent expiry', () => {+ const lintNavigation = {+ kind: 'lint' as const,+ detail: { line: 7, column: 2 },+ };++ test('an intent older than 30 seconds is discarded at consume time', () => {+ setSystemTime(new Date('2026-07-09T12:00:00.000Z'));+ rememberPendingSourceNavigation('doc-a', lintNavigation);++ setSystemTime(new Date('2026-07-09T12:00:30.001Z'));+ expect(consumePendingSourceNavigation('doc-a')).toBeNull();+ });++ test('an intent aged exactly 30 seconds is still consumed', () => {+ setSystemTime(new Date('2026-07-09T12:00:00.000Z'));+ rememberPendingSourceNavigation('doc-a', lintNavigation);++ setSystemTime(new Date('2026-07-09T12:00:30.000Z'));+ expect(consumePendingSourceNavigation('doc-a')).toEqual(lintNavigation);+ });++ test('peek reports an expired intent as absent', () => {+ setSystemTime(new Date('2026-07-09T12:00:00.000Z'));+ rememberPendingSourceNavigation('doc-a', lintNavigation);++ setSystemTime(new Date('2026-07-09T12:01:00.000Z'));+ expect(peekPendingSourceNavigation('doc-a')).toBeNull();+ });++ test('re-remembering restarts the expiry clock', () => {+ setSystemTime(new Date('2026-07-09T12:00:00.000Z'));+ rememberPendingSourceNavigation('doc-a', {+ kind: 'raw-mdx',+ detail: { offset: 7 },+ });++ setSystemTime(new Date('2026-07-09T12:00:20.000Z'));+ rememberPendingSourceNavigation('doc-a', lintNavigation);++ // 40s after the first remember, 20s after the second — the refreshed+ // timestamp keeps the intent alive.+ setSystemTime(new Date('2026-07-09T12:00:40.000Z'));+ expect(consumePendingSourceNavigation('doc-a')).toEqual(lintNavigation);+ });+});diff --git a/packages/app/src/editor/source-editor-navigation.ts b/packages/app/src/editor/source-editor-navigation.tsindex 3ce80cdd8..65699ca28 100644--- a/packages/app/src/editor/source-editor-navigation.ts+++ b/packages/app/src/editor/source-editor-navigation.ts@@ -1,27 +1,49 @@import type { OutlineNavDetail } from '@/components/OutlinePanel';+import type { LintNavDetail } from '@/components/ProblemsPanel';import type { RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';type PendingSourceNavigation =| { kind: 'outline'; detail: OutlineNavDetail }- | { kind: 'raw-mdx'; detail: RawMdxNavDetail };+ | { kind: 'raw-mdx'; detail: RawMdxNavDetail }+ | { kind: 'lint'; detail: LintNavDetail };-const pendingNavigations = new Map<string, PendingSourceNavigation>();+/**+ * Discard-at-consume horizon. The replay effect fires on every source-mode+ * activation, not only the first mount after a click — so an intent banked+ * while the doc sat in WYSIWYG must expire, or a much-later mode switch would+ * jump the cursor to stale coordinates.+ */+const PENDING_NAVIGATION_TTL_MS = 30_000;++interface PendingNavigationEntry {+ navigation: PendingSourceNavigation;+ rememberedAt: number;+}++const pendingNavigations = new Map<string, PendingNavigationEntry>();++function liveNavigationOf(+ entry: PendingNavigationEntry | undefined,+): PendingSourceNavigation | null {+ if (!entry) return null;+ return Date.now() - entry.rememberedAt > PENDING_NAVIGATION_TTL_MS ? null : entry.navigation;+}export function rememberPendingSourceNavigation(docName: string,navigation: PendingSourceNavigation,): void {- pendingNavigations.set(docName, navigation);+ pendingNavigations.set(docName, { navigation, rememberedAt: Date.now() });}export function peekPendingSourceNavigation(docName: string): PendingSourceNavigation | null {- return pendingNavigations.get(docName) ?? null;+ return liveNavigationOf(pendingNavigations.get(docName));}export function consumePendingSourceNavigation(docName: string): PendingSourceNavigation | null {- const navigation = pendingNavigations.get(docName) ?? null;+ const entry = pendingNavigations.get(docName);pendingNavigations.delete(docName);- return navigation;+ return liveNavigationOf(entry);}export function clearPendingSourceNavigation(docName: string): void {diff --git a/packages/app/src/editor/source-lint/markdown-lint-source.test.ts b/packages/app/src/editor/source-lint/markdown-lint-source.test.tsnew file mode 100644index 000000000..0eb660a39--- /dev/null+++ b/packages/app/src/editor/source-lint/markdown-lint-source.test.ts@@ -0,0 +1,114 @@+/**+ * Unit tests for the pure diagnostic mapping (0-based LSP ranges → absolute CM+ * offsets). Uses an `EditorState`-derived `Text` so it runs headless (no DOM),+ * matching the source-polish convention of testing the pure builder directly.+ */++import { describe, expect, test } from 'bun:test';+import { lintGutter } from '@codemirror/lint';+import { EditorState } from '@codemirror/state';+import {+ DEFAULT_LINTER_CONFIG,+ type LintDiagnostic,+ type LintRange,+} from '@inkeep/open-knowledge-core';+import { createMarkdownLintExtension, mapLintDiagnostics } from './markdown-lint-source.ts';++const docOf = (text: string) => EditorState.create({ doc: text }).doc;++const range = (+ startLine: number,+ startCharacter: number,+ endLine: number,+ endCharacter: number,+): LintRange => ({+ start: { line: startLine, character: startCharacter },+ end: { line: endLine, character: endCharacter },+});++describe('mapLintDiagnostics', () => {+ test('maps a range to absolute offsets on the right line', () => {+ const doc = docOf('# Title\n\nhas a\ttab here\n');+ const results: LintDiagnostic[] = [+ {+ range: range(2, 5, 2, 6),+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ },+ ];+ const [d] = mapLintDiagnostics(doc, results);+ const line3 = doc.line(3);+ expect(d?.from).toBe(line3.from + 5);+ expect(d?.to).toBe(line3.from + 6);+ expect(d?.severity).toBe('warning');+ expect(d?.source).toBe('markdownlint/MD010');+ });++ test('a whole-line range spans to end of line', () => {+ const doc = docOf('---\nstatus: draft\n---\n');+ const results: LintDiagnostic[] = [+ {+ range: range(0, 0, 0, '---'.length),+ severity: 'warning',+ source: 'frontmatter',+ code: 'required',+ message: 'Frontmatter property "title" is required',+ },+ ];+ const [d] = mapLintDiagnostics(doc, results);+ const line1 = doc.line(1);+ expect(d?.from).toBe(line1.from);+ expect(d?.to).toBe(line1.to);+ });++ test('clamps an out-of-range line instead of throwing', () => {+ const doc = docOf('one line\n');+ const results: LintDiagnostic[] = [+ {+ range: range(998, 0, 998, 5),+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD047',+ message: 'x',+ },+ ];+ expect(() => mapLintDiagnostics(doc, results)).not.toThrow();+ expect(mapLintDiagnostics(doc, results)).toHaveLength(1);+ });++ test('attaches a Fix action only when fixes are present', () => {+ const doc = docOf('a\tb\n');+ const base: LintDiagnostic = {+ range: range(0, 1, 0, 2),+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ };+ const withFix: LintDiagnostic[] = [+ { ...base, fixes: [{ range: range(0, 1, 0, 2), newText: ' ' }] },+ ];+ const noFix: LintDiagnostic[] = [base];+ expect(mapLintDiagnostics(doc, withFix)[0]?.actions).toHaveLength(1);+ expect(mapLintDiagnostics(doc, withFix)[0]?.actions?.[0]?.name).toBe('Fix');+ expect(mapLintDiagnostics(doc, noFix)[0]?.actions).toBeUndefined();+ });+});++describe('createMarkdownLintExtension', () => {+ test('returns an empty extension when disabled', () => {+ const ext = createMarkdownLintExtension({ ...DEFAULT_LINTER_CONFIG, enabled: false });+ expect(Array.isArray(ext) ? ext.length : 1).toBe(0);+ });++ test('returns lint extensions when enabled', () => {+ const ext = createMarkdownLintExtension({ ...DEFAULT_LINTER_CONFIG, enabled: true });+ // [lintGutter(), linter(...)] — a non-empty extension array.+ expect(Array.isArray(ext)).toBe(true);+ expect((ext as unknown[]).length).toBeGreaterThan(0);+ // Smoke: lintGutter is constructible in this environment.+ expect(lintGutter()).toBeDefined();+ });+});diff --git a/packages/app/src/editor/source-lint/markdown-lint-source.ts b/packages/app/src/editor/source-lint/markdown-lint-source.tsnew file mode 100644index 000000000..cde8e41e2--- /dev/null+++ b/packages/app/src/editor/source-lint/markdown-lint-source.ts@@ -0,0 +1,90 @@+import { type Action, type Diagnostic, linter, lintGutter } from '@codemirror/lint';+import type { Extension, Text } from '@codemirror/state';+import type { LintDiagnostic, LinterConfig, LintPosition } from '@inkeep/open-knowledge-core';+import { lintDocument } from '@inkeep/open-knowledge-core';++/**+ * Source-mode markdown linter for CodeMirror. Wraps the framework-agnostic core+ * engine (`lintDocument`) in `@codemirror/lint`'s `linter()` facet: it produces+ * wavy underlines, the lint gutter, hover tooltips, and an inline "Fix" action+ * for auto-fixable rules. The diagnostics map the engine's 0-based LSP ranges+ * onto absolute CM offsets.+ *+ * Returns `[]` when linting is disabled so the gutter column disappears+ * entirely. Reconfigure the owning Compartment (in `SourceEditor.tsx`) when the+ * config changes — that re-runs the pass with the new rules.+ */+export function createMarkdownLintExtension(config: LinterConfig, docName?: string): Extension {+ if (!config.enabled) return [];+ return [+ lintGutter(),+ // 600ms trailing debounce keeps re-linting off the typing hot path. The+ // async source is native to @codemirror/lint — it re-checks doc currency+ // when the promise resolves.+ linter(+ async (view) =>+ mapLintDiagnostics(+ view.state.doc,+ await lintDocument(view.state.doc.toString(), config, docName),+ ),+ {+ delay: 600,+ },+ ),+ ];+}++/**+ * Clamped absolute CM offset for a 0-based LSP position. Lines are clamped —+ * the doc can shift between the async lint request and this mapping.+ */+function offsetOf(doc: Text, position: LintPosition): number {+ const lineNumber = Math.min(Math.max(position.line + 1, 1), doc.lines);+ const line = doc.line(lineNumber);+ return Math.min(line.from + Math.max(0, position.character), line.to);+}++/**+ * Map the engine's LSP-range diagnostics onto CodeMirror `Diagnostic`s against+ * `doc`. Pure (no `EditorView`) so it's unit-testable with an+ * `EditorState`-derived `Text` and no DOM.+ */+export function mapLintDiagnostics(doc: Text, results: LintDiagnostic[]): Diagnostic[] {+ const diagnostics: Diagnostic[] = [];+ for (const result of results) {+ const from = offsetOf(doc, result.range.start);+ const to = offsetOf(doc, result.range.end);++ const diagnostic: Diagnostic = {+ from,+ to: Math.max(to, from),+ severity: result.severity,+ message: result.message,+ source: `${result.source}/${result.code}`,+ };+ const action = fixAction(result);+ if (action) diagnostic.actions = [action];+ diagnostics.push(diagnostic);+ }+ return diagnostics;+}++function fixAction(result: LintDiagnostic): Action | null {+ const fixes = result.fixes;+ if (!fixes || fixes.length === 0) return null;+ return {+ name: 'Fix',+ apply(view) {+ const doc = view.state.doc;+ // Each `LintTextEdit` range is resolved against the pre-fix doc; CM+ // composes the change set atomically, so the offsets need no rebasing.+ view.dispatch({+ changes: fixes.map((fix) => ({+ from: offsetOf(doc, fix.range.start),+ to: offsetOf(doc, fix.range.end),+ insert: fix.newText,+ })),+ });+ },+ };+}diff --git a/packages/app/src/editor/useDocDiagnostics.dom.test.tsx b/packages/app/src/editor/useDocDiagnostics.dom.test.tsxnew file mode 100644index 000000000..70d84de3c--- /dev/null+++ b/packages/app/src/editor/useDocDiagnostics.dom.test.tsx@@ -0,0 +1,63 @@+/**+ * Behavioral test for useDocDiagnostics: lints the live `Y.Text('source')` of+ * the active provider and re-lints when that text changes. Uses a real Y.Doc+ * (the hook only touches `provider.document.getText('source')`).+ */++import { afterEach, describe, expect, test } from 'bun:test';+import type { HocuspocusProvider } from '@hocuspocus/provider';+import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';+import { cleanup, renderHook, waitFor } from '@testing-library/react';+import * as Y from 'yjs';+import { useDocDiagnostics } from './useDocDiagnostics';++function fakeProvider(initial: string): { provider: HocuspocusProvider; doc: Y.Doc } {+ const doc = new Y.Doc();+ doc.getText('source').insert(0, initial);+ return {+ provider: {+ document: doc,+ configuration: { name: 'test-doc' },+ } as unknown as HocuspocusProvider,+ doc,+ };+}++const enabled: LinterConfig = {+ ...DEFAULT_LINTER_CONFIG,+ enabled: true,+ plugins: { markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true } },+};++afterEach(() => cleanup());++describe('useDocDiagnostics', () => {+ test('returns [] when the provider is null', () => {+ const { result } = renderHook(() => useDocDiagnostics(null, enabled));+ expect(result.current).toEqual([]);+ });++ test('returns [] when linting is disabled', () => {+ const { provider } = fakeProvider('# Title\n\n\ttabbed\n');+ const { result } = renderHook(() =>+ useDocDiagnostics(provider, { ...enabled, enabled: false }),+ );+ expect(result.current).toEqual([]);+ });++ test('lints the live source text on mount', async () => {+ const { provider } = fakeProvider('# Title\n\n\ttabbed line\n');+ const { result } = renderHook(() => useDocDiagnostics(provider, enabled));+ // The lint pass is async — the initial diagnostics land a tick after mount.+ await waitFor(() => expect(result.current.some((d) => d.code === 'MD010')).toBe(true));+ });++ test('re-lints (debounced) when the source text changes', async () => {+ const { provider, doc } = fakeProvider('# Title\n\nclean\n');+ const { result } = renderHook(() => useDocDiagnostics(provider, enabled));+ expect(result.current.some((d) => d.code === 'MD010')).toBe(false);++ doc.getText('source').insert(doc.getText('source').length, '\ttabbed\n');+ await waitFor(() => expect(result.current.some((d) => d.code === 'MD010')).toBe(true));+ });+});diff --git a/packages/app/src/editor/useDocDiagnostics.ts b/packages/app/src/editor/useDocDiagnostics.tsnew file mode 100644index 000000000..ed07b0b0e--- /dev/null+++ b/packages/app/src/editor/useDocDiagnostics.ts@@ -0,0 +1,76 @@+/**+ * Live, mode-agnostic lint diagnostics for the active document. Reads the full+ * doc text from `Y.Text('source')` — which both source mode (CodeMirror) and+ * WYSIWYG mode (Server Observer A keeps it in sync) bind to — and runs the core+ * `lintDocument` engine against the effective config. Because it reads the CRDT+ * directly (not the CodeMirror view), the Problems panel and its badge stay+ * populated in WYSIWYG mode too, where there is no source editor mounted.+ *+ * Re-lints on a 300 ms trailing-edge debounce (matching the OutlinePanel+ * convention) so keystroke bursts coalesce into one pass.+ */++import type { HocuspocusProvider } from '@hocuspocus/provider';+import { type LintDiagnostic, type LinterConfig, lintDocument } from '@inkeep/open-knowledge-core';+import { useEffect, useState } from 'react';++const RELINT_DEBOUNCE_MS = 300;++/**+ * Live diagnostics for `provider`'s doc under `config`. Returns `[]` when either+ * is null or linting is disabled. Recomputes on every `Y.Text('source')` change+ * (debounced) and whenever the provider or the config VALUE changes.+ *+ * The effect keys on a serialized config hash rather than object identity:+ * callers routinely pass a freshly-built config object each render (e.g.+ * `lintConfig?.effective ?? null`), and depending on identity would re-run the+ * effect — and its `setState` — every render, looping. The empty-result branch+ * also returns the prior reference when already empty so it can't re-trigger a+ * render on its own.+ */+export function useDocDiagnostics(+ provider: HocuspocusProvider | null,+ config: LinterConfig | null,+): LintDiagnostic[] {+ const configKey = config?.enabled ? JSON.stringify(config) : null;+ const [diagnostics, setDiagnostics] = useState<LintDiagnostic[]>([]);++ useEffect(() => {+ if (!provider || configKey === null) {+ setDiagnostics((prev) => (prev.length === 0 ? prev : []));+ return;+ }+ const effectiveConfig = JSON.parse(configKey) as LinterConfig;+ const ytext = provider.document.getText('source');+ let timer: ReturnType<typeof setTimeout> | null = null;+ let cancelled = false;+ const docName = provider.configuration.name;+ // The lint pass is async: drop a resolution that lands after this effect+ // has been torn down (provider/config changed) so it can't clobber the+ // next pair's diagnostics.+ const recompute = () =>+ void lintDocument(ytext.toString(), effectiveConfig, docName)+ .then((diagnostics) => {+ if (!cancelled) setDiagnostics(diagnostics);+ })+ .catch((err) => {+ // Mirror the sibling decoration pass: a lint throw (malformed config,+ // unexpected input) must not surface as an unhandled rejection.+ if (!cancelled) console.warn('[lint] lintDocument failed', err);+ });+ const schedule = () => {+ if (timer) clearTimeout(timer);+ timer = setTimeout(recompute, RELINT_DEBOUNCE_MS);+ };+ // Initial pass for this provider/config pair, then observe for live edits.+ recompute();+ ytext.observe(schedule);+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ ytext.unobserve(schedule);+ };+ }, [provider, configKey]);++ return diagnostics;+}diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 67d0d7c2a..ce7cc9626 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -2,6 +2,10 @@@import "tw-animate-css";@import "shadcn/tailwind.css";@import "./cmd-f.css";+/* IDE color-theme palettes (Dracula, Nord, …). Generated from+ src/lib/color-themes.ts — `html[data-color-theme="…"]` rules out-specify the+ base :root/.dark blocks below. See color-themes.ts for the generator. */+@import "./color-themes.generated.css";@plugin "tailwind-scrollbar";/* --- Activity Panel unified-diff styling (react-diff-view) ---@@ -4957,6 +4961,127 @@ html.electron-mode [data-slot="sidebar-inner"] {--broken-link-color: oklch(72% 0.18 25);}+/* Markdown linter (@codemirror/lint) — re-theme the default diagnostic surfaces+ onto OK's tokens so warnings/errors read consistently in light and dark. The+ wavy underline uses text-decoration (the same visual language as broken+ refs above) rather than the library's SVG background, which doesn't track+ our oklch palette. Severity colors: amber for warning, red for error. */+.cm-editor .cm-lintRange-warning {+ background: none;+ text-decoration: underline wavy var(--lint-warning-color, oklch(70% 0.15 75));+ text-underline-offset: 0.2em;+}+.cm-editor .cm-lintRange-error {+ background: none;+ text-decoration: underline wavy var(--lint-error-color, oklch(55% 0.15 25));+ text-underline-offset: 0.2em;+}+.dark .cm-editor .cm-lintRange-warning {+ --lint-warning-color: oklch(80% 0.13 80);+}+.dark .cm-editor .cm-lintRange-error {+ --lint-error-color: oklch(72% 0.18 25);+}+/* Diagnostic tooltip + lint panel onto OK popover tokens. */+.cm-tooltip.cm-tooltip-lint,+.cm-panel.cm-panel-lint {+ background-color: var(--popover);+ color: var(--popover-foreground);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm, 0.25rem);+}+.cm-diagnostic {+ border-left-width: 3px;+}+.cm-diagnostic-warning {+ border-left-color: var(--lint-warning-color, oklch(70% 0.15 75));+}+.cm-diagnostic-error {+ border-left-color: var(--lint-error-color, oklch(55% 0.15 25));+}+.cm-diagnosticAction {+ background-color: var(--primary);+ color: var(--primary-foreground);+ border-radius: var(--radius-sm, 0.25rem);+}++/* WYSIWYG markdown-lint decorations (markdown-lint-decorations.ts). Source mode+ underlines the exact error range; WYSIWYG has no source columns, so we flag+ the top-level block a diagnostic falls in with the SAME wavy underline visual+ language — applied to the block's text via a node decoration. No background+ fill or accent bar (those read as a heavy full-width highlight); just the+ recognizable squiggle, reusing the --lint-*-color tokens so the two surfaces+ match in light and dark. The native `title` tooltip the plugin sets on the+ block lists the rule + message on hover. */+.ProseMirror .ok-lint-block {+ text-decoration-line: underline;+ text-decoration-style: wavy;+ text-decoration-color: var(--lint-warning-color, oklch(70% 0.15 75));+ text-decoration-skip-ink: none;+ text-underline-offset: 0.2em;+}+.ProseMirror .ok-lint-block.ok-lint-block-error {+ text-decoration-color: var(--lint-error-color, oklch(55% 0.15 25));+}+.dark .ProseMirror .ok-lint-block {+ --lint-warning-color: oklch(80% 0.13 80);+}+.dark .ProseMirror .ok-lint-block.ok-lint-block-error {+ --lint-error-color: oklch(72% 0.18 25);+}+/* Textless blocks (thematic break, block image) carry no inline text, so the+ wavy text-decoration above paints nothing. Swap it for an outline that reads+ the same warning/error color. The base .ok-lint-block class stays applied for+ the hover-tooltip lookup; here we cancel its (invisible) underline. */+.ProseMirror .ok-lint-block-atom {+ text-decoration: none;+ outline: 2px dashed var(--lint-warning-color, oklch(70% 0.15 75));+ outline-offset: 3px;+ border-radius: 3px;+}+.ProseMirror .ok-lint-block-atom.ok-lint-block-error {+ outline-color: var(--lint-error-color, oklch(55% 0.15 25));+}+/* Hover tooltip for a decorated lint block (markdown-lint-decorations.ts). A+ styled, instant alternative to the native `title` — OK popover tokens,+ one diagnostic per line, never intercepts pointer events. */+.ok-lint-tooltip {+ position: absolute;+ z-index: 50;+ max-width: 22rem;+ padding: 0.375rem 0.5rem;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm, 0.25rem);+ background-color: var(--popover);+ color: var(--popover-foreground);+ box-shadow: var(--shadow-md, 0 2px 8px oklch(0% 0 0 / 0.15));+ font-size: 0.75rem;+ line-height: 1.1rem;+ white-space: pre-line;+ pointer-events: auto;+ display: flex;+ flex-direction: column;+}+.ok-lint-tooltip-message {+ white-space: pre-line;+}+.ok-lint-tooltip-fix {+ align-self: flex-start;+ margin-top: 0.25rem;+ padding: 0.125rem 0.5rem;+ border-radius: 0.25rem;+ font-weight: 600;+ cursor: pointer;+ color: var(--color-fd-primary-foreground, #fff);+ background: var(--color-fd-primary, oklch(55% 0.2 255));+}+.ok-lint-tooltip-fix:hover {+ filter: brightness(1.08);+}+.ok-lint-tooltip[hidden] {+ display: none;+}+/* Tables — hanging indent only, composed through .cm-line's additive-calcvia --list-hang (set inline by the source-polish view-plugin ontable-row/header lines — same mechanism lists use). Wrapped rowdiff --git a/packages/app/src/lib/color-themes.test.ts b/packages/app/src/lib/color-themes.test.tsnew file mode 100644index 000000000..97461d1cb--- /dev/null+++ b/packages/app/src/lib/color-themes.test.ts@@ -0,0 +1,219 @@+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { ConfigSchema, resolveLeafSchema } from '@inkeep/open-knowledge-core';+import { getEnumOptions } from '../components/settings/schema-walker';+import {+ buildCustomThemeCss,+ COLOR_THEMES,+ type ColorThemeBase,+ type CustomThemeSeed,+ customThemeKind,+ DEFAULT_CUSTOM_SEED,+ expandCustomSeed,+ expandPalette,+ generateColorThemesCss,+ isDarkColorTheme,+ isHexColor,+ relativeLuminance,+ resolveColorTheme,+ resolveCustomSeed,+} from './color-themes';++const HEX = /^#[0-9a-f]{6}$/;+// Themes whose palette isn't a static, fully-authored `base`: `default` (no+// overlay) and `custom` (built at runtime from the user seed).+const NON_STATIC = new Set(['default', 'custom']);++describe('color-themes registry', () => {+ test('default is first; default + custom are the system-kind (non-static) themes', () => {+ expect(COLOR_THEMES[0]?.id).toBe('default');+ expect(COLOR_THEMES[0]?.base).toBeUndefined();+ const systemThemes = COLOR_THEMES.filter((t) => t.kind === 'system');+ expect(systemThemes.map((t) => t.id).sort()).toEqual(['custom', 'default']);+ });++ test('every static theme carries a full base palette of 6-digit hex colors', () => {+ for (const theme of COLOR_THEMES) {+ if (NON_STATIC.has(theme.id)) continue;+ // Static built-ins force their own mode — dark or light.+ expect(['dark', 'light']).toContain(theme.kind);+ expect(theme.base).toBeDefined();+ for (const [key, value] of Object.entries(theme.base as ColorThemeBase)) {+ expect(value, `${theme.id}.${key}`).toMatch(HEX);+ }+ }+ });++ test('ids are unique', () => {+ const ids = COLOR_THEMES.map((t) => t.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ test('resolveColorTheme falls back to default for unknown / missing ids', () => {+ expect(resolveColorTheme(undefined).id).toBe('default');+ expect(resolveColorTheme('not-a-theme').id).toBe('default');+ expect(resolveColorTheme('dracula').id).toBe('dracula');+ });++ test('isDarkColorTheme is true for dark IDE themes, false for default and light themes', () => {+ expect(isDarkColorTheme('default')).toBe(false);+ expect(isDarkColorTheme(undefined)).toBe(false);+ expect(isDarkColorTheme('catppuccin-frappe')).toBe(true);+ expect(isDarkColorTheme('catppuccin-latte')).toBe(false);+ });+});++describe('expandPalette', () => {+ test('emits every shadcn surface token the base .dark block defines', () => {+ const tokens = expandPalette(COLOR_THEMES[1]?.base as ColorThemeBase);+ // A representative slice across surface, accent, sidebar, and syntax families.+ for (const required of [+ 'background',+ 'foreground',+ 'card',+ 'primary',+ 'primary-foreground',+ 'muted-foreground',+ 'destructive',+ 'border',+ 'ring',+ 'sidebar',+ 'sidebar-accent-foreground',+ 'chart-1',+ 'syntax-keyword',+ 'syntax-string',+ ]) {+ expect(tokens[required], required).toBeTruthy();+ }+ });+});++describe('generated stylesheet', () => {+ test('color-themes.generated.css is in sync with the registry (run `bun run gen:color-themes`)', () => {+ const onDisk = readFileSync(resolve(import.meta.dir, '../color-themes.generated.css'), 'utf8');+ expect(onDisk).toBe(generateColorThemesCss());+ });++ test('emits one attribute-scoped rule per static IDE theme and none for default/custom', () => {+ const css = generateColorThemesCss();+ expect(css).not.toContain('data-color-theme="default"');+ // `custom` has no static base — its rule is built at runtime, not generated.+ expect(css).not.toContain('data-color-theme="custom"');+ for (const theme of COLOR_THEMES) {+ if (NON_STATIC.has(theme.id)) continue;+ expect(css).toContain(`html[data-color-theme="${theme.id}"] {`);+ }+ });+});++describe('registry stays in sync with its consumers', () => {+ test('ids match the appearance.colorTheme enum in ConfigSchema', () => {+ const leaf = resolveLeafSchema(ConfigSchema, ['appearance', 'colorTheme']);+ const enumOptions = leaf ? getEnumOptions(leaf) : undefined;+ expect([...(enumOptions ?? [])].sort()).toEqual(COLOR_THEMES.map((t) => t.id).sort());+ });++ test('every static IDE id appears in the index.html FOUC allowlist', () => {+ // The pre-paint script in index.html can't import this module, so it+ // hardcodes the id allowlist. `default` (no overlay) and `custom` (replayed+ // from a cached <style>, not the static allowlist) are handled separately.+ const html = readFileSync(resolve(import.meta.dir, '../../index.html'), 'utf8');+ for (const theme of COLOR_THEMES) {+ if (theme.id === 'default' || theme.id === 'custom') continue;+ expect(html, theme.id).toContain(`'${theme.id}'`);+ }+ });++ test('the index.html FOUC light-theme set matches the registry light themes', () => {+ // The pre-paint script decides the `dark` class before any bundle loads, so+ // it can't import the registry — it carries its own light-id array+ // (`[...].includes(ct)`). Adding a light theme must update that array too, or+ // the new theme would flash dark on first paint. This asserts the two stay in+ // lockstep (the light-kind analog of the allowlist-presence check above).+ const html = readFileSync(resolve(import.meta.dir, '../../index.html'), 'utf8');+ const match = html.match(/\[([^\]]*)\]\.includes\(ct\)/);+ expect(match, 'FOUC light-theme array (`[...].includes(ct)`) not found in index.html').not.toBe(+ null,+ );+ const scriptLightIds = [...(match?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]).sort();+ const registryLightIds = COLOR_THEMES.filter((t) => t.kind === 'light')+ .map((t) => t.id)+ .sort();+ expect(scriptLightIds).toEqual(registryLightIds);+ });++ test('custom is registered as a tile and accepted by the schema enum', () => {+ expect(COLOR_THEMES.some((t) => t.id === 'custom')).toBe(true);+ const leaf = resolveLeafSchema(ConfigSchema, ['appearance', 'colorTheme']);+ expect([...(leaf ? (getEnumOptions(leaf) ?? []) : [])]).toContain('custom');+ });+});++describe('custom theme seed', () => {+ test('isHexColor accepts #rrggbb only', () => {+ expect(isHexColor('#0f172a')).toBe(true);+ expect(isHexColor('#FFF')).toBe(false);+ expect(isHexColor('0f172a')).toBe(false);+ expect(isHexColor('rebeccapurple')).toBe(false);+ expect(isHexColor(123)).toBe(false);+ expect(isHexColor(undefined)).toBe(false);+ });++ test('relativeLuminance orders black < mid < white', () => {+ expect(relativeLuminance('#000000')).toBeCloseTo(0, 5);+ expect(relativeLuminance('#ffffff')).toBeCloseTo(1, 5);+ expect(relativeLuminance('#0f172a')).toBeLessThan(0.5);+ expect(relativeLuminance('#f1f5f9')).toBeGreaterThan(0.5);+ });++ test('customThemeKind derives mode from the background luminance', () => {+ expect(customThemeKind({ ...DEFAULT_CUSTOM_SEED, background: '#0f172a' })).toBe('dark');+ expect(customThemeKind({ ...DEFAULT_CUSTOM_SEED, background: '#fefefe' })).toBe('light');+ });++ test('resolveCustomSeed merges valid fields over the default and drops bad hex', () => {+ const seed = resolveCustomSeed({+ background: '#123456',+ primary: 'not-a-hex',+ accent: undefined,+ });+ expect(seed.background).toBe('#123456');+ expect(seed.primary).toBe(DEFAULT_CUSTOM_SEED.primary);+ expect(seed.accent).toBe(DEFAULT_CUSTOM_SEED.accent);+ });++ test('resolveCustomSeed returns the full default for an absent seed', () => {+ expect(resolveCustomSeed(undefined)).toEqual(DEFAULT_CUSTOM_SEED);+ });++ test('expandCustomSeed maps the six seeds onto the base palette', () => {+ const seed: CustomThemeSeed = {+ background: '#101010',+ surface: '#202020',+ foreground: '#fafafa',+ primary: '#3366ff',+ accent: '#33ddcc',+ border: '#303030',+ };+ const base = expandCustomSeed(seed);+ expect(base.bg).toBe('#101010');+ expect(base.bgElevated).toBe('#202020');+ expect(base.fg).toBe('#fafafa');+ expect(base.primary).toBe('#3366ff');+ expect(base.blue).toBe('#33ddcc');+ // Text on a dark primary is white; muted text is a derived color-mix.+ expect(base.primaryFg).toBe('#ffffff');+ expect(base.fgMuted).toContain('color-mix');+ });++ test('buildCustomThemeCss emits a custom-scoped rule with the seed + matching color-scheme', () => {+ const css = buildCustomThemeCss({ ...DEFAULT_CUSTOM_SEED, background: '#0a0a0a' });+ expect(css).toContain('html[data-color-theme="custom"] {');+ expect(css).toContain('color-scheme: dark;');+ expect(css).toContain('--background: #0a0a0a;');++ const lightCss = buildCustomThemeCss({ ...DEFAULT_CUSTOM_SEED, background: '#fafafa' });+ expect(lightCss).toContain('color-scheme: light;');+ });+});diff --git a/packages/app/src/lib/color-themes.ts b/packages/app/src/lib/color-themes.tsnew file mode 100644index 000000000..7d616d6ce--- /dev/null+++ b/packages/app/src/lib/color-themes.ts@@ -0,0 +1,152 @@+/**+ * App-facing barrel for the IDE color themes.+ *+ * The built-in theme registry + its pure token logic now live in+ * `@inkeep/open-knowledge-core` (`theme/theme-plugins.ts`) as a `ThemePlugin`+ * registry — moved there so the `appearance.colorTheme` config enum can be+ * DERIVED from it (core can't import app). This module re-exports those under the+ * app's existing names and keeps the **custom theme** seed logic, which is+ * app-only (built at runtime from the user's six-color seed; not part of the+ * built-in plugin registry).+ */++import {+ type ColorThemeBase,+ colorThemeMode,+ expandPalette,+ generateColorThemesCss,+ isDarkTheme,+ resolveThemePlugin,+ THEME_PLUGINS,+ type ThemePlugin,+} from '@inkeep/open-knowledge-core';++export type { ColorThemeBase };+// Re-export the core registry + pure token logic under the app's existing names.+export {+ colorThemeMode,+ expandPalette,+ generateColorThemesCss,+ isDarkTheme as isDarkColorTheme,+ resolveThemePlugin as resolveColorTheme,+ THEME_PLUGINS as COLOR_THEMES,+};+export type ColorTheme = ThemePlugin;++// ---------------------------------------------------------------------------+// Custom theme — the user's own palette (`appearance.colorTheme: 'custom'`).+//+// Unlike the built-ins, a custom palette is unknown at build time, so its CSS+// is generated at runtime from a six-color seed and injected as a <style> tag+// (see `useApplyConfigColorTheme`). The seed expands to a full `ColorThemeBase`+// here, then through the same `expandPalette` the built-ins use — one+// token-mapping source for both.+// ---------------------------------------------------------------------------++/** The six user-editable seed colors for the custom theme. All `#rrggbb`. */+export interface CustomThemeSeed {+ /** Editor canvas background. */+ background: string;+ /** Elevated surfaces — cards, sidebar, popovers. */+ surface: string;+ /** Primary text. */+ foreground: string;+ /** Accent for buttons, links, focus ring. */+ primary: string;+ /** Secondary accent — syntax highlights, charts. */+ accent: string;+ /** Hairline borders + inputs. */+ border: string;+}++const HEX_RE = /^#[0-9a-fA-F]{6}$/;++/** A tasteful slate/indigo dark default so a fresh custom theme is usable immediately. */+export const DEFAULT_CUSTOM_SEED: CustomThemeSeed = {+ background: '#0f172a',+ surface: '#1e293b',+ foreground: '#e2e8f0',+ primary: '#6366f1',+ accent: '#22d3ee',+ border: '#334155',+};++export function isHexColor(value: unknown): value is string {+ return typeof value === 'string' && HEX_RE.test(value);+}++/**+ * Merge a (possibly partial / hand-edited) config seed over the default,+ * dropping any field that isn't a valid `#rrggbb` hex so a typo can't break the+ * whole palette.+ */+export function resolveCustomSeed(+ partial: Partial<Record<keyof CustomThemeSeed, unknown>> | undefined,+): CustomThemeSeed {+ const seed = { ...DEFAULT_CUSTOM_SEED };+ if (partial) {+ for (const key of Object.keys(DEFAULT_CUSTOM_SEED) as (keyof CustomThemeSeed)[]) {+ const v = partial[key];+ if (isHexColor(v)) seed[key] = v;+ }+ }+ return seed;+}++/** sRGB relative luminance (WCAG) of a `#rrggbb` color, 0 (black) … 1 (white). */+export function relativeLuminance(hex: string): number {+ const h = isHexColor(hex) ? hex : '#000000';+ const channel = (i: number) => {+ const c = Number.parseInt(h.slice(1 + i * 2, 3 + i * 2), 16) / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(0) + 0.7152 * channel(1) + 0.0722 * channel(2);+}++/** A custom seed is dark when its background is dark — drives the `.dark` class + `color-scheme`. */+export function customThemeKind(seed: CustomThemeSeed): 'light' | 'dark' {+ return relativeLuminance(seed.background) < 0.5 ? 'dark' : 'light';+}++/** Text color that reads on top of `bg` — white on dark, near-black on light. */+function contrastingText(bg: string): string {+ return relativeLuminance(bg) < 0.5 ? '#ffffff' : '#0a0a0a';+}++/**+ * Expand the six-color seed into a full `ColorThemeBase`. Text-on-accent and+ * muted text are derived (luminance pick + `color-mix`); the semantic accent+ * hues (red/green/yellow/orange) are fixed, legible-on-either-mode defaults,+ * while blue/cyan/purple track the user's `accent` so syntax + charts stay+ * on-brand.+ */+export function expandCustomSeed(seed: CustomThemeSeed): ColorThemeBase {+ return {+ bg: seed.background,+ bgElevated: seed.surface,+ bgSubtle: seed.surface,+ fg: seed.foreground,+ fgMuted: `color-mix(in oklab, ${seed.foreground} 55%, ${seed.background})`,+ border: seed.border,+ primary: seed.primary,+ primaryFg: contrastingText(seed.primary),+ red: '#e5534b',+ green: '#3fb950',+ yellow: '#d29922',+ blue: seed.accent,+ cyan: seed.accent,+ orange: '#db8d3f',+ purple: seed.accent,+ };+}++/**+ * Build the runtime stylesheet for the active custom theme: one+ * `html[data-color-theme="custom"]` rule with the full expanded token set and a+ * `color-scheme` matching the seed's light/dark kind.+ */+export function buildCustomThemeCss(seed: CustomThemeSeed): string {+ const tokens = expandPalette(expandCustomSeed(seed));+ const lines = Object.entries(tokens).map(([name, value]) => ` --${name}: ${value};`);+ return `html[data-color-theme="custom"] {\n color-scheme: ${customThemeKind(seed)};\n${lines.join('\n')}\n}`;+}diff --git a/packages/app/src/lib/config-context.ts b/packages/app/src/lib/config-context.tsindex fb9635327..50795bf6f 100644--- a/packages/app/src/lib/config-context.ts+++ b/packages/app/src/lib/config-context.ts@@ -62,3 +62,13 @@ export function useConfigContext(): ConfigContextValue {}return ctx;}++/**+ * Like `useConfigContext` but returns `null` instead of throwing when no+ * `<ConfigProvider />` is mounted. For components that also render in+ * provider-less unit harnesses (e.g. the Settings theme controls, tested with a+ * bare binding) — they fall back to defaults when the merged config is absent.+ */+export function useConfigContextOptional(): ConfigContextValue | null {+ return use(ConfigContext);+}diff --git a/packages/app/src/lib/config-provider.tsx b/packages/app/src/lib/config-provider.tsxindex 8ea771f5a..724370643 100644--- a/packages/app/src/lib/config-provider.tsx+++ b/packages/app/src/lib/config-provider.tsx@@ -42,8 +42,10 @@ import { type ReactNode, useEffect, useState } from 'react';import * as Y from 'yjs';import { useThemeBridge } from '@/hooks/use-theme-bridge';import { buildAuthToken } from './auth-token';+import { colorThemeMode, customThemeKind, resolveCustomSeed } from './color-themes';import { ConfigContext, type ConfigContextValue } from './config-context';import { useServerInstanceId } from './server-instance-store';+import { useApplyConfigColorTheme } from './use-apply-config-color-theme';import { useApplyConfigTheme } from './use-apply-config-theme';export { useConfigContext } from './config-context';@@ -276,11 +278,34 @@ export function ConfigProvider({: null;const themeValue = merged?.appearance?.theme;- // Bridge `appearance.theme` from the merged config into next-themes app-wide.+ const colorThemeValue = merged?.appearance?.colorTheme;+ const customSeed = merged?.appearance?.customTheme;+ // The Themes plugin toggle. Disabled means the effect stops: the default+ // palette applies and the saved `colorTheme` is ignored (not cleared — it+ // comes back when the plugin is re-enabled). Default on (absent → enabled).+ const colorThemeEnabled = merged?.appearance?.colorThemeEnabled !== false;+ // A non-`default` palette takes over the appearance: it forces next-themes+ // into its own light/dark mode so Tailwind `dark:` variants resolve against+ // the themed tokens. Most IDE palettes are dark (Dracula, Catppuccin Frappé,+ // …); a light palette (Catppuccin Latte) forces light. `custom` derives its+ // mode from the seed background's luminance. `default` (and a disabled Themes+ // plugin) defers to the user's light/dark/system `appearance.theme`. We never+ // patch `appearance.theme` here — switching back to `default` restores the+ // saved mode from config.+ const effectiveMode = !colorThemeEnabled+ ? themeValue+ : colorThemeValue === 'custom'+ ? customThemeKind(resolveCustomSeed(customSeed))+ : (colorThemeMode(colorThemeValue) ?? themeValue);+ // Bridge the effective mode from the merged config into next-themes app-wide.// The hook owns the dependency discipline that prevents a cross-window// light/dark flicker storm across open project windows — see// `useApplyConfigTheme`.- useApplyConfigTheme(themeValue);+ useApplyConfigTheme(effectiveMode);+ // Apply the palette overlay (`data-color-theme` attribute + FOUC cache; for+ // `custom`, the runtime `<style>` built from the seed). Honors the plugin+ // toggle: disabled clears the overlay and its FOUC caches.+ useApplyConfigColorTheme(colorThemeValue, customSeed, colorThemeEnabled);// Push `appearance.theme` to Electron main's `nativeTheme.themeSource`// and signal the cold-launch show-gate via the shared `useThemeBridge`@@ -301,7 +326,7 @@ export function ConfigProvider({// appearance from frame 1 and the gate releases promptly.useThemeBridge(typeof window !== 'undefined' ? window.okDesktop : undefined,- themeValue ?? 'system',+ effectiveMode ?? 'system',);const value: ConfigContextValue = {diff --git a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx b/packages/app/src/lib/config-provider.user-synced.dom.test.tsxindex b60d86ac0..369ecd4e6 100644--- a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx+++ b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx@@ -185,6 +185,17 @@ mock.module('@inkeep/open-knowledge-core', () => ({mergeLayeredCalls.push([user, project, projectLocal]);return mergedConfig;},+ // `@/lib/color-themes` (pulled in transitively via config-provider and+ // SettingsDialogBody) now re-exports the theme registry from core, so the+ // wholesale core mock must stub every re-exported symbol or color-themes'+ // re-exports fail to resolve (a hard named-import error for `colorThemeMode`,+ // which SettingsDialogBody imports statically).+ colorThemeMode: (id?: string) => (id && id !== 'default' && id !== 'custom' ? 'dark' : undefined),+ expandPalette: () => ({}),+ generateColorThemesCss: () => '',+ isDarkTheme: (id?: string) => Boolean(id) && id !== 'default' && id !== 'custom',+ resolveThemePlugin: (id?: string) => ({ id: id ?? 'default', label: 'Default', kind: 'system' }),+ THEME_PLUGINS: [],}));// Module-level toggle for the second case (mount-time pre-synced seed).diff --git a/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsxnew file mode 100644index 000000000..db956171a--- /dev/null+++ b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx@@ -0,0 +1,167 @@+import { afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { cleanup, render } from '@testing-library/react';+import {+ applyColorThemeToDom,+ COLOR_THEME_ATTRIBUTE,+ COLOR_THEME_STORAGE_KEY,+ CUSTOM_THEME_STORAGE_KEY,+ CUSTOM_THEME_STYLE_ID,+ useApplyConfigColorTheme,+} from './use-apply-config-color-theme';++// The jsdom preload installs `window` but not a top-level `localStorage`+// global; production runs in a real browser where it is global. Bridge it so+// the FOUC-cache writes are observable here.+beforeAll(() => {+ if (typeof localStorage === 'undefined') {+ (globalThis as { localStorage?: Storage }).localStorage = window.localStorage;+ }+});++function Harness({ colorTheme, enabled }: { colorTheme: string | undefined; enabled?: boolean }) {+ useApplyConfigColorTheme(colorTheme, undefined, enabled ?? true);+ return null;+}++function CustomHarness({ enabled }: { enabled: boolean }) {+ useApplyConfigColorTheme('custom', { background: '#101014' }, enabled);+ return null;+}++describe('useApplyConfigColorTheme', () => {+ afterEach(() => {+ cleanup();+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ try {+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ } catch {}+ });++ test('sets the attribute + FOUC cache for an IDE theme', () => {+ render(<Harness colorTheme="dracula" />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBe('dracula');+ });++ test('clears the attribute + cache when switched back to default', () => {+ const { rerender } = render(<Harness colorTheme="catppuccin-frappe" />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('catppuccin-frappe');+ rerender(<Harness colorTheme="default" />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ });++ test('treats an unknown id as default (clears the overlay)', () => {+ render(<Harness colorTheme="not-a-real-theme" />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ });+});++describe('useApplyConfigColorTheme — Themes plugin disabled', () => {+ afterEach(() => {+ cleanup();+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+ try {+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);+ } catch {}+ });++ test('disabling reverts an active named palette to the default', () => {+ const { rerender } = render(<Harness colorTheme="catppuccin-frappe" enabled />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('catppuccin-frappe');++ rerender(<Harness colorTheme="catppuccin-frappe" enabled={false} />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ // The FOUC mirror carries the disabled state — a reload's pre-paint script+ // finds no cached palette, so it cannot flash the palette back.+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ });++ test('mounting disabled never applies the saved palette', () => {+ render(<Harness colorTheme="dracula" enabled={false} />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ });++ test('disabling removes the custom <style> and both FOUC mirror entries', () => {+ const { rerender } = render(<CustomHarness enabled />);+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).not.toBeNull();+ expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).not.toBeNull();++ rerender(<CustomHarness enabled={false} />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).toBeNull();+ });++ test('re-enabling brings the saved palette back', () => {+ const { rerender } = render(<Harness colorTheme="dracula" enabled={false} />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);++ rerender(<Harness colorTheme="dracula" enabled />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBe('dracula');+ });+});++describe('applyColorThemeToDom', () => {+ afterEach(() => {+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ try {+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ } catch {}+ });++ test('is idempotent and clears on undefined', () => {+ applyColorThemeToDom('gruvbox');+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('gruvbox');+ applyColorThemeToDom(undefined);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ });+});++describe('applyColorThemeToDom — custom palette', () => {+ afterEach(() => {+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+ try {+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);+ } catch {}+ });++ test('injects a <style> built from the seed and caches it for FOUC', () => {+ applyColorThemeToDom('custom', { background: '#0a0a0a', primary: '#abcdef' });+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('custom');++ const style = document.getElementById(CUSTOM_THEME_STYLE_ID);+ expect(style).not.toBeNull();+ expect(style?.textContent).toContain('html[data-color-theme="custom"]');+ expect(style?.textContent).toContain('--background: #0a0a0a;');+ expect(style?.textContent).toContain('--primary: #abcdef;');++ const cached = JSON.parse(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY) ?? '{}');+ expect(cached.css).toContain('--background: #0a0a0a;');+ expect(cached.dark).toBe(true);+ });++ test('switching away from custom removes the <style> and the cache', () => {+ applyColorThemeToDom('custom', { background: '#0a0a0a' });+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).not.toBeNull();++ applyColorThemeToDom('dracula');+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();+ expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).toBeNull();+ });++ test('a light background yields a light color-scheme + dark:false cache', () => {+ applyColorThemeToDom('custom', { background: '#fafafa', foreground: '#111111' });+ const style = document.getElementById(CUSTOM_THEME_STYLE_ID);+ expect(style?.textContent).toContain('color-scheme: light;');+ const cached = JSON.parse(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY) ?? '{}');+ expect(cached.dark).toBe(false);+ });+});diff --git a/packages/app/src/lib/use-apply-config-color-theme.ts b/packages/app/src/lib/use-apply-config-color-theme.tsnew file mode 100644index 000000000..d40b8599d--- /dev/null+++ b/packages/app/src/lib/use-apply-config-color-theme.ts@@ -0,0 +1,124 @@+import { useEffect } from 'react';+import {+ buildCustomThemeCss,+ type CustomThemeSeed,+ customThemeKind,+ resolveColorTheme,+ resolveCustomSeed,+} from './color-themes';++/** localStorage key the FOUC script in `index.html` reads pre-paint. Keep both in sync. */+export const COLOR_THEME_STORAGE_KEY = 'ok-color-theme-v1';++/** localStorage key holding the active custom theme's prebuilt CSS + kind, for flash-free reload. */+export const CUSTOM_THEME_STORAGE_KEY = 'ok-custom-theme-v1';++/** The `<html>` attribute the generated `color-themes.generated.css` rules key off. */+export const COLOR_THEME_ATTRIBUTE = 'data-color-theme';++/** id of the runtime `<style>` element holding the active custom palette. */+export const CUSTOM_THEME_STYLE_ID = 'ok-custom-theme';++type SeedInput = Partial<Record<keyof CustomThemeSeed, unknown>> | undefined;++function upsertCustomStyle(css: string): void {+ let style = document.getElementById(CUSTOM_THEME_STYLE_ID) as HTMLStyleElement | null;+ if (!style) {+ style = document.createElement('style');+ style.id = CUSTOM_THEME_STYLE_ID;+ document.head.appendChild(style);+ }+ if (style.textContent !== css) style.textContent = css;+}++function removeCustomStyle(): void {+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+}++/**+ * Apply a color theme to the DOM now: set (or clear, for `default`) the+ * `data-color-theme` attribute on `<html>`, inject/remove the runtime custom+ * palette `<style>`, and mirror everything into the localStorage caches the+ * pre-paint FOUC script reads on the next reload. Idempotent. Shared by the+ * config effect below and the Settings picker's optimistic on-click apply so+ * both paths stay byte-identical.+ *+ * `customSeed` is only consulted for the `custom` theme; pass the merged-config+ * `appearance.customTheme` (a partial seed — missing/invalid fields fall back+ * to the default palette).+ *+ * `enabled: false` (the Themes plugin toggled off) applies exactly like+ * `default`: the attribute clears, no custom `<style>` is injected, and BOTH+ * FOUC caches are removed — the mirror is how pre-paint learns the disabled+ * state, so a reload can't flash the palette back.+ */+export function applyColorThemeToDom(+ colorThemeValue: string | undefined,+ customSeed?: SeedInput,+ enabled = true,+): void {+ if (typeof document === 'undefined') return;+ const theme = resolveColorTheme(enabled ? colorThemeValue : 'default');+ const root = document.documentElement;++ if (theme.id === 'default') {+ root.removeAttribute(COLOR_THEME_ATTRIBUTE);+ } else {+ root.setAttribute(COLOR_THEME_ATTRIBUTE, theme.id);+ }++ let customCacheEntry: string | null = null;+ if (theme.id === 'custom') {+ const seed = resolveCustomSeed(customSeed);+ const css = buildCustomThemeCss(seed);+ upsertCustomStyle(css);+ customCacheEntry = JSON.stringify({ css, dark: customThemeKind(seed) === 'dark' });+ } else {+ removeCustomStyle();+ }++ try {+ if (theme.id === 'default') {+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ } else {+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, theme.id);+ }+ if (customCacheEntry) {+ localStorage.setItem(CUSTOM_THEME_STORAGE_KEY, customCacheEntry);+ } else {+ localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);+ }+ } catch {+ // Private-mode / storage-disabled: the attribute + style are still applied+ // for this session; only the next-reload FOUC pre-paint is forgone.+ }+}++/**+ * Bridge the merged-config `appearance.colorTheme` (+ `appearance.customTheme`+ * seed) into the DOM app-wide.+ *+ * The dark/light *mode* that a palette forces is handled separately by+ * `useApplyConfigTheme` (next-themes owns the `.dark` class) — this hook only+ * toggles which palette overlay is active. `default` (and any unknown value)+ * clears the attribute so the base `:root` / `.dark` theme shows through.+ *+ * Unlike the mode flip there is no cross-window storm risk here: nothing+ * listens for the `ok-color-theme-v1` `storage` event, so a write doesn't+ * re-enter this effect in other windows.+ */+export function useApplyConfigColorTheme(+ colorThemeValue: string | undefined,+ customSeed?: SeedInput,+ enabled = true,+): void {+ // Serialize the seed so the effect re-runs on a live color edit while the+ // custom theme is active, without depending on object identity. `seedKey` is+ // the value-stable proxy for `customSeed`; depending on the object directly+ // would churn on every render, and biome can't see the proxy relationship.+ const seedKey = enabled && colorThemeValue === 'custom' ? JSON.stringify(customSeed ?? null) : '';+ // biome-ignore lint/correctness/useExhaustiveDependencies: seedKey is the value-stable proxy for customSeed (see above).+ useEffect(() => {+ applyColorThemeToDom(colorThemeValue, customSeed, enabled);+ }, [colorThemeValue, seedKey, enabled]);+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 1fc1b4827..1113695a1 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -20,6 +20,7 @@"-g6KIS": ["Unrecognized link"],"-gdcIo": ["Auto-sync is on — your commits push and remote changes pull on intervals."],"-i7ik4": ["Collapse burst ", ["burstNumber"], " diff"],+ "-kbIAr": ["Links & images"],"-lCAuQ": ["Loading graph"],"-o5XAG": ["Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."@@ -87,6 +88,7 @@"12F9WL": ["(no id)"],"16D5Zj": ["Are you sure you want to delete ", ["itemName"], "? This action cannot be undone."],"1AumWo": ["Push failed — check the server logs for details."],+ "1CalO6": ["Style"],"1EcCom": [["keyName"], " value"],"1FLarN": ["Describe what you want to create to continue"],"1GhYxC": ["of ", ["totalPages"]],@@ -106,6 +108,7 @@"1d1F11": ["Select all files and folders"],"1di5fu": ["Document not found"],"1hvhf0": ["The folder on disk and the id agents use to invoke this skill."],+ "1njn7W": ["Light"],"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],"1t_NnN": ["Reject"],"2-CeZn": [@@ -125,6 +128,7 @@"2FnYUD": ["App & system info, recent app logs, and project server logs: the essentials we need to reproduce the issue."],+ "2G-56b": ["Failed to update markdownlint rules"],"2GT3Hf": ["Global"],"2H43L8": ["Secrets like API keys and tokens are redacted automatically."],"2IYGkU": ["This doc has unpushed changes. Recipients will see the last pushed version."],@@ -139,6 +143,7 @@"2hYmUH": ["[email protected]"],"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],"2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],+ "2m_bmh": [["label"], " (", ["0"], ")"],"2myNzt": ["We've filed it with the team and attached your logs."],"2n3oDU": ["Project-level pages ordered by inbound link count, up to ",@@ -229,6 +234,7 @@"4c_a6S": ["Nothing set yet."],"4g19V6": ["Failed to update property"],"4hJhzz": ["Table"],+ "4ieVh2": ["Pick “Custom” above to use this palette."],"4jDd0j": ["Anyone can see"],"4mLBx9": ["Subscriptions aren't available right now."],"4niEzY": ["Sandboxed HTML embed — write HTML, see the rendered preview live."],@@ -246,6 +252,7 @@"4zGlN_": ["Paste image URL or click upload"],"5-FeN2": ["Share URL"],"5-o4kO": ["Only markdown files"],+ "50ORFs": ["Reset ", ["0"], " to default"],"54Y6Fg": ["Could not load templates. Try again later."],"56WWtu": ["Couldn't load starter packs: ", ["error"]],"56xUL1": ["Property name"],@@ -430,6 +437,7 @@"96w9hU": ["Something went wrong opening this file (HTTP ", ["status"], ")."],"99eR72": ["Visual editor table selection"],"9Bd18D": ["Failed to load hub pages"],+ "9KooKn": ["Run a project audit from the Problems panel."],"9NJWgv": ["Backlinks"],"9OIqw4": ["You don't have write access to this repo."],"9PQysm": ["Hide advanced"],@@ -562,6 +570,7 @@],"CXTwen": ["Can't safely edit this project config"],"CXj9C-": ["New property name"],+ "C_Lyvh": ["Failed to save theme setting"],"C_WGy8": ["This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."],@@ -602,6 +611,7 @@"DXd9LM": ["New worktree"],"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],"DbILZA": ["No matches. Some files are excluded from search (hidden or ignored files)."],+ "DcLaew": ["Custom theme"],"DeDYLr": ["Unrecognized wiki link"],"DgcGrb": [["fileCount", "plural", { "one": ["file"], "other": ["files"] }]],"DhK_hZ": [@@ -617,6 +627,7 @@"DiFKSL": ["Counting markdown files"],"Dnn2XG": ["Automatic"],"DrYM2Z": ["Sync disabled"],+ "DsDwR-": [["0", "plural", { "one": ["#", " error"], "other": ["#", " errors"] }]],"DskIkK": ["Sign-in stream ended without confirmation — please try again"],"Dub54T": ["Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."@@ -650,6 +661,7 @@"EOjU5V": ["Inline Math Properties"],"ETyvvg": ["No language match."],"EVnzPs": ["Edit with AI"],+ "EWPtMO": ["Code"],"EWX92Z": ["Collapse Ask AI"],"EZVxVz": ["Replace the active match from the replace field."],"E_BHoD": [@@ -660,6 +672,7 @@"E_tNGD": ["Connected as @", ["login"]],"Ea1prf": ["Choose which editors every skill in this project installs into."],"EarrCe": ["Search emoji"],+ "Eax_et": ["Accent"],"EbZT7P": ["Toggle the left file sidebar."],"EbjWsS": ["Current commit"],"EcM3k7": ["Failed to clean up pending ", ["kind"]],@@ -720,6 +733,7 @@")."],"FXk_zY": ["Adds a guided workflow for authoring new Agent Skills."],+ "FZtBeR": ["Enable ", ["0"]],"FgRAvd": ["Logs & system info"],"FjkaiT": ["Zoom out"],"FnMkli": ["Sync disabled — you don't have permission to push"],@@ -736,6 +750,7 @@"G-JBA1": ["Source mode requires a live connection — your edits are saved and will appear when you reconnect."],+ "G-h6qN": [["0", "plural", { "one": ["#", " option set"], "other": ["#", " options set"] }]],"G0YZ-I": ["Indent or outdent list item"],"G1Gw0v": ["New template"],"G1XxbZ": ["Checkbox"],@@ -770,6 +785,7 @@],"G_686w": ["Task List"],"G_efLf": ["Installed into"],+ "G_hVTP": ["Enable Themes"],"G_mWXb": ["Filter languages"],"GamjcN": ["Template saved"],"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],@@ -778,6 +794,7 @@"Gp_twO": ["Local path"],"GsBUCk": ["Loading settings"],"Gt4gOO": ["This folder has unpushed changes. Recipients will see the last pushed version."],+ "GtJbUa": ["Background"],"GuaJb-": ["Open email draft"],"GubkSu": ["Use a starter pack"],"GuqOb1": ["Failed to load headings"],@@ -816,6 +833,7 @@],"Hrz9NY": ["Wiki link"],"HyvSqq": ["Project Skill"],+ "I-xnra": [["0"], " hex value"],"I1gRhX": ["Failed to rename"],"I5685_": ["Try a prompt"],"I5AfhE": ["Sync status unavailable — server unreachable."],@@ -823,6 +841,7 @@"IA1wNb": ["The Claude Desktop App didn't open the file. Is it installed? (", ["msg"], ")"],"IA6JW2": ["Detecting"],"ICoNYz": ["You can also manage this in Settings."],+ "IFezUv": ["The audit could not be completed. Try again."],"IInnZo": ["Conflict"],"IKkfn_": ["Report reference: ", ["reference"]],"IKoTAC": ["Keep disabled"],@@ -864,6 +883,7 @@"JOcPqH": ["Bring a remote repository onto this machine."],"JWsZlx": ["Open a project to edit."],"JZ8cO6": ["Light, dark, or follow the OS."],+ "J_bJiH": ["Pick a built-in IDE color palette, or define your own."],"Jejur6": ["Couldn't load document"],"JfPuv7": [["shareBranch"], " isn't a valid branch name."],"Jhj_lh": ["Modify the link target, anchor, and display label."],@@ -918,6 +938,7 @@"Kr3VPS": ["Codex will still ask until you run \"ok init\" in a terminal for this project."],"KsAPaB": ["This branch is checked out in:"],"KszKI_": ["Skill level"],+ "KtACeE": ["Default: <0>", ["0"], "</0>"],"KujtjC": ["Find"],"L-rMC9": ["Reset to default"],"L1ZE3M": ["Document statistics"],@@ -1041,6 +1062,7 @@"NOHyEE": ["Retry push"],"NORKZU": ["Pattern warnings: ", ["summary"]],"NQ8llq": ["Add item"],+ "NQXwDy": ["Edit in config file"],"NRSLBe": [["diffMin"], "m ago"],"NSnIUP": ["Two-page (even)"],"NUr4kz": ["A reusable starting point for new documents in this folder."],@@ -1049,12 +1071,14 @@"Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."],"NcurBF": ["Pan down"],+ "NgZwB0": [["enabledCount"], "/", ["0"], " on"],"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],"NkXEFS": ["Restore failed — document unchanged"],"NmPNJJ": ["Copy code"],"Nn4GgW": ["Will be created as <0>", ["sanitizedName"], "</0>"],"NnQapF": ["Open with AI ", ["targetDisplayName"]],"NpC29w": ["Create a new list item from the current list item."],+ "NrFwux": ["Failed to save content rules — ", ["0"]],"Nu4DdT": ["Sync"],"Nu4oKW": ["Description"],"NuH1jp": ["Public repository"],@@ -1089,11 +1113,13 @@"OVjNeX": ["Terminal ", ["0"]],"OX2Neh": ["Inline code"],"OXb_Df": ["Settings content"],+ "OXdGnd": ["Problems"],"OYnx7O": ["Path cannot start with \"/\""],"OZJeTZ": ["Skill"],"Oawo4U": ["The report service couldn't be reached."],"OdmsFg": ["Failed to delete item"],"OeAl1e": ["e.g. assets/uploads"],+ "OfhWJH": ["Reset"],"OgyJSr": ["Local only"],"OiHJdA": ["Move through slash, wiki-link, tag, and path suggestions; accept or dismiss the active suggestion."@@ -1125,6 +1151,7 @@"PCSkw2": ["Skills"],"PIMM5l": ["You're subscribed!"],"PKLY-1": ["Opening..."],+ "PKjGhT": ["Headings"],"PMyJ9C": ["No edit session yet"],"PPFQ3o": ["Installed \"", ["0"], "\" into ", ["1"]],"PQCdtv": ["\"", ["docName"], "\" doesn't exist."],@@ -1133,6 +1160,9 @@"PVUn_c": ["Open folder"],"PZtgO0": ["Opening worktree"],"P_bX4O": ["How to set up"],+ "Pck6eI": [+ "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."+ ],"PdA9NZ": [["ahead"], " ahead"],"PdJZ5p": ["No skills yet."],"Pgu10b": ["Saved as <0>", ["slug"], ".md</0>"],@@ -1190,6 +1220,7 @@"A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."],"R9IDFz": ["Renames the folder on disk and the id agents use to invoke it."],+ "R9Khdg": ["Auto"],"RDjuBN": ["Setup"],"RDrXh4": ["Configure user, project, and integration settings."],"RG4XHV": ["Copy ", ["0"], " prompt"],@@ -1209,6 +1240,7 @@"Rb1zMa": ["No excerpt"],"RfHNf8": ["Open activity panel for ", ["tooltipName"]],"RfaEio": ["Toggle source comment"],+ "RfilGt": ["No rules match your filters."],"RgbKEe": ["You don't have access to this repository."],"Rj01Fz": ["Links"],"RlCInP": ["Slash commands"],@@ -1218,6 +1250,7 @@"RobAKV": ["Update the destination and optional section anchor."],"Rq1vFD": ["Tree view options"],"RrAIZx": ["What config sharing covers"],+ "Rsdhj9": ["Configuration warnings"],"Rx5ReQ": ["Rename ", ["keyName"]],"RyIKxy": ["This ",@@ -1262,12 +1295,17 @@"TJnkyf": ["ok ui responded but server.lock has no port yet"],"TKQ7K-": ["Install"],"TLIO3j": ["Toggle italic formatting."],+ "T_R-Qz": ["Primary"],"T_wG4n": ["We couldn't check your GitHub connection."],"Ta25TG": ["No history yet"],"TbjyhA": ["Docs"],+ "Te6sK2": [+ "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."+ ],"ThmUrC": ["Could not finalize project setup. Try again."],"Tjc1pH": ["Section <0>(optional heading anchor)</0>"],"TsZmgr": ["The file on disk, and the id agents use."],+ "TvY_XA": ["Documentation"],"TwYboS": ["Navigate CodeMirror source search results or dismiss the search panel."],"Tz0i8g": ["Settings"],"Tz9pJB": ["Clone stream ended unexpectedly — check if the clone completed"],@@ -1317,6 +1355,7 @@"UhpfxY": ["Pan left"],"UkQGhd": ["Hide replace"],"Up2_7p": ["Copy full path"],+ "UpCz01": ["This doc"],"UuYo7g": ["This ",["targetNoun"],@@ -1325,6 +1364,11 @@"Uuj_R4": ["New from template"],"Uw6ERJ": ["Couldn't copy: ", ["detail"]],"UyROxs": [["mins", "plural", { "one": ["#", " min ago"], "other": ["#", " min ago"] }]],+ "V2Gmie": [+ "These rules come from your project's <0>",+ ["configFile"],+ "</0> file, which fully governs linting for this project. Turn rules on or off and edit their options here; changes write back to the file."+ ],"V48OUT": ["You deleted <0>", ["filePath"], "</0> locally, but it was modified upstream."],"V7QxyT": ["Connection dropped"],"VAHWL_": ["Connected as <0>@", ["signedInLogin"], "</0>"],@@ -1349,6 +1393,7 @@"VbqhBI": ["Already at ", ["assetContentPath"], " — reusing."],"VcqWBy": ["Upload may have succeeded but the sidebar is out of date — refresh to resync"],"VdXv4D": ["Clone from GitHub"],+ "Vftef5": ["Common markdown issues — hard tabs, heading increments, list markers, and more."],"Vlc75q": ["Keep file deleted"],"VsaI0G": [["folderCount", "plural", { "one": ["folder"], "other": ["folders"] }]],"VuxVSP": ["Start source completion"],@@ -1357,6 +1402,7 @@"VzGJRl": ["Add link"],"W-ntoW": ["heading-slug"],"W0i24j": ["Object"],+ "W1SI2K": [["0", "plural", { "one": ["#", " warning"], "other": ["#", " warnings"] }]],"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],"W3Xlpc": ["Set the auto-sync default for users opening this project for the first time. This setting is committed to your repository."@@ -1369,6 +1415,7 @@],"W8vpBM": ["starter pack"],"W9_Bub": ["Local changes overlap with incoming sync"],+ "WFEbV1": ["Flag common markdown issues in the editor. Powered by <0>markdownlint<1/></0>."],"WHPvOb": ["All files are hidden by view filters."],"WJjviG": ["What to include"],"WL6puM": ["Path resolves outside project"],@@ -1380,6 +1427,7 @@"WPwDin": ["Open folder on disk"],"WR0y2O": ["Share folder"],"WRNXKp": ["Searching"],+ "WRdYfS": ["Refresh audit"],"WWcqsG": ["Start here: what this is and how it's organized."],"WZ-vBy": ["Permanently deletes <0>",@@ -1456,6 +1504,7 @@"Y6SK9K": ["Show source"],"Y8ViJx": ["A newer version may have been deployed since this tab opened."],"YC6_wP": ["Edit ", ["keyName"]],+ "YEIS9T": ["Edits apply live. Light or dark is chosen from the background."],"YEP3X2": ["Delete a table when the active table cell selection covers the full table."],"YGIi_c": ["Reinstall"],"YIp4R0": [@@ -1465,6 +1514,9 @@"YKLP_-": ["Template renamed"],"YLMBSd": ["e.g. The editor froze after I pasted a large table"],"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],+ "YRavYS": [+ "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."+ ],"YSFv5w": ["No git repository — config sharing does not apply here."],"YTLmTM": ["Remove the parent <0>.git</0> folder"],"YW7Q86": ["Search settings not yet loaded — try again in a moment"],@@ -1488,6 +1540,9 @@"Z5h97D": ["Hide files and folders from your knowledge base. Hidden items don’t appear in the file tree, search, or AI tools. <0>Learn more about patterns</0>."],+ "Z6rrjc": [+ "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."+ ],"Z8KDox": ["Enter a folder name (e.g. brain)."],"Z8lGw6": ["Share"],"ZARuZJ": ["Couldn't load files"],@@ -1499,6 +1554,7 @@"). Other files and writers are unaffected."],"ZBt4rI": ["Instruction for the AI"],+ "ZI8uvA": ["No problems found."],"ZLQol-": ["You can turn this on later in <0>Settings → Sync</0>."],"ZNK2Tq": ["root"],"ZQJ1IV": ["Activate the last editor tab."],@@ -1590,6 +1646,7 @@"aENGMB": ["Semantic search adds meaning-based ranking to the search tool so conceptually-related pages surface even without shared keywords."],+ "aHPdYV": ["Go to line ", ["displayLine"]],"aM23Wr": ["page-name"],"aOp3hw": ["Couldn't move to Trash"],"aWlJai": ["Starting sign-in flow"],@@ -1635,6 +1692,7 @@],"bwil08": ["Building <0>openknowledge.skill</0> and opening the Claude Desktop App"],"c1LZZH": ["Link copied."],+ "c4fVUV": ["Fix"],"c5f7sm": ["Code block language: ", ["currentLabel"], ". Click to change."],"c5rF4v": ["What is this knowledge base for?"],"c863eW": ["Could not switch to ", ["shareBranch"], ". Try switching manually."],@@ -1648,6 +1706,7 @@"cIptmH": ["In the Claude Desktop App"],"cKjLuT": ["(project + user)"],"cN1Gcp": ["A worktree folder for ", ["shareBranch"], " already exists."],+ "cOJyVj": ["Disable Themes"],"cOSAfL": ["No repositories found on your GitHub account."],"cOrTMo": ["Your share link is ready below."],"cRHuuI": ["Couldn't copy path"],@@ -1660,6 +1719,7 @@"cZGNlb": ["Add another pattern"],"cZI5AL": ["OK Desktop"],"cZ_8zB": ["Stays on this computer."],+ "ccNps_": ["Only modified"],"cd5EXh": ["Report a bug"],"cdm00A": ["No Incoming"],"cdmk8A": ["Uncommitted changes"],@@ -1680,6 +1740,7 @@],"d2uTPx": ["Server error (HTTP ", ["status"], ")"],"d5rK4X": [["chars", "plural", { "one": ["char"], "other": ["chars"] }]],+ "dCIGNG": ["Border"],"dD7NPy": ["Outline"],"dDpCOp": ["Rename succeeded but the sidebar may be out of date — refresh to resync"],"dEgA5A": ["Cancel"],@@ -1706,6 +1767,7 @@"Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."],"dURmlQ": ["\"frontmatter\" is a reserved property name"],+ "dVaXnv": ["Content rules not yet loaded — try again in a moment"],"dXWMFn": ["Removes this skill from your editors."],"dbapvC": ["Follow us on social media"],"dbhUX1": ["Hide this file"],@@ -1719,6 +1781,7 @@"dvGKu2": ["Shared auto-sync default"],"dw_3cv": ["Rename skill"],"dw_dUJ": ["Failed to duplicate path"],+ "dx-TwN": ["Running project audit"],"e0NrBM": ["Project"],"e1Rn_k": ["Open containing folder"],"e1hptq": ["Embed a video with native player controls."],@@ -1743,6 +1806,7 @@"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],"el312q": ["Install skills into"],"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],+ "enPTnx": ["line ", ["displayLine"]],"eneWvv": ["Draft"],"epuNYK": ["Mark a block as the source of truth. Mirrors elsewhere update live as you edit it."@@ -1756,6 +1820,7 @@"fBHvBn": ["There's no project folder for this window, so a terminal can't start here."],"fG0X0e": ["Install ", ["brand"], " →"],"fIgqfQ": ["Reinstalling"],+ "fJ3EbT": ["Themes"],"fJgQHX": ["Failed to create file"],"fNr-MX": ["Disable semantic search"],"fR-Kdc": ["(project-level only)"],@@ -1764,6 +1829,7 @@"fWsBTs": ["Something went wrong. Please try again."],"fYKgzG": ["Failed to load recent projects."],"fYjgXu": ["Unordered list of items."],+ "fZj9em": ["Fix ", ["flatId"]],"f_PkYv": ["Restarting closes this project's server. Connected agents (Claude Code, Codex, Cursor) will see their OpenKnowledge MCP connection close unexpectedly — you may need to restart the agent, or toggle its OpenKnowledge MCP server off and on, to reconnect."],@@ -1826,6 +1892,7 @@"gwykHF": ["This doc hasn't synced to GitHub yet. The link will work after the next sync."],"h-AdvS": ["The folders and templates are already here, so there's nothing to add."],"h06R3C": ["No pages are missing outgoing graph links."],+ "h16FyT": ["Lists"],"h3QZcB": ["A branch named ",["shareBranch"],@@ -1900,6 +1967,7 @@"iGCs04": ["No templates available"],"iH8pgl": ["Back"],"iHAJDj": ["Resolving default location"],+ "iIaSUD": ["Whitespace"],"iKSP5j": ["Word wrap"],"iKZkk1": ["Property value"],"iMkWoF": ["Turn on"],@@ -1933,6 +2001,7 @@"Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills.<2/><3>Shared</3> commits them to git, so anyone who clones the repo gets the same setup. <4/><5>Local only</5> keeps them out of git (via <6>.git/info/exclude</6>)."],"iuTKci": ["No edits yet."],+ "iv452l": ["Documentation for ", ["0"], " (opens in browser)"],"iycx_A": ["Pushing"],"j9Vqvc": ["inherited"],"j9tqwO": ["Not in sidebar"],@@ -1968,6 +2037,9 @@"</0> already exists here. Saving creates a local copy that overrides it for this folder."],"k0vc0N": ["New terminal tab"],+ "k2fEi7": [+ "User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."+ ],"k4CuuV": ["Ready-made folders and templates to get you started quickly. Select a pack to preview what gets created, then add it to your project."],@@ -1979,6 +2051,7 @@" ready. Results may be incomplete."],"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],+ "kDwcbW": ["Go to line ", ["displayLine"], " in ", ["0"]],"kFLlsI": ["Insert a footnote reference + matching definition stub."],"kLv8d3": ["Your copy of branch <0>",@@ -1993,6 +2066,16 @@"Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."],"kYL1lH": ["Agent activity"],+ "k_Dqw1": [+ [+ "0",+ "plural",+ {+ "one": ["No problems across ", "#", " document."],+ "other": ["No problems across ", "#", " documents."]+ }+ ]+ ],"k_pade": ["Config sharing is now shared. Commit the OK files to share with your team."],"k_yIIc": ["Will be created at: <0>", ["targetPreview"], "</0>"],"kdzzOK": ["Off — search ranks by keyword only. No content leaves this computer."],@@ -2006,6 +2089,7 @@"kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],"ku0yLQ": ["Pages are embedded the first time a search needs them."],"ky9Tuc": ["Edit ", ["0"], " source"],+ "l-4nnw": ["Search rules"],"l17ab4": ["Could not write project files. Try a different location."],"l1aQKz": ["Visual editor table"],"l1l8sj": [["0"], "d ago"],@@ -2188,6 +2272,9 @@"oQA-cA": ["Full path"],"oS1YpJ": ["Open the Project Navigator."],"oXKEsy": ["Delete an adjacent wiki-link or tag chip."],+ "oXlLi4": [+ "Project plugins are your project's authoring standard — turn them on or off here. The choice is committed to config.yml and shared with every collaborator via git. Each enabled plugin gets its own page under Plugins in the settings sidebar."+ ],"oYepHb": ["The terminal is turned off for this project. Turn it back on to run commands here."],@@ -2195,6 +2282,7 @@"You picked ~/Documents. OpenKnowledge will index every markdown file under it. If you only want to manage a sub-folder, choose a smaller scope."],"ogAuyr": ["Back to document view"],+ "ohUJJM": ["Plugins"],"omXJcU": ["Close others"],"optX0N": [["0"], "h ago"],"oqB2ez": ["Previous match"],@@ -2235,6 +2323,7 @@"pmUArF": ["Workspace"],"ppDgFi": ["Restart with this app's version"],"psfGPX": ["MCP connections"],+ "pvnfJD": ["Dark"],"pzutoc": ["Italic"],"q2kXMG": ["Inline Math"],"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],@@ -2265,6 +2354,7 @@"qbfj1f": ["Receiving objects"],"qdBUHP": ["Couldn't load ", ["fileName"]],"qi1F96": ["Reveal in File Explorer"],+ "qiN9NB": ["Surface"],"qiRoLb": ["Summarize everything I changed this week"],"qioCwA": ["Jump to page ", ["pageNumber"]],"qjHMHf": ["Failed to disable sync — ", ["detail"]],@@ -2288,6 +2378,7 @@"rD-woT": ["Tell us what went wrong and we'll gather the logs. Nothing leaves your Mac until you've reviewed it."],+ "rFmBG3": ["Color theme"],"rFw02Q": ["Uploading ", ["keyName"]],"rJVoVX": ["Source find results"],"rNifQd": ["Remove property"],@@ -2555,6 +2646,7 @@"y3aU20": ["Save changes"],"y46m5r": ["The desktop app isn't responding. Refresh and try again."],"y5FUYi": ["Suggestion menu open"],+ "y5UgU8": ["Disable ", ["0"]],"y8B54M": ["Couldn't send your prompt — please try again."],"yCX4jp": [" Your selection could not be restored."],"yEJ-sl": [@@ -2579,6 +2671,7 @@"yMgL_E": ["Find field navigation"],"yQE2r9": ["Loading"],"yQyglE": ["No matching docs"],+ "yR5LHI": ["Enter a 6-digit hex like #1A2B3C"],"yUxR-Q": ["Expand ", ["keyName"]],"yWSvcf": ["Content root"],"yWWThY": ["Asset reference"],@@ -2587,6 +2680,7 @@"y_5CE8": ["Item ", ["0"]],"y_K0Dz": ["What happened?"],"yaPGPa": ["Open a project to manage its AI tool connections."],+ "yf5auF": ["Search rules by id, alias, or name"],"yf5r22": [["keyName"]," type: ",@@ -2618,6 +2712,7 @@"z60Lgn": ["Saves the file to <0>~/Downloads/openknowledge.skill</0> and opens the Claude Desktop App. Requires Node.js or Bun on your PATH."],+ "zAJzIg": ["Problems in ", ["0"]],"zAsDLY": ["Graph visualization of document links"],"zKxoPm": ["Couldn't rename \"", ["0"], "\": ", ["1"]],"zL0LPh": ["Global outside text fields"],@@ -2626,6 +2721,9 @@"zQBg2C": ["Move the current block up or down one position."],"zUhPuR": ["Open containing folder, ", ["hint"]],"zXj1rA": ["Search by meaning"],+ "zYp8Sr": [+ "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."+ ],"zZ_I5K": ["Open project menu"],"zaXlhf": ["The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 2abdd9dc7..cdbdf39fb 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -123,6 +123,11 @@ msgstr "{0, plural, one {# backlink} other {# backlinks}}"msgid "{0, plural, one {# doc} other {# docs}}"msgstr "{0, plural, one {# doc} other {# docs}}"+#. placeholder {0}: audit.result.errorCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {# error} other {# errors}}"+msgstr "{0, plural, one {# error} other {# errors}}"+#. placeholder {0}: value.length#: src/components/ArrayOfObjectsWidget.tsxmsgid "{0, plural, one {# item} other {# items}}"@@ -133,6 +138,11 @@ msgstr "{0, plural, one {# item} other {# items}}"msgid "{0, plural, one {# key} other {# keys}}"msgstr "{0, plural, one {# key} other {# keys}}"+#. placeholder {0}: opts.length+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "{0, plural, one {# option set} other {# options set}}"+msgstr "{0, plural, one {# option set} other {# options set}}"+#. placeholder {0}: blocked.length#: src/editor/components/PreviewBlockedNotice.tsxmsgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"@@ -148,6 +158,11 @@ msgstr "{0, plural, one {# template} other {# templates}}"msgid "{0, plural, one {# use} other {# uses}}"msgstr "{0, plural, one {# use} other {# uses}}"+#. placeholder {0}: audit.result.warningCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {# warning} other {# warnings}}"+msgstr "{0, plural, one {# warning} other {# warnings}}"+#. placeholder {0}: fileRows.length#: src/components/CreatedItemsList.tsxmsgid "{0, plural, one {File} other {Files}}"@@ -158,6 +173,16 @@ msgstr "{0, plural, one {File} other {Files}}"msgid "{0, plural, one {Folder} other {Folders}}"msgstr "{0, plural, one {Folder} other {Folders}}"+#. placeholder {0}: result.fileCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"+msgstr "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"++#. placeholder {0}: labels[key]+#: src/components/settings/CustomThemeEditor.tsx+msgid "{0} hex value"+msgstr "{0} hex value"+#. placeholder {0}: templates.length#: src/components/empty-state/CreateView.tsxmsgid "{0} templates available"@@ -329,6 +354,11 @@ msgstr "{displayName} CLI, {hint}"msgid "{docName} is {0}. OpenKnowledge currently opens files up to {1}."msgstr "{docName} is {0}. OpenKnowledge currently opens files up to {1}."+#. placeholder {0}: entries.length+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "{enabledCount}/{0} on"+msgstr "{enabledCount}/{0} on"+#: src/components/FileTree.tsxmsgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"msgstr "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"@@ -376,6 +406,11 @@ msgstr "{keyName} type: complex value (nested; read-only)"msgid "{keyName} value"msgstr "{keyName} value"+#. placeholder {0}: diagnostics.length+#: src/components/DocPanel.tsx+msgid "{label} ({0})"+msgstr "{label} ({0})"+#: src/components/GraphPanel.tsxmsgid "{linkCount, plural, one {# link} other {# links}}"msgstr "{linkCount, plural, one {# link} other {# links}}"@@ -563,6 +598,10 @@ msgstr "<0>Want to follow along?</0> Open a GitHub issue and mention your referemsgid "📝 or assets/icon.png"msgstr "📝 or assets/icon.png"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."+msgstr "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."+#: src/components/ShareBranchSwitchDialog.tsxmsgid "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."msgstr "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."@@ -604,6 +643,10 @@ msgstr "A newer version may have been deployed since this tab opened."msgid "A non-empty folder already exists at this path. Pick a different folder."msgstr "A non-empty folder already exists at this path. Pick a different folder."+#: src/components/settings/LintingSection.tsx+msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."+msgstr "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."+#: src/components/CreateProjectDialog.tsxmsgid "A project already exists at this location. Pick a different parent folder."msgstr "A project already exists at this location. Pick a different parent folder."@@ -664,6 +707,10 @@ msgstr "A worktree folder for that branch already exists."msgid "Above"msgstr "Above"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Accent"+msgstr "Accent"+#: src/components/DiffView.tsxmsgid "Accept"msgstr "Accept"@@ -1029,6 +1076,10 @@ msgstr "Authoritative content; mirrored verbatim everywhere it's referenced."msgid "Authorize in browser"msgstr "Authorize in browser"+#: src/components/settings/ColorThemePicker.tsx+msgid "Auto"+msgstr "Auto"+#: src/components/settings/TerminalSection.tsxmsgid "Auto-approve settings not yet loaded — try again in a moment"msgstr "Auto-approve settings not yet loaded — try again in a moment"@@ -1092,6 +1143,10 @@ msgstr "Back"msgid "Back to document view"msgstr "Back to document view"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Background"+msgstr "Background"+#: src/components/LinksPanel.tsxmsgid "Backlinks"msgstr "Backlinks"@@ -1156,6 +1211,10 @@ msgstr "blog-post"msgid "Bold"msgstr "Bold"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Border"+msgstr "Border"+#: src/components/GraphPanel.tsxmsgid "Both"msgstr "Both"@@ -1532,6 +1591,10 @@ msgstr "Close terminal"msgid "Clusters"msgstr "Clusters"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Code"+msgstr "Code"+#: src/lib/keyboard-shortcuts.tsmsgid "Code block"msgstr "Code block"@@ -1602,6 +1665,10 @@ msgstr "Collapse terminal"msgid "Collapsible section with a clickable summary."msgstr "Collapsible section with a clickable summary."+#: src/components/settings/SettingsDialogBody.tsx+msgid "Color theme"+msgstr "Color theme"+#: src/components/CommandPalette.tsxmsgid "Command failed."msgstr "Command failed."@@ -1626,6 +1693,10 @@ msgstr "Commit or stash changes to switch:"msgid "Commits happen automatically"msgstr "Commits happen automatically"+#: src/components/settings/LintingSection.tsx+msgid "Common markdown issues — hard tabs, heading increments, list markers, and more."+msgstr "Common markdown issues — hard tabs, heading increments, list markers, and more."+#: src/components/HelpPopover.tsxmsgid "Community"msgstr "Community"@@ -1680,6 +1751,10 @@ msgstr "Config sharing unavailable: {0}."msgid "Config sharing unchanged — see details below."msgstr "Config sharing unchanged — see details below."+#: src/components/ProblemsPanel.tsx+msgid "Configuration warnings"+msgstr "Configuration warnings"+#: src/components/settings/SettingsDialogShell.tsxmsgid "Configure user, project, and integration settings."msgstr "Configure user, project, and integration settings."@@ -1793,6 +1868,10 @@ msgstr "Content directory must be inside the project"msgid "Content root"msgstr "Content root"+#: src/components/settings/LintingSection.tsx+msgid "Content rules not yet loaded — try again in a moment"+msgstr "Content rules not yet loaded — try again in a moment"+#: src/editor/bubble-menu/FootnoteBubbleButton.tsxmsgid "Convert selection to footnote"msgstr "Convert selection to footnote"@@ -2403,10 +2482,18 @@ msgstr "Custom HTML with a live preview pane (sandboxed iframe)."msgid "Custom open-knowledge entry — not managed by OpenKnowledge"msgstr "Custom open-knowledge entry — not managed by OpenKnowledge"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Custom theme"+msgstr "Custom theme"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Customize how the editor looks and behaves."msgstr "Customize how the editor looks and behaves."+#: src/components/settings/ColorThemePicker.tsx+msgid "Dark"+msgstr "Dark"+#: src/components/PropertyWidgets.tsxmsgid "Date"msgstr "Date"@@ -2423,6 +2510,11 @@ msgstr "Default location for new attachments"msgid "Default properties"msgstr "Default properties"+#. placeholder {0}: formatOptionConfigValue(spec.default)+#: src/components/settings/rule-option-field.tsx+msgid "Default: <0>{0}</0>"+msgstr "Default: <0>{0}</0>"+#: src/components/DeleteConfirmationDialog.tsx#: src/components/skill-actions.tsx#: src/components/TemplateRow.tsx@@ -2573,6 +2665,13 @@ msgstr "Diff layout"msgid "Diff unavailable"msgstr "Diff unavailable"+#. placeholder {0}: plugin.label+#. placeholder {0}: rule.name+#: src/components/settings/LintingSection.tsx+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Disable {0}"+msgstr "Disable {0}"+#: src/components/settings/LinkPreviewsSection.tsxmsgid "Disable external link previews"msgstr "Disable external link previews"@@ -2589,6 +2688,10 @@ msgstr "Disable semantic search"msgid "Disable sync"msgstr "Disable sync"+#: src/components/settings/LintingSection.tsx+msgid "Disable Themes"+msgstr "Disable Themes"+#: src/components/TemplateProperties.tsxmsgid "Disambiguates similarly-named templates in the menu."msgstr "Disambiguates similarly-named templates in the menu."@@ -2668,6 +2771,15 @@ msgstr "Document statistics"msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Documentation"+msgstr "Documentation"++#. placeholder {0}: rule.id+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Documentation for {0} (opens in browser)"+msgstr "Documentation for {0} (opens in browser)"+#: src/components/FileTree.tsxmsgid "Documents response did not match expected shape."msgstr "Documents response did not match expected shape."@@ -2797,6 +2909,10 @@ msgstr "Edit {0} source"msgid "Edit {keyName}"msgstr "Edit {keyName}"+#: src/components/settings/rule-option-field.tsx+msgid "Edit in config file"+msgstr "Edit in config file"+#: src/editor/extensions/InternalLinkPropPanel.tsxmsgid "Edit markdown link"msgstr "Edit markdown link"@@ -2849,6 +2965,10 @@ msgstr "Editor status bar"msgid "Editors to install skills into"msgstr "Editors to install skills into"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Edits apply live. Light or dark is chosen from the background."+msgstr "Edits apply live. Light or dark is chosen from the background."+#: src/editor/slash-command/component-items.tsxmsgid "Edits at the source land here — no copy-paste drift."msgstr "Edits at the source land here — no copy-paste drift."@@ -2902,6 +3022,13 @@ msgstr "Empty"msgid "Empty starting content"msgstr "Empty starting content"+#. placeholder {0}: plugin.label+#. placeholder {0}: rule.name+#: src/components/settings/LintingSection.tsx+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Enable {0}"+msgstr "Enable {0}"+#: src/components/AutoSyncOnboardingDialog.tsx#: src/components/EnableSyncConfirmDialog.tsx#: src/components/share-receive-miss-content.tsx@@ -2937,6 +3064,10 @@ msgstr "Enable terminal"msgid "Enable terminal for this project"msgstr "Enable terminal for this project"+#: src/components/settings/LintingSection.tsx+msgid "Enable Themes"+msgstr "Enable Themes"+#: src/components/ActivityModeContent.tsxmsgid "Ended"msgstr "Ended"@@ -2945,6 +3076,10 @@ msgstr "Ended"msgid "Eng specs"msgstr "Eng specs"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Enter a 6-digit hex like #1A2B3C"+msgstr "Enter a 6-digit hex like #1A2B3C"+#: src/components/SeedDialog.tsxmsgid "Enter a folder name (e.g. brain)."msgstr "Enter a folder name (e.g. brain)."@@ -3259,10 +3394,23 @@ msgstr "Failed to render PDF"msgid "Failed to reorder"msgstr "Failed to reorder"+#. placeholder {0}: humanFormat(result.error)+#: src/components/settings/LintingSection.tsx+msgid "Failed to save content rules — {0}"+msgstr "Failed to save content rules — {0}"++#: src/components/settings/LintingSection.tsx+msgid "Failed to save theme setting"+msgstr "Failed to save theme setting"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Failed to update attachment location — {detail}"msgstr "Failed to update attachment location — {detail}"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Failed to update markdownlint rules"+msgstr "Failed to update markdownlint rules"+#: src/components/ObjectWidget.tsx#: src/components/PropertyPanel.tsxmsgid "Failed to update property"@@ -3404,10 +3552,23 @@ msgstr "Fit height"msgid "Fit width"msgstr "Fit width"+#: src/components/ProblemsPanel.tsx+#: src/editor/extensions/markdown-lint-decorations.ts+msgid "Fix"+msgstr "Fix"++#: src/components/ProblemsPanel.tsx+msgid "Fix {flatId}"+msgstr "Fix {flatId}"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Fixed folder in content root"msgstr "Fixed folder in content root"+#: src/components/settings/LintingSection.tsx+msgid "Flag common markdown issues in the editor. Powered by <0>markdownlint<1/></0>."+msgstr "Flag common markdown issues in the editor. Powered by <0>markdownlint<1/></0>."+#: src/lib/keyboard-shortcuts.tsmsgid "Fold or unfold source"msgstr "Fold or unfold source"@@ -3571,6 +3732,15 @@ msgstr "Go back"msgid "Go to line"msgstr "Go to line"+#: src/components/ProblemsPanel.tsx+msgid "Go to line {displayLine}"+msgstr "Go to line {displayLine}"++#. placeholder {0}: file.file+#: src/components/ProblemsPanel.tsx+msgid "Go to line {displayLine} in {0}"+msgstr "Go to line {displayLine} in {0}"+#: src/components/DocPanel.tsx#: src/components/GraphPanel.tsxmsgid "Graph"@@ -3629,10 +3799,18 @@ msgstr "Heading suggestions"msgid "heading-slug"msgstr "heading-slug"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Headings"+msgstr "Headings"+#: src/components/AutoSyncEnableWarning.tsxmsgid "Heads up"msgstr "Heads up"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."+msgstr "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."+#: src/editor/slash-command/embed-starter-items.tsxmsgid "Hello, world!"msgstr "Hello, world!"@@ -4111,10 +4289,18 @@ msgstr "Let Tab leave the source editor instead of indenting."msgid "Level"msgstr "Level"+#: src/components/settings/ColorThemePicker.tsx+msgid "Light"+msgstr "Light"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Light, dark, or follow the OS."msgstr "Light, dark, or follow the OS."+#: src/components/ProblemsPanel.tsx+msgid "line {displayLine}"+msgstr "line {displayLine}"+#: src/editor/bubble-menu/LinkEditPopover.tsx#: src/editor/slash-command/component-items.tsxmsgid "Link"@@ -4157,10 +4343,18 @@ msgstr "Link-graph response did not match expected shape."msgid "Links"msgstr "Links"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Links & images"+msgstr "Links & images"+#: src/components/PropertyWidgets.tsxmsgid "List"msgstr "List"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Lists"+msgstr "Lists"+#: src/components/PageHeaderWidgets.tsx#: src/components/SkillsSidebarSection.tsx#: src/editor/components/TagDialog.tsx@@ -4410,6 +4604,7 @@ msgid "Missing page: {linkTitle}. Click to create."msgstr "Missing page: {linkTitle}. Click to create."#: src/components/FolderOverview.tsx+#: src/components/settings/markdownlint-rule-browser.tsxmsgid "Modified"msgstr "Modified"@@ -4694,6 +4889,10 @@ msgstr "Next source diagnostic"msgid "Next tab"msgstr "Next tab"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."+msgstr "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."+#: src/components/FileSidebar.tsxmsgid "No AI agents installed"msgstr "No AI agents installed"@@ -4865,6 +5064,10 @@ msgstr "No pages matched \"{semanticQueryText}\" by meaning."msgid "No patterns yet. Type a folder or file name below to start hiding files."msgstr "No patterns yet. Type a folder or file name below to start hiding files."+#: src/components/ProblemsPanel.tsx+msgid "No problems found."+msgstr "No problems found."+#: src/components/settings/SkillsManagerSection.tsxmsgid "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."msgstr "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."@@ -4890,6 +5093,10 @@ msgstr "no response"msgid "No results"msgstr "No results"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "No rules match your filters."+msgstr "No rules match your filters."+#: src/components/SkillsSidebarSection.tsxmsgid "No skills yet."msgstr "No skills yet."@@ -5064,6 +5271,10 @@ msgstr "Only external links trigger a request. Links to other documents in thismsgid "Only markdown files"msgstr "Only markdown files"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Only modified"+msgstr "Only modified"+#: src/editor/components/TagDialog.tsxmsgid "Only the current document uses <0>#{tag}</0>."msgstr "Only the current document uses <0>#{tag}</0>."@@ -5577,10 +5788,22 @@ msgstr "Permanently deletes <0>{targetGitPath}</0> and all its git history. Workmsgid "Permission denied"msgstr "Permission denied"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Pick “Custom” above to use this palette."+msgstr "Pick “Custom” above to use this palette."+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."msgstr "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."+#: src/components/settings/SettingsDialogBody.tsx+msgid "Pick a built-in IDE color palette, or define your own."+msgstr "Pick a built-in IDE color palette, or define your own."++#: src/components/settings/SettingsDialogBody.tsx+msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."+msgstr "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."+#: src/components/PublishToGitHubDialog.tsxmsgid "Pick a name"msgstr "Pick a name"@@ -5605,6 +5828,11 @@ msgstr "Plain"msgid "Please enter a valid email address."msgstr "Please enter a valid email address."+#: src/components/settings/LintingSection.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Plugins"+msgstr "Plugins"+#: src/components/settings/SettingsDialogBody.tsx#: src/components/settings/SettingsDialogShell.tsxmsgid "Preferences"@@ -5638,6 +5866,10 @@ msgstr "Previous match"msgid "Previous tab"msgstr "Previous tab"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Primary"+msgstr "Primary"+#: src/components/PublishToGitHubDialog.tsxmsgid "Private"msgstr "Private"@@ -5650,6 +5882,16 @@ msgstr "Private repository"msgid "probe failed"msgstr "probe failed"+#: src/components/DocPanel.tsx+#: src/components/ProblemsPanel.tsx+msgid "Problems"+msgstr "Problems"++#. placeholder {0}: file.file+#: src/components/ProblemsPanel.tsx+msgid "Problems in {0}"+msgstr "Problems in {0}"+#: src/components/HelpPopover.tsxmsgid "Product updates"msgstr "Product updates"@@ -5663,6 +5905,7 @@ msgid "project"msgstr "project"#: src/components/CommandPalette.tsx+#: src/components/PanelScopeHeader.tsx#: src/lib/skill-scope.tsmsgid "Project"msgstr "Project"@@ -5679,6 +5922,10 @@ msgstr "Project folder created, but git init failed. Try again."msgid "Project name"msgstr "Project name"+#: src/components/settings/LintingSection.tsx+msgid "Project plugins are your project's authoring standard — turn them on or off here. The choice is committed to config.yml and shared with every collaborator via git. Each enabled plugin gets its own page under Plugins in the settings sidebar."+msgstr "Project plugins are your project's authoring standard — turn them on or off here. The choice is committed to config.yml and shared with every collaborator via git. Each enabled plugin gets its own page under Plugins in the settings sidebar."+#: src/components/FileTree.tsx#: src/components/SeedDialog.tsxmsgid "Project root"@@ -5852,6 +6099,10 @@ msgstr "Reconnecting after server restart"msgid "Reconnecting…"msgstr "Reconnecting…"+#: src/components/ProblemsPanel.tsx+msgid "Refresh audit"+msgstr "Refresh audit"+#: src/components/InstallInClaudeDesktopDialog.tsx#: src/components/settings/SettingsDialogBody.tsxmsgid "Reinstall"@@ -6109,10 +6360,20 @@ msgstr "Research the extinction of flightless birds"msgid "research-note"msgstr "research-note"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Reset"+msgstr "Reset"++#. placeholder {0}: rule.id+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Reset {0} to default"+msgstr "Reset {0} to default"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset {labelText} to default"msgstr "Reset {labelText} to default"+#: src/components/settings/markdownlint-rule-browser.tsx#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset to default"msgstr "Reset to default"@@ -6266,6 +6527,10 @@ msgstr "Role"msgid "root"msgstr "root"+#: src/components/settings/LintingSection.tsx+msgid "Run a project audit from the Problems panel."+msgstr "Run a project audit from the Problems panel."+#: src/components/settings/TerminalSection.tsxmsgid "Run a real terminal docked inside OpenKnowledge, starting in this project's folder."msgstr "Run a real terminal docked inside OpenKnowledge, starting in this project's folder."@@ -6274,6 +6539,10 @@ msgstr "Run a real terminal docked inside OpenKnowledge, starting in this projecmsgid "Run this in your terminal"msgstr "Run this in your terminal"+#: src/components/ProblemsPanel.tsx+msgid "Running project audit"+msgstr "Running project audit"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Same folder as current file"msgstr "Same folder as current file"@@ -6325,6 +6594,7 @@ msgid "Saving"msgstr "Saving"#: src/components/NewSkillDialog.tsx+#: src/components/PanelScopeHeader.tsxmsgid "Scope"msgstr "Scope"@@ -6391,6 +6661,14 @@ msgstr "Search projects"msgid "Search projects..."msgstr "Search projects..."+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Search rules"+msgstr "Search rules"++#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Search rules by id, alias, or name"+msgstr "Search rules by id, alias, or name"+#: src/components/settings/SearchSection.tsxmsgid "Search settings not yet loaded — try again in a moment"msgstr "Search settings not yet loaded — try again in a moment"@@ -7008,6 +7286,10 @@ msgstr "Stored on this machine."msgid "Strikethrough"msgstr "Strikethrough"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Style"+msgstr "Style"+#: src/components/SeedDialog.tsxmsgid "Subfolder name"msgstr "Subfolder name"@@ -7041,6 +7323,10 @@ msgstr "Suggestion menu open"msgid "Summarize everything I changed this week"msgstr "Summarize everything I changed this week"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Surface"+msgstr "Surface"+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Switch and update branch"msgstr "Switch and update branch"@@ -7302,6 +7588,7 @@ msgid "Terminal settings not yet loaded — try again in a moment"msgstr "Terminal settings not yet loaded — try again in a moment"#: src/components/PropertyWidgets.tsx+#: src/components/settings/CustomThemeEditor.tsxmsgid "Text"msgstr "Text"@@ -7334,6 +7621,10 @@ msgstr "The <0>type</0> every document created from this template gets (e.g. <1>msgid "The agent's persona, values, and voice."msgstr "The agent's persona, values, and voice."+#: src/components/ProblemsPanel.tsx+msgid "The audit could not be completed. Try again."+msgstr "The audit could not be completed. Try again."+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"@@ -7421,10 +7712,20 @@ msgstr "The terminal stopped unexpectedly."msgid "Theme"msgstr "Theme"+#: src/components/settings/LintingSection.tsx+#: src/components/settings/SettingsDialogBody.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Themes"+msgstr "Themes"+#: src/components/TerminalRefusalNotice.tsxmsgid "There's no project folder for this window, so a terminal can't start here."msgstr "There's no project folder for this window, so a terminal can't start here."+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "These rules come from your project's <0>{configFile}</0> file, which fully governs linting for this project. Turn rules on or off and edit their options here; changes write back to the file."+msgstr "These rules come from your project's <0>{configFile}</0> file, which fully governs linting for this project. Turn rules on or off and edit their options here; changes write back to the file."+#: src/components/share-receive-miss-content.tsxmsgid "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>, and that change hasn't synced yet."msgstr "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>, and that change hasn't synced yet."@@ -7476,6 +7777,10 @@ msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're cumsgid "This branch is checked out in:"msgstr "This branch is checked out in:"+#: src/components/PanelScopeHeader.tsx+msgid "This doc"+msgstr "This doc"+#: src/components/ShareFreshnessWarning.tsxmsgid "This doc has unpushed changes. Recipients will see the last pushed version."msgstr "This doc has unpushed changes. Recipients will see the last pushed version."@@ -8052,6 +8357,10 @@ msgstr "Use the default OpenAI endpoint or override it with an OpenAI-compatiblemsgid "User"msgstr "User"+#: src/components/settings/LintingSection.tsx+msgid "User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."+msgstr "User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Using the <0>OK_EMBEDDINGS_API_KEY</0> environment variable (managed outside OpenKnowledge)."msgstr "Using the <0>OK_EMBEDDINGS_API_KEY</0> environment variable (managed outside OpenKnowledge)."@@ -8220,6 +8529,10 @@ msgstr "Where newly added attachments are placed."msgid "Where should it live?"msgstr "Where should it live?"+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Whitespace"+msgstr "Whitespace"+#: src/components/CreatedItemsList.tsxmsgid "Who you are, so the agent has your context."msgstr "Who you are, so the agent has your context."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex fc27f3231..e375fafb5 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -20,6 +20,7 @@"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],"-gdcIo": ["Àũţō-śŷńć ĩś ōń — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ ōń ĩńţēŕvàĺś."],"-i7ik4": ["Ćōĺĺàƥśē ƀũŕśţ ", ["burstNumber"], " ďĩƒƒ"],+ "-kbIAr": ["Ĺĩńķś & ĩḿàĝēś"],"-lCAuQ": ["Ĺōàďĩńĝ ĝŕàƥĥ"],"-o5XAG": ["Śēńţ ƥŕĩvàţēĺŷ ţō ţĥē ŌƥēńĶńōŵĺēďĝē ţēàḿ, àĺōńĝ ŵĩţĥ ŷōũŕ ńōţē àńď àƥƥ vēŕśĩōń. Ńēvēŕ ƥōśţēď ƥũƀĺĩćĺŷ."@@ -87,6 +88,7 @@"12F9WL": ["(ńō ĩď)"],"16D5Zj": ["Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ", ["itemName"], "? Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."],"1AumWo": ["Ƥũśĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],+ "1CalO6": ["Śţŷĺē"],"1EcCom": [["keyName"], " vàĺũē"],"1FLarN": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ćŕēàţē ţō ćōńţĩńũē"],"1GhYxC": ["ōƒ ", ["totalPages"]],@@ -106,6 +108,7 @@"1d1F11": ["Śēĺēćţ àĺĺ ƒĩĺēś àńď ƒōĺďēŕś"],"1di5fu": ["Ďōćũḿēńţ ńōţ ƒōũńď"],"1hvhf0": ["Ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ţĥĩś śķĩĺĺ."],+ "1njn7W": ["Ĺĩĝĥţ"],"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],"1t_NnN": ["ŔēĴēćţ"],"2-CeZn": [@@ -125,6 +128,7 @@"2FnYUD": ["Àƥƥ & śŷśţēḿ ĩńƒō, ŕēćēńţ àƥƥ ĺōĝś, àńď ƥŕōĴēćţ śēŕvēŕ ĺōĝś: ţĥē ēśśēńţĩàĺś ŵē ńēēď ţō ŕēƥŕōďũćē ţĥē ĩśśũē."],+ "2G-56b": ["Ƒàĩĺēď ţō ũƥďàţē ḿàŕķďōŵńĺĩńţ ŕũĺēś"],"2GT3Hf": ["Ĝĺōƀàĺ"],"2H43L8": ["Śēćŕēţś ĺĩķē ÀƤĨ ķēŷś àńď ţōķēńś àŕē ŕēďàćţēď àũţōḿàţĩćàĺĺŷ."],"2IYGkU": ["Ţĥĩś ďōć ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],@@ -139,6 +143,7 @@"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],"2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],+ "2m_bmh": [["label"], " (", ["0"], ")"],"2myNzt": ["Ŵē'vē ƒĩĺēď ĩţ ŵĩţĥ ţĥē ţēàḿ àńď àţţàćĥēď ŷōũŕ ĺōĝś."],"2n3oDU": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ōŕďēŕēď ƀŷ ĩńƀōũńď ĺĩńķ ćōũńţ, ũƥ ţō ",@@ -229,6 +234,7 @@"4c_a6S": ["Ńōţĥĩńĝ śēţ ŷēţ."],"4g19V6": ["Ƒàĩĺēď ţō ũƥďàţē ƥŕōƥēŕţŷ"],"4hJhzz": ["Ţàƀĺē"],+ "4ieVh2": ["Ƥĩćķ “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś ƥàĺēţţē."],"4jDd0j": ["Àńŷōńē ćàń śēē"],"4mLBx9": ["Śũƀśćŕĩƥţĩōńś àŕēń'ţ àvàĩĺàƀĺē ŕĩĝĥţ ńōŵ."],"4niEzY": ["Śàńďƀōxēď ĤŢḾĹ ēḿƀēď — ŵŕĩţē ĤŢḾĹ, śēē ţĥē ŕēńďēŕēď ƥŕēvĩēŵ ĺĩvē."],@@ -246,6 +252,7 @@"4zGlN_": ["Ƥàśţē ĩḿàĝē ŨŔĹ ōŕ ćĺĩćķ ũƥĺōàď"],"5-FeN2": ["Śĥàŕē ŨŔĹ"],"5-o4kO": ["Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],+ "50ORFs": ["Ŕēśēţ ", ["0"], " ţō ďēƒàũĺţ"],"54Y6Fg": ["Ćōũĺď ńōţ ĺōàď ţēḿƥĺàţēś. Ţŕŷ àĝàĩń ĺàţēŕ."],"56WWtu": ["Ćōũĺďń'ţ ĺōàď śţàŕţēŕ ƥàćķś: ", ["error"]],"56xUL1": ["Ƥŕōƥēŕţŷ ńàḿē"],@@ -430,6 +437,7 @@"96w9hU": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ ţĥĩś ƒĩĺē (ĤŢŢƤ ", ["status"], ")."],"99eR72": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē śēĺēćţĩōń"],"9Bd18D": ["Ƒàĩĺēď ţō ĺōàď ĥũƀ ƥàĝēś"],+ "9KooKn": ["Ŕũń à ƥŕōĴēćţ àũďĩţ ƒŕōḿ ţĥē Ƥŕōƀĺēḿś ƥàńēĺ."],"9NJWgv": ["ßàćķĺĩńķś"],"9OIqw4": ["Ŷōũ ďōń'ţ ĥàvē ŵŕĩţē àććēśś ţō ţĥĩś ŕēƥō."],"9PQysm": ["Ĥĩďē àďvàńćēď"],@@ -562,6 +570,7 @@],"CXTwen": ["Ćàń'ţ śàƒēĺŷ ēďĩţ ţĥĩś ƥŕōĴēćţ ćōńƒĩĝ"],"CXj9C-": ["Ńēŵ ƥŕōƥēŕţŷ ńàḿē"],+ "C_Lyvh": ["Ƒàĩĺēď ţō śàvē ţĥēḿē śēţţĩńĝ"],"C_WGy8": ["Ţĥĩś ƒĩĺē ĩś ţōō ĺàŕĝē ţō ōƥēń ĩń ţĥē ƀũĩĺţ-ĩń ţēxţ ēďĩţōŕ (1 Ḿß ĺĩḿĩţ). Ũśē Ōƥēń ƒĩĺē ƀēĺōŵ ţō ōƥēń ĩţ ĩń àńōţĥēŕ àƥƥ."],@@ -602,6 +611,7 @@"DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],"DbILZA": ["Ńō ḿàţćĥēś. Śōḿē ƒĩĺēś àŕē ēxćĺũďēď ƒŕōḿ śēàŕćĥ (ĥĩďďēń ōŕ ĩĝńōŕēď ƒĩĺēś)."],+ "DcLaew": ["Ćũśţōḿ ţĥēḿē"],"DeDYLr": ["Ũńŕēćōĝńĩźēď ŵĩķĩ ĺĩńķ"],"DgcGrb": [["fileCount", "plural", { "one": ["ƒĩĺē"], "other": ["ƒĩĺēś"] }]],"DhK_hZ": [@@ -617,6 +627,7 @@"DiFKSL": ["Ćōũńţĩńĝ ḿàŕķďōŵń ƒĩĺēś"],"Dnn2XG": ["Àũţōḿàţĩć"],"DrYM2Z": ["Śŷńć ďĩśàƀĺēď"],+ "DsDwR-": [["0", "plural", { "one": ["#", " ēŕŕōŕ"], "other": ["#", " ēŕŕōŕś"] }]],"DskIkK": ["Śĩĝń-ĩń śţŕēàḿ ēńďēď ŵĩţĥōũţ ćōńƒĩŕḿàţĩōń — ƥĺēàśē ţŕŷ àĝàĩń"],"Dub54T": ["Ƥŕēvĩēŵ ƀŕōŵśēŕś ćàń'ţ àũţō-ćōƥŷ. Ũśē Ćḿď/Ćţŕĺ+Ć ōń ţĥē ŨŔĹ àƀōvē, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."@@ -650,6 +661,7 @@"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],"EVnzPs": ["Ēďĩţ ŵĩţĥ ÀĨ"],+ "EWPtMO": ["Ćōďē"],"EWX92Z": ["Ćōĺĺàƥśē Àśķ ÀĨ"],"EZVxVz": ["Ŕēƥĺàćē ţĥē àćţĩvē ḿàţćĥ ƒŕōḿ ţĥē ŕēƥĺàćē ƒĩēĺď."],"E_BHoD": [@@ -660,6 +672,7 @@"E_tNGD": ["Ćōńńēćţēď àś @", ["login"]],"Ea1prf": ["Ćĥōōśē ŵĥĩćĥ ēďĩţōŕś ēvēŕŷ śķĩĺĺ ĩń ţĥĩś ƥŕōĴēćţ ĩńśţàĺĺś ĩńţō."],"EarrCe": ["Śēàŕćĥ ēḿōĴĩ"],+ "Eax_et": ["Àććēńţ"],"EbZT7P": ["Ţōĝĝĺē ţĥē ĺēƒţ ƒĩĺē śĩďēƀàŕ."],"EbjWsS": ["Ćũŕŕēńţ ćōḿḿĩţ"],"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],@@ -720,6 +733,7 @@")."],"FXk_zY": ["Àďďś à ĝũĩďēď ŵōŕķƒĺōŵ ƒōŕ àũţĥōŕĩńĝ ńēŵ Àĝēńţ Śķĩĺĺś."],+ "FZtBeR": ["Ēńàƀĺē ", ["0"]],"FgRAvd": ["Ĺōĝś & śŷśţēḿ ĩńƒō"],"FjkaiT": ["Źōōḿ ōũţ"],"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],@@ -736,6 +750,7 @@"G-JBA1": ["Śōũŕćē ḿōďē ŕēǫũĩŕēś à ĺĩvē ćōńńēćţĩōń — ŷōũŕ ēďĩţś àŕē śàvēď àńď ŵĩĺĺ àƥƥēàŕ ŵĥēń ŷōũ ŕēćōńńēćţ."],+ "G-h6qN": [["0", "plural", { "one": ["#", " ōƥţĩōń śēţ"], "other": ["#", " ōƥţĩōńś śēţ"] }]],"G0YZ-I": ["Ĩńďēńţ ōŕ ōũţďēńţ ĺĩśţ ĩţēḿ"],"G1Gw0v": ["Ńēŵ ţēḿƥĺàţē"],"G1XxbZ": ["Ćĥēćķƀōx"],@@ -770,6 +785,7 @@],"G_686w": ["Ţàśķ Ĺĩśţ"],"G_efLf": ["Ĩńśţàĺĺēď ĩńţō"],+ "G_hVTP": ["Ēńàƀĺē Ţĥēḿēś"],"G_mWXb": ["Ƒĩĺţēŕ ĺàńĝũàĝēś"],"GamjcN": ["Ţēḿƥĺàţē śàvēď"],"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],@@ -778,6 +794,7 @@"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],"Gt4gOO": ["Ţĥĩś ƒōĺďēŕ ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],+ "GtJbUa": ["ßàćķĝŕōũńď"],"GuaJb-": ["Ōƥēń ēḿàĩĺ ďŕàƒţ"],"GubkSu": ["Ũśē à śţàŕţēŕ ƥàćķ"],"GuqOb1": ["Ƒàĩĺēď ţō ĺōàď ĥēàďĩńĝś"],@@ -816,6 +833,7 @@],"Hrz9NY": ["Ŵĩķĩ ĺĩńķ"],"HyvSqq": ["ƤŕōĴēćţ Śķĩĺĺ"],+ "I-xnra": [["0"], " ĥēx vàĺũē"],"I1gRhX": ["Ƒàĩĺēď ţō ŕēńàḿē"],"I5685_": ["Ţŕŷ à ƥŕōḿƥţ"],"I5AfhE": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ũńŕēàćĥàƀĺē."],@@ -823,6 +841,7 @@"IA1wNb": ["Ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ďĩďń'ţ ōƥēń ţĥē ƒĩĺē. Ĩś ĩţ ĩńśţàĺĺēď? (", ["msg"], ")"],"IA6JW2": ["Ďēţēćţĩńĝ"],"ICoNYz": ["Ŷōũ ćàń àĺśō ḿàńàĝē ţĥĩś ĩń Śēţţĩńĝś."],+ "IFezUv": ["Ţĥē àũďĩţ ćōũĺď ńōţ ƀē ćōḿƥĺēţēď. Ţŕŷ àĝàĩń."],"IInnZo": ["Ćōńƒĺĩćţ"],"IKkfn_": ["Ŕēƥōŕţ ŕēƒēŕēńćē: ", ["reference"]],"IKoTAC": ["Ķēēƥ ďĩśàƀĺēď"],@@ -864,6 +883,7 @@"JOcPqH": ["ßŕĩńĝ à ŕēḿōţē ŕēƥōśĩţōŕŷ ōńţō ţĥĩś ḿàćĥĩńē."],"JWsZlx": ["Ōƥēń à ƥŕōĴēćţ ţō ēďĩţ."],"JZ8cO6": ["Ĺĩĝĥţ, ďàŕķ, ōŕ ƒōĺĺōŵ ţĥē ŌŚ."],+ "J_bJiH": ["Ƥĩćķ à ƀũĩĺţ-ĩń ĨĎĒ ćōĺōŕ ƥàĺēţţē, ōŕ ďēƒĩńē ŷōũŕ ōŵń."],"Jejur6": ["Ćōũĺďń'ţ ĺōàď ďōćũḿēńţ"],"JfPuv7": [["shareBranch"], " ĩśń'ţ à vàĺĩď ƀŕàńćĥ ńàḿē."],"Jhj_lh": ["Ḿōďĩƒŷ ţĥē ĺĩńķ ţàŕĝēţ, àńćĥōŕ, àńď ďĩśƥĺàŷ ĺàƀēĺ."],@@ -918,6 +938,7 @@"Kr3VPS": ["Ćōďēx ŵĩĺĺ śţĩĺĺ àśķ ũńţĩĺ ŷōũ ŕũń \"ōķ ĩńĩţ\" ĩń à ţēŕḿĩńàĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],"KsAPaB": ["Ţĥĩś ƀŕàńćĥ ĩś ćĥēćķēď ōũţ ĩń:"],"KszKI_": ["Śķĩĺĺ ĺēvēĺ"],+ "KtACeE": ["Ďēƒàũĺţ: <0>", ["0"], "</0>"],"KujtjC": ["Ƒĩńď"],"L-rMC9": ["Ŕēśēţ ţō ďēƒàũĺţ"],"L1ZE3M": ["Ďōćũḿēńţ śţàţĩśţĩćś"],@@ -1041,6 +1062,7 @@"NOHyEE": ["Ŕēţŕŷ ƥũśĥ"],"NORKZU": ["Ƥàţţēŕń ŵàŕńĩńĝś: ", ["summary"]],"NQ8llq": ["Àďď ĩţēḿ"],+ "NQXwDy": ["Ēďĩţ ĩń ćōńƒĩĝ ƒĩĺē"],"NRSLBe": [["diffMin"], "ḿ àĝō"],"NSnIUP": ["Ţŵō-ƥàĝē (ēvēń)"],"NUr4kz": ["À ŕēũśàƀĺē śţàŕţĩńĝ ƥōĩńţ ƒōŕ ńēŵ ďōćũḿēńţś ĩń ţĥĩś ƒōĺďēŕ."],@@ -1049,12 +1071,14 @@"Ŕēàď ţĥŕōũĝĥ ţĥĩś ćōďēƀàśē àńď ďŕàƒţ à ţēćĥńĩćàĺ śƥēć ƒōŕ ţĥē ḿōśţ ćōḿƥĺēx ḿōďũĺē: àń ōvēŕvĩēŵ, ţĥē àŕćĥĩţēćţũŕē, ķēŷ ƒĩĺēś, àńď ōƥēń ǫũēśţĩōńś, àĺĺ ĺĩńķēď ƒŕōḿ à śƥēćś ĩńďēx ƥàĝē."],"NcurBF": ["Ƥàń ďōŵń"],+ "NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],"NkXEFS": ["Ŕēśţōŕē ƒàĩĺēď — ďōćũḿēńţ ũńćĥàńĝēď"],"NmPNJJ": ["Ćōƥŷ ćōďē"],"Nn4GgW": ["Ŵĩĺĺ ƀē ćŕēàţēď àś <0>", ["sanitizedName"], "</0>"],"NnQapF": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"]],"NpC29w": ["Ćŕēàţē à ńēŵ ĺĩśţ ĩţēḿ ƒŕōḿ ţĥē ćũŕŕēńţ ĺĩśţ ĩţēḿ."],+ "NrFwux": ["Ƒàĩĺēď ţō śàvē ćōńţēńţ ŕũĺēś — ", ["0"]],"Nu4DdT": ["Śŷńć"],"Nu4oKW": ["Ďēśćŕĩƥţĩōń"],"NuH1jp": ["Ƥũƀĺĩć ŕēƥōśĩţōŕŷ"],@@ -1089,11 +1113,13 @@"OVjNeX": ["Ţēŕḿĩńàĺ ", ["0"]],"OX2Neh": ["Ĩńĺĩńē ćōďē"],"OXb_Df": ["Śēţţĩńĝś ćōńţēńţ"],+ "OXdGnd": ["Ƥŕōƀĺēḿś"],"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],"OZJeTZ": ["Śķĩĺĺ"],"Oawo4U": ["Ţĥē ŕēƥōŕţ śēŕvĩćē ćōũĺďń'ţ ƀē ŕēàćĥēď."],"OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],"OeAl1e": ["ē.ĝ. àśśēţś/ũƥĺōàďś"],+ "OfhWJH": ["Ŕēśēţ"],"OgyJSr": ["Ĺōćàĺ ōńĺŷ"],"OiHJdA": ["Ḿōvē ţĥŕōũĝĥ śĺàśĥ, ŵĩķĩ-ĺĩńķ, ţàĝ, àńď ƥàţĥ śũĝĝēśţĩōńś; àććēƥţ ōŕ ďĩśḿĩśś ţĥē àćţĩvē śũĝĝēśţĩōń."@@ -1125,6 +1151,7 @@"PCSkw2": ["Śķĩĺĺś"],"PIMM5l": ["Ŷōũ'ŕē śũƀśćŕĩƀēď!"],"PKLY-1": ["Ōƥēńĩńĝ..."],+ "PKjGhT": ["Ĥēàďĩńĝś"],"PMyJ9C": ["Ńō ēďĩţ śēśśĩōń ŷēţ"],"PPFQ3o": ["Ĩńśţàĺĺēď \"", ["0"], "\" ĩńţō ", ["1"]],"PQCdtv": ["\"", ["docName"], "\" ďōēśń'ţ ēxĩśţ."],@@ -1133,6 +1160,9 @@"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],"PZtgO0": ["Ōƥēńĩńĝ ŵōŕķţŕēē"],"P_bX4O": ["Ĥōŵ ţō śēţ ũƥ"],+ "Pck6eI": [+ "Ƥĩćķ à ƀũĩĺţ-ĩń ĨĎĒ ƥàĺēţţē. Ţĥē ďàŕķ ĨĎĒ ţĥēḿēś ōvēŕŕĩďē ţĥē ĺĩĝĥţ/ďàŕķ śēţţĩńĝ ĩń Ƥŕēƒēŕēńćēś."+ ],"PdA9NZ": [["ahead"], " àĥēàď"],"PdJZ5p": ["Ńō śķĩĺĺś ŷēţ."],"Pgu10b": ["Śàvēď àś <0>", ["slug"], ".ḿď</0>"],@@ -1190,6 +1220,7 @@"À ŕēàĺ śĥēĺĺ ĩś ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕńĩńĝ ĩţ ōń ŕũńś ćōḿḿàńďś ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ."],"R9IDFz": ["Ŕēńàḿēś ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ĩţ."],+ "R9Khdg": ["Àũţō"],"RDjuBN": ["Śēţũƥ"],"RDrXh4": ["Ćōńƒĩĝũŕē ũśēŕ, ƥŕōĴēćţ, àńď ĩńţēĝŕàţĩōń śēţţĩńĝś."],"RG4XHV": ["Ćōƥŷ ", ["0"], " ƥŕōḿƥţ"],@@ -1209,6 +1240,7 @@"Rb1zMa": ["Ńō ēxćēŕƥţ"],"RfHNf8": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"]],"RfaEio": ["Ţōĝĝĺē śōũŕćē ćōḿḿēńţ"],+ "RfilGt": ["Ńō ŕũĺēś ḿàţćĥ ŷōũŕ ƒĩĺţēŕś."],"RgbKEe": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ŕēƥōśĩţōŕŷ."],"Rj01Fz": ["Ĺĩńķś"],"RlCInP": ["Śĺàśĥ ćōḿḿàńďś"],@@ -1218,6 +1250,7 @@"RobAKV": ["Ũƥďàţē ţĥē ďēśţĩńàţĩōń àńď ōƥţĩōńàĺ śēćţĩōń àńćĥōŕ."],"Rq1vFD": ["Ţŕēē vĩēŵ ōƥţĩōńś"],"RrAIZx": ["Ŵĥàţ ćōńƒĩĝ śĥàŕĩńĝ ćōvēŕś"],+ "Rsdhj9": ["Ćōńƒĩĝũŕàţĩōń ŵàŕńĩńĝś"],"Rx5ReQ": ["Ŕēńàḿē ", ["keyName"]],"RyIKxy": ["Ţĥĩś ",@@ -1262,12 +1295,17 @@"TJnkyf": ["ōķ ũĩ ŕēśƥōńďēď ƀũţ śēŕvēŕ.ĺōćķ ĥàś ńō ƥōŕţ ŷēţ"],"TKQ7K-": ["Ĩńśţàĺĺ"],"TLIO3j": ["Ţōĝĝĺē ĩţàĺĩć ƒōŕḿàţţĩńĝ."],+ "T_R-Qz": ["Ƥŕĩḿàŕŷ"],"T_wG4n": ["Ŵē ćōũĺďń'ţ ćĥēćķ ŷōũŕ ĜĩţĤũƀ ćōńńēćţĩōń."],"Ta25TG": ["Ńō ĥĩśţōŕŷ ŷēţ"],"TbjyhA": ["Ďōćś"],+ "Te6sK2": [+ "Ĥēàďś ũƥ: ēďĩţĩńĝ àńŷ ŕũĺē ōŕ ōƥţĩōń ĥēŕē ćŕēàţēś à <0>.ḿàŕķďōŵńĺĩńţ.Ĵśōń</0> ƒĩĺē ĩń ŷōũŕ ƥŕōĴēćţ ţō śàvē ŷōũŕ ćĥàńĝēś."+ ],"ThmUrC": ["Ćōũĺď ńōţ ƒĩńàĺĩźē ƥŕōĴēćţ śēţũƥ. Ţŕŷ àĝàĩń."],"Tjc1pH": ["Śēćţĩōń <0>(ōƥţĩōńàĺ ĥēàďĩńĝ àńćĥōŕ)</0>"],"TsZmgr": ["Ţĥē ƒĩĺē ōń ďĩśķ, àńď ţĥē ĩď àĝēńţś ũśē."],+ "TvY_XA": ["Ďōćũḿēńţàţĩōń"],"TwYboS": ["Ńàvĩĝàţē ĆōďēḾĩŕŕōŕ śōũŕćē śēàŕćĥ ŕēśũĺţś ōŕ ďĩśḿĩśś ţĥē śēàŕćĥ ƥàńēĺ."],"Tz0i8g": ["Śēţţĩńĝś"],"Tz9pJB": ["Ćĺōńē śţŕēàḿ ēńďēď ũńēxƥēćţēďĺŷ — ćĥēćķ ĩƒ ţĥē ćĺōńē ćōḿƥĺēţēď"],@@ -1317,6 +1355,7 @@"UhpfxY": ["Ƥàń ĺēƒţ"],"UkQGhd": ["Ĥĩďē ŕēƥĺàćē"],"Up2_7p": ["Ćōƥŷ ƒũĺĺ ƥàţĥ"],+ "UpCz01": ["Ţĥĩś ďōć"],"UuYo7g": ["Ţĥĩś ",["targetNoun"],@@ -1325,6 +1364,11 @@"Uuj_R4": ["Ńēŵ ƒŕōḿ ţēḿƥĺàţē"],"Uw6ERJ": ["Ćōũĺďń'ţ ćōƥŷ: ", ["detail"]],"UyROxs": [["mins", "plural", { "one": ["#", " ḿĩń àĝō"], "other": ["#", " ḿĩń àĝō"] }]],+ "V2Gmie": [+ "Ţĥēśē ŕũĺēś ćōḿē ƒŕōḿ ŷōũŕ ƥŕōĴēćţ'ś <0>",+ ["configFile"],+ "</0> ƒĩĺē, ŵĥĩćĥ ƒũĺĺŷ ĝōvēŕńś ĺĩńţĩńĝ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕń ŕũĺēś ōń ōŕ ōƒƒ àńď ēďĩţ ţĥēĩŕ ōƥţĩōńś ĥēŕē; ćĥàńĝēś ŵŕĩţē ƀàćķ ţō ţĥē ƒĩĺē."+ ],"V48OUT": ["Ŷōũ ďēĺēţēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ḿōďĩƒĩēď ũƥśţŕēàḿ."],"V7QxyT": ["Ćōńńēćţĩōń ďŕōƥƥēď"],"VAHWL_": ["Ćōńńēćţēď àś <0>@", ["signedInLogin"], "</0>"],@@ -1349,6 +1393,7 @@"VbqhBI": ["Àĺŕēàďŷ àţ ", ["assetContentPath"], " — ŕēũśĩńĝ."],"VcqWBy": ["Ũƥĺōàď ḿàŷ ĥàvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ĩś ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],+ "Vftef5": ["Ćōḿḿōń ḿàŕķďōŵń ĩśśũēś — ĥàŕď ţàƀś, ĥēàďĩńĝ ĩńćŕēḿēńţś, ĺĩśţ ḿàŕķēŕś, àńď ḿōŕē."],"Vlc75q": ["Ķēēƥ ƒĩĺē ďēĺēţēď"],"VsaI0G": [["folderCount", "plural", { "one": ["ƒōĺďēŕ"], "other": ["ƒōĺďēŕś"] }]],"VuxVSP": ["Śţàŕţ śōũŕćē ćōḿƥĺēţĩōń"],@@ -1357,6 +1402,7 @@"VzGJRl": ["Àďď ĺĩńķ"],"W-ntoW": ["ĥēàďĩńĝ-śĺũĝ"],"W0i24j": ["ŌƀĴēćţ"],+ "W1SI2K": [["0", "plural", { "one": ["#", " ŵàŕńĩńĝ"], "other": ["#", " ŵàŕńĩńĝś"] }]],"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],"W3Xlpc": ["Śēţ ţĥē àũţō-śŷńć ďēƒàũĺţ ƒōŕ ũśēŕś ōƥēńĩńĝ ţĥĩś ƥŕōĴēćţ ƒōŕ ţĥē ƒĩŕśţ ţĩḿē. Ţĥĩś śēţţĩńĝ ĩś ćōḿḿĩţţēď ţō ŷōũŕ ŕēƥōśĩţōŕŷ."@@ -1369,6 +1415,7 @@],"W8vpBM": ["śţàŕţēŕ ƥàćķ"],"W9_Bub": ["Ĺōćàĺ ćĥàńĝēś ōvēŕĺàƥ ŵĩţĥ ĩńćōḿĩńĝ śŷńć"],+ "WFEbV1": ["Ƒĺàĝ ćōḿḿōń ḿàŕķďōŵń ĩśśũēś ĩń ţĥē ēďĩţōŕ. Ƥōŵēŕēď ƀŷ <0>ḿàŕķďōŵńĺĩńţ<1/></0>."],"WHPvOb": ["Àĺĺ ƒĩĺēś àŕē ĥĩďďēń ƀŷ vĩēŵ ƒĩĺţēŕś."],"WJjviG": ["Ŵĥàţ ţō ĩńćĺũďē"],"WL6puM": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ƥŕōĴēćţ"],@@ -1380,6 +1427,7 @@"WPwDin": ["Ōƥēń ƒōĺďēŕ ōń ďĩśķ"],"WR0y2O": ["Śĥàŕē ƒōĺďēŕ"],"WRNXKp": ["Śēàŕćĥĩńĝ"],+ "WRdYfS": ["Ŕēƒŕēśĥ àũďĩţ"],"WWcqsG": ["Śţàŕţ ĥēŕē: ŵĥàţ ţĥĩś ĩś àńď ĥōŵ ĩţ'ś ōŕĝàńĩźēď."],"WZ-vBy": ["Ƥēŕḿàńēńţĺŷ ďēĺēţēś <0>",@@ -1456,6 +1504,7 @@"Y6SK9K": ["Śĥōŵ śōũŕćē"],"Y8ViJx": ["À ńēŵēŕ vēŕśĩōń ḿàŷ ĥàvē ƀēēń ďēƥĺōŷēď śĩńćē ţĥĩś ţàƀ ōƥēńēď."],"YC6_wP": ["Ēďĩţ ", ["keyName"]],+ "YEIS9T": ["Ēďĩţś àƥƥĺŷ ĺĩvē. Ĺĩĝĥţ ōŕ ďàŕķ ĩś ćĥōśēń ƒŕōḿ ţĥē ƀàćķĝŕōũńď."],"YEP3X2": ["Ďēĺēţē à ţàƀĺē ŵĥēń ţĥē àćţĩvē ţàƀĺē ćēĺĺ śēĺēćţĩōń ćōvēŕś ţĥē ƒũĺĺ ţàƀĺē."],"YGIi_c": ["Ŕēĩńśţàĺĺ"],"YIp4R0": [@@ -1465,6 +1514,9 @@"YKLP_-": ["Ţēḿƥĺàţē ŕēńàḿēď"],"YLMBSd": ["ē.ĝ. Ţĥē ēďĩţōŕ ƒŕōźē àƒţēŕ Ĩ ƥàśţēď à ĺàŕĝē ţàƀĺē"],"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],+ "YRavYS": [+ "À ƥēŕśōńàĺ ćōĺōŕ-ţĥēḿē ƥĩćķēŕ — ńōţ śĥàŕēď ŵĩţĥ ŷōũŕ ƥŕōĴēćţ. Ŵĥēń ōń, ĩţ àƥƥēàŕś ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śĩďēƀàŕ."+ ],"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],"YW7Q86": ["Śēàŕćĥ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],@@ -1488,6 +1540,9 @@"Z5h97D": ["Ĥĩďē ƒĩĺēś àńď ƒōĺďēŕś ƒŕōḿ ŷōũŕ ķńōŵĺēďĝē ƀàśē. Ĥĩďďēń ĩţēḿś ďōń’ţ àƥƥēàŕ ĩń ţĥē ƒĩĺē ţŕēē, śēàŕćĥ, ōŕ ÀĨ ţōōĺś. <0>Ĺēàŕń ḿōŕē àƀōũţ ƥàţţēŕńś</0>."],+ "Z6rrjc": [+ "Ńō <0>.ḿàŕķďōŵńĺĩńţ.*</0> ƒĩĺē ŷēţ — ēvēŕŷ ŕũĺē ŕũńś ōń ţĥē śàḿē ďēƒàũĺţś àś ţĥē VŚ Ćōďē ḿàŕķďōŵńĺĩńţ ēxţēńśĩōń: àĺĺ ōń, ēxćēƥţ ĺĩńē ĺēńĝţĥ."+ ],"Z8KDox": ["Ēńţēŕ à ƒōĺďēŕ ńàḿē (ē.ĝ. ƀŕàĩń)."],"Z8lGw6": ["Śĥàŕē"],"ZARuZJ": ["Ćōũĺďń'ţ ĺōàď ƒĩĺēś"],@@ -1499,6 +1554,7 @@"). Ōţĥēŕ ƒĩĺēś àńď ŵŕĩţēŕś àŕē ũńàƒƒēćţēď."],"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],+ "ZI8uvA": ["Ńō ƥŕōƀĺēḿś ƒōũńď."],"ZLQol-": ["Ŷōũ ćàń ţũŕń ţĥĩś ōń ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],"ZNK2Tq": ["ŕōōţ"],"ZQJ1IV": ["Àćţĩvàţē ţĥē ĺàśţ ēďĩţōŕ ţàƀ."],@@ -1590,6 +1646,7 @@"aENGMB": ["Śēḿàńţĩć śēàŕćĥ àďďś ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō ţĥē śēàŕćĥ ţōōĺ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĩţĥōũţ śĥàŕēď ķēŷŵōŕďś."],+ "aHPdYV": ["Ĝō ţō ĺĩńē ", ["displayLine"]],"aM23Wr": ["ƥàĝē-ńàḿē"],"aOp3hw": ["Ćōũĺďń'ţ ḿōvē ţō Ţŕàśĥ"],"aWlJai": ["Śţàŕţĩńĝ śĩĝń-ĩń ƒĺōŵ"],@@ -1635,6 +1692,7 @@],"bwil08": ["ßũĩĺďĩńĝ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńĩńĝ ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],"c1LZZH": ["Ĺĩńķ ćōƥĩēď."],+ "c4fVUV": ["Ƒĩx"],"c5f7sm": ["Ćōďē ƀĺōćķ ĺàńĝũàĝē: ", ["currentLabel"], ". Ćĺĩćķ ţō ćĥàńĝē."],"c5rF4v": ["Ŵĥàţ ĩś ţĥĩś ķńōŵĺēďĝē ƀàśē ƒōŕ?"],"c863eW": ["Ćōũĺď ńōţ śŵĩţćĥ ţō ", ["shareBranch"], ". Ţŕŷ śŵĩţćĥĩńĝ ḿàńũàĺĺŷ."],@@ -1648,6 +1706,7 @@"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],"cN1Gcp": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ", ["shareBranch"], " àĺŕēàďŷ ēxĩśţś."],+ "cOJyVj": ["Ďĩśàƀĺē Ţĥēḿēś"],"cOSAfL": ["Ńō ŕēƥōśĩţōŕĩēś ƒōũńď ōń ŷōũŕ ĜĩţĤũƀ àććōũńţ."],"cOrTMo": ["Ŷōũŕ śĥàŕē ĺĩńķ ĩś ŕēàďŷ ƀēĺōŵ."],"cRHuuI": ["Ćōũĺďń'ţ ćōƥŷ ƥàţĥ"],@@ -1660,6 +1719,7 @@"cZGNlb": ["Àďď àńōţĥēŕ ƥàţţēŕń"],"cZI5AL": ["ŌĶ Ďēśķţōƥ"],"cZ_8zB": ["Śţàŷś ōń ţĥĩś ćōḿƥũţēŕ."],+ "ccNps_": ["Ōńĺŷ ḿōďĩƒĩēď"],"cd5EXh": ["Ŕēƥōŕţ à ƀũĝ"],"cdm00A": ["Ńō Ĩńćōḿĩńĝ"],"cdmk8A": ["Ũńćōḿḿĩţţēď ćĥàńĝēś"],@@ -1680,6 +1740,7 @@],"d2uTPx": ["Śēŕvēŕ ēŕŕōŕ (ĤŢŢƤ ", ["status"], ")"],"d5rK4X": [["chars", "plural", { "one": ["ćĥàŕ"], "other": ["ćĥàŕś"] }]],+ "dCIGNG": ["ßōŕďēŕ"],"dD7NPy": ["Ōũţĺĩńē"],"dDpCOp": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],"dEgA5A": ["Ćàńćēĺ"],@@ -1706,6 +1767,7 @@"Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."],"dURmlQ": ["\"ƒŕōńţḿàţţēŕ\" ĩś à ŕēśēŕvēď ƥŕōƥēŕţŷ ńàḿē"],+ "dVaXnv": ["Ćōńţēńţ ŕũĺēś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],"dXWMFn": ["Ŕēḿōvēś ţĥĩś śķĩĺĺ ƒŕōḿ ŷōũŕ ēďĩţōŕś."],"dbapvC": ["Ƒōĺĺōŵ ũś ōń śōćĩàĺ ḿēďĩà"],"dbhUX1": ["Ĥĩďē ţĥĩś ƒĩĺē"],@@ -1719,6 +1781,7 @@"dvGKu2": ["Śĥàŕēď àũţō-śŷńć ďēƒàũĺţ"],"dw_3cv": ["Ŕēńàḿē śķĩĺĺ"],"dw_dUJ": ["Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥàţĥ"],+ "dx-TwN": ["Ŕũńńĩńĝ ƥŕōĴēćţ àũďĩţ"],"e0NrBM": ["ƤŕōĴēćţ"],"e1Rn_k": ["Ōƥēń ćōńţàĩńĩńĝ ƒōĺďēŕ"],"e1hptq": ["Ēḿƀēď à vĩďēō ŵĩţĥ ńàţĩvē ƥĺàŷēŕ ćōńţŕōĺś."],@@ -1743,6 +1806,7 @@"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],"el312q": ["Ĩńśţàĺĺ śķĩĺĺś ĩńţō"],"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],+ "enPTnx": ["ĺĩńē ", ["displayLine"]],"eneWvv": ["Ďŕàƒţ"],"epuNYK": ["Ḿàŕķ à ƀĺōćķ àś ţĥē śōũŕćē ōƒ ţŕũţĥ. Ḿĩŕŕōŕś ēĺśēŵĥēŕē ũƥďàţē ĺĩvē àś ŷōũ ēďĩţ ĩţ."@@ -1756,6 +1820,7 @@"fBHvBn": ["Ţĥēŕē'ś ńō ƥŕōĴēćţ ƒōĺďēŕ ƒōŕ ţĥĩś ŵĩńďōŵ, śō à ţēŕḿĩńàĺ ćàń'ţ śţàŕţ ĥēŕē."],"fG0X0e": ["Ĩńśţàĺĺ ", ["brand"], " →"],"fIgqfQ": ["Ŕēĩńśţàĺĺĩńĝ"],+ "fJ3EbT": ["Ţĥēḿēś"],"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],"fNr-MX": ["Ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ"],"fR-Kdc": ["(ƥŕōĴēćţ-ĺēvēĺ ōńĺŷ)"],@@ -1764,6 +1829,7 @@"fWsBTs": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ. Ƥĺēàśē ţŕŷ àĝàĩń."],"fYKgzG": ["Ƒàĩĺēď ţō ĺōàď ŕēćēńţ ƥŕōĴēćţś."],"fYjgXu": ["Ũńōŕďēŕēď ĺĩśţ ōƒ ĩţēḿś."],+ "fZj9em": ["Ƒĩx ", ["flatId"]],"f_PkYv": ["Ŕēśţàŕţĩńĝ ćĺōśēś ţĥĩś ƥŕōĴēćţ'ś śēŕvēŕ. Ćōńńēćţēď àĝēńţś (Ćĺàũďē Ćōďē, Ćōďēx, Ćũŕśōŕ) ŵĩĺĺ śēē ţĥēĩŕ ŌƥēńĶńōŵĺēďĝē ḾĆƤ ćōńńēćţĩōń ćĺōśē ũńēxƥēćţēďĺŷ — ŷōũ ḿàŷ ńēēď ţō ŕēśţàŕţ ţĥē àĝēńţ, ōŕ ţōĝĝĺē ĩţś ŌƥēńĶńōŵĺēďĝē ḾĆƤ śēŕvēŕ ōƒƒ àńď ōń, ţō ŕēćōńńēćţ."],@@ -1826,6 +1892,7 @@"gwykHF": ["Ţĥĩś ďōć ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],"h-AdvS": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē àĺŕēàďŷ ĥēŕē, śō ţĥēŕē'ś ńōţĥĩńĝ ţō àďď."],"h06R3C": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ōũţĝōĩńĝ ĝŕàƥĥ ĺĩńķś."],+ "h16FyT": ["Ĺĩśţś"],"h3QZcB": ["À ƀŕàńćĥ ńàḿēď ",["shareBranch"],@@ -1900,6 +1967,7 @@"iGCs04": ["Ńō ţēḿƥĺàţēś àvàĩĺàƀĺē"],"iH8pgl": ["ßàćķ"],"iHAJDj": ["Ŕēśōĺvĩńĝ ďēƒàũĺţ ĺōćàţĩōń"],+ "iIaSUD": ["Ŵĥĩţēśƥàćē"],"iKSP5j": ["Ŵōŕď ŵŕàƥ"],"iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],"iMkWoF": ["Ţũŕń ōń"],@@ -1933,6 +2001,7 @@"Śēţũƥ ƒĩĺēś ĩńćĺũďē: <0>.ōķ/</0>, ÀĨ-ţōōĺ ḾĆƤ ćōńƒĩĝś (<1>.ḿćƥ.Ĵśōń</1> àńď ƥēŕ-ţōōĺ ƒĩĺēś), ƥŕōĴēćţ śķĩĺĺś.<2/><3>Śĥàŕēď</3> ćōḿḿĩţś ţĥēḿ ţō ĝĩţ, śō àńŷōńē ŵĥō ćĺōńēś ţĥē ŕēƥō ĝēţś ţĥē śàḿē śēţũƥ. <4/><5>Ĺōćàĺ ōńĺŷ</5> ķēēƥś ţĥēḿ ōũţ ōƒ ĝĩţ (vĩà <6>.ĝĩţ/ĩńƒō/ēxćĺũďē</6>)."],"iuTKci": ["Ńō ēďĩţś ŷēţ."],+ "iv452l": ["Ďōćũḿēńţàţĩōń ƒōŕ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],"iycx_A": ["Ƥũśĥĩńĝ"],"j9Vqvc": ["ĩńĥēŕĩţēď"],"j9tqwO": ["Ńōţ ĩń śĩďēƀàŕ"],@@ -1968,6 +2037,9 @@"</0> àĺŕēàďŷ ēxĩśţś ĥēŕē. Śàvĩńĝ ćŕēàţēś à ĺōćàĺ ćōƥŷ ţĥàţ ōvēŕŕĩďēś ĩţ ƒōŕ ţĥĩś ƒōĺďēŕ."],"k0vc0N": ["Ńēŵ ţēŕḿĩńàĺ ţàƀ"],+ "k2fEi7": [+ "Ũśēŕ ƥĺũĝĩńś àŕē ƥēŕśōńàĺ ţō ţĥĩś ďēvĩćē — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĺĩvēś ĩń ŷōũŕ ũśēŕ ćōńƒĩĝ àńď ĩś ńēvēŕ ćōḿḿĩţţēď ţō ţĥē ƥŕōĴēćţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."+ ],"k4CuuV": ["Ŕēàďŷ-ḿàďē ƒōĺďēŕś àńď ţēḿƥĺàţēś ţō ĝēţ ŷōũ śţàŕţēď ǫũĩćķĺŷ. Śēĺēćţ à ƥàćķ ţō ƥŕēvĩēŵ ŵĥàţ ĝēţś ćŕēàţēď, ţĥēń àďď ĩţ ţō ŷōũŕ ƥŕōĴēćţ."],@@ -1979,6 +2051,7 @@" ŕēàďŷ. Ŕēśũĺţś ḿàŷ ƀē ĩńćōḿƥĺēţē."],"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],+ "kDwcbW": ["Ĝō ţō ĺĩńē ", ["displayLine"], " ĩń ", ["0"]],"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],"kLv8d3": ["Ŷōũŕ ćōƥŷ ōƒ ƀŕàńćĥ <0>",@@ -1993,6 +2066,16 @@"Ďōń'ţ śēē <0>Śķĩĺĺś</0>? Ēńàƀĺē <1>Śēţţĩńĝś <2/> Ćàƥàƀĩĺĩţĩēś <3/> Ćōďē ēxēćũţĩōń àńď ƒĩĺē ćŕēàţĩōń</1> ƒĩŕśţ."],"kYL1lH": ["Àĝēńţ àćţĩvĩţŷ"],+ "k_Dqw1": [+ [+ "0",+ "plural",+ {+ "one": ["Ńō ƥŕōƀĺēḿś àćŕōśś ", "#", " ďōćũḿēńţ."],+ "other": ["Ńō ƥŕōƀĺēḿś àćŕōśś ", "#", " ďōćũḿēńţś."]+ }+ ]+ ],"k_pade": ["Ćōńƒĩĝ śĥàŕĩńĝ ĩś ńōŵ śĥàŕēď. Ćōḿḿĩţ ţĥē ŌĶ ƒĩĺēś ţō śĥàŕē ŵĩţĥ ŷōũŕ ţēàḿ."],"k_yIIc": ["Ŵĩĺĺ ƀē ćŕēàţēď àţ: <0>", ["targetPreview"], "</0>"],"kdzzOK": ["Ōƒƒ — śēàŕćĥ ŕàńķś ƀŷ ķēŷŵōŕď ōńĺŷ. Ńō ćōńţēńţ ĺēàvēś ţĥĩś ćōḿƥũţēŕ."],@@ -2006,6 +2089,7 @@"kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],"ku0yLQ": ["Ƥàĝēś àŕē ēḿƀēďďēď ţĥē ƒĩŕśţ ţĩḿē à śēàŕćĥ ńēēďś ţĥēḿ."],"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],+ "l-4nnw": ["Śēàŕćĥ ŕũĺēś"],"l17ab4": ["Ćōũĺď ńōţ ŵŕĩţē ƥŕōĴēćţ ƒĩĺēś. Ţŕŷ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],"l1aQKz": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē"],"l1l8sj": [["0"], "ď àĝō"],@@ -2188,6 +2272,9 @@"oQA-cA": ["Ƒũĺĺ ƥàţĥ"],"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],"oXKEsy": ["Ďēĺēţē àń àďĴàćēńţ ŵĩķĩ-ĺĩńķ ōŕ ţàĝ ćĥĩƥ."],+ "oXlLi4": [+ "ƤŕōĴēćţ ƥĺũĝĩńś àŕē ŷōũŕ ƥŕōĴēćţ'ś àũţĥōŕĩńĝ śţàńďàŕď — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĩś ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ àńď śĥàŕēď ŵĩţĥ ēvēŕŷ ćōĺĺàƀōŕàţōŕ vĩà ĝĩţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."+ ],"oYepHb": ["Ţĥē ţēŕḿĩńàĺ ĩś ţũŕńēď ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕń ĩţ ƀàćķ ōń ţō ŕũń ćōḿḿàńďś ĥēŕē."],@@ -2195,6 +2282,7 @@"Ŷōũ ƥĩćķēď ~/Ďōćũḿēńţś. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷ ḿàŕķďōŵń ƒĩĺē ũńďēŕ ĩţ. Ĩƒ ŷōũ ōńĺŷ ŵàńţ ţō ḿàńàĝē à śũƀ-ƒōĺďēŕ, ćĥōōśē à śḿàĺĺēŕ śćōƥē."],"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],+ "ohUJJM": ["Ƥĺũĝĩńś"],"omXJcU": ["Ćĺōśē ōţĥēŕś"],"optX0N": [["0"], "ĥ àĝō"],"oqB2ez": ["Ƥŕēvĩōũś ḿàţćĥ"],@@ -2235,6 +2323,7 @@"pmUArF": ["Ŵōŕķśƥàćē"],"ppDgFi": ["Ŕēśţàŕţ ŵĩţĥ ţĥĩś àƥƥ'ś vēŕśĩōń"],"psfGPX": ["ḾĆƤ ćōńńēćţĩōńś"],+ "pvnfJD": ["Ďàŕķ"],"pzutoc": ["Ĩţàĺĩć"],"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],@@ -2265,6 +2354,7 @@"qbfj1f": ["Ŕēćēĩvĩńĝ ōƀĴēćţś"],"qdBUHP": ["Ćōũĺďń'ţ ĺōàď ", ["fileName"]],"qi1F96": ["Ŕēvēàĺ ĩń Ƒĩĺē Ēxƥĺōŕēŕ"],+ "qiN9NB": ["Śũŕƒàćē"],"qiRoLb": ["Śũḿḿàŕĩźē ēvēŕŷţĥĩńĝ Ĩ ćĥàńĝēď ţĥĩś ŵēēķ"],"qioCwA": ["ĵũḿƥ ţō ƥàĝē ", ["pageNumber"]],"qjHMHf": ["Ƒàĩĺēď ţō ďĩśàƀĺē śŷńć — ", ["detail"]],@@ -2288,6 +2378,7 @@"rD-woT": ["Ţēĺĺ ũś ŵĥàţ ŵēńţ ŵŕōńĝ àńď ŵē'ĺĺ ĝàţĥēŕ ţĥē ĺōĝś. Ńōţĥĩńĝ ĺēàvēś ŷōũŕ Ḿàć ũńţĩĺ ŷōũ'vē ŕēvĩēŵēď ĩţ."],+ "rFmBG3": ["Ćōĺōŕ ţĥēḿē"],"rFw02Q": ["Ũƥĺōàďĩńĝ ", ["keyName"]],"rJVoVX": ["Śōũŕćē ƒĩńď ŕēśũĺţś"],"rNifQd": ["Ŕēḿōvē ƥŕōƥēŕţŷ"],@@ -2555,6 +2646,7 @@"y3aU20": ["Śàvē ćĥàńĝēś"],"y46m5r": ["Ţĥē ďēśķţōƥ àƥƥ ĩśń'ţ ŕēśƥōńďĩńĝ. Ŕēƒŕēśĥ àńď ţŕŷ àĝàĩń."],"y5FUYi": ["Śũĝĝēśţĩōń ḿēńũ ōƥēń"],+ "y5UgU8": ["Ďĩśàƀĺē ", ["0"]],"y8B54M": ["Ćōũĺďń'ţ śēńď ŷōũŕ ƥŕōḿƥţ — ƥĺēàśē ţŕŷ àĝàĩń."],"yCX4jp": [" Ŷōũŕ śēĺēćţĩōń ćōũĺď ńōţ ƀē ŕēśţōŕēď."],"yEJ-sl": [@@ -2579,6 +2671,7 @@"yMgL_E": ["Ƒĩńď ƒĩēĺď ńàvĩĝàţĩōń"],"yQE2r9": ["Ĺōàďĩńĝ"],"yQyglE": ["Ńō ḿàţćĥĩńĝ ďōćś"],+ "yR5LHI": ["Ēńţēŕ à 6-ďĩĝĩţ ĥēx ĺĩķē #1À2ß3Ć"],"yUxR-Q": ["Ēxƥàńď ", ["keyName"]],"yWSvcf": ["Ćōńţēńţ ŕōōţ"],"yWWThY": ["Àśśēţ ŕēƒēŕēńćē"],@@ -2587,6 +2680,7 @@"y_5CE8": ["Ĩţēḿ ", ["0"]],"y_K0Dz": ["Ŵĥàţ ĥàƥƥēńēď?"],"yaPGPa": ["Ōƥēń à ƥŕōĴēćţ ţō ḿàńàĝē ĩţś ÀĨ ţōōĺ ćōńńēćţĩōńś."],+ "yf5auF": ["Śēàŕćĥ ŕũĺēś ƀŷ ĩď, àĺĩàś, ōŕ ńàḿē"],"yf5r22": [["keyName"]," ţŷƥē: ",@@ -2618,6 +2712,7 @@"z60Lgn": ["Śàvēś ţĥē ƒĩĺē ţō <0>~/Ďōŵńĺōàďś/ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńś ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ. Ŕēǫũĩŕēś Ńōďē.Ĵś ōŕ ßũń ōń ŷōũŕ ƤÀŢĤ."],+ "zAJzIg": ["Ƥŕōƀĺēḿś ĩń ", ["0"]],"zAsDLY": ["Ĝŕàƥĥ vĩśũàĺĩźàţĩōń ōƒ ďōćũḿēńţ ĺĩńķś"],"zKxoPm": ["Ćōũĺďń'ţ ŕēńàḿē \"", ["0"], "\": ", ["1"]],"zL0LPh": ["Ĝĺōƀàĺ ōũţśĩďē ţēxţ ƒĩēĺďś"],@@ -2626,6 +2721,9 @@"zQBg2C": ["Ḿōvē ţĥē ćũŕŕēńţ ƀĺōćķ ũƥ ōŕ ďōŵń ōńē ƥōśĩţĩōń."],"zUhPuR": ["Ōƥēń ćōńţàĩńĩńĝ ƒōĺďēŕ, ", ["hint"]],"zXj1rA": ["Śēàŕćĥ ƀŷ ḿēàńĩńĝ"],+ "zYp8Sr": [+ "À <0>Ḿōďĩƒĩēď</0> ƀàďĝē ḿàŕķś ŕũĺēś ŷōũŕ ćōńƒĩĝ śēţś ēxƥĺĩćĩţĺŷ — ďĩŕēćţĺŷ, ōŕ ĩńĥēŕĩţēď ţĥŕōũĝĥ <1>ēxţēńďś</1>. Ũńḿàŕķēď ŕũĺēś ķēēƥ ţĥēĩŕ ďēƒàũĺţ śţàţē."+ ],"zZ_I5K": ["Ōƥēń ƥŕōĴēćţ ḿēńũ"],"zaXlhf": ["Ţĥē ƥŕōƥēŕţĩēś ƀĺōćķ àţ ţĥē ţōƥ ōƒ ţĥĩś ďōć ĥàś à ƒōŕḿàţţĩńĝ ēŕŕōŕ. Śŵĩţćĥ ţō śōũŕćē ḿōďē ţō ƒĩx ĩţ."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex a425ed54c..9b29af1ca 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -123,6 +123,11 @@ msgstr ""msgid "{0, plural, one {# doc} other {# docs}}"msgstr ""+#. placeholder {0}: audit.result.errorCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {# error} other {# errors}}"+msgstr ""+#. placeholder {0}: value.length#: src/components/ArrayOfObjectsWidget.tsxmsgid "{0, plural, one {# item} other {# items}}"@@ -133,6 +138,11 @@ msgstr ""msgid "{0, plural, one {# key} other {# keys}}"msgstr ""+#. placeholder {0}: opts.length+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "{0, plural, one {# option set} other {# options set}}"+msgstr ""+#. placeholder {0}: blocked.length#: src/editor/components/PreviewBlockedNotice.tsxmsgid "{0, plural, one {# request blocked by the preview's security policy} other {# requests blocked by the preview's security policy}}"@@ -148,6 +158,11 @@ msgstr ""msgid "{0, plural, one {# use} other {# uses}}"msgstr ""+#. placeholder {0}: audit.result.warningCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {# warning} other {# warnings}}"+msgstr ""+#. placeholder {0}: fileRows.length#: src/components/CreatedItemsList.tsxmsgid "{0, plural, one {File} other {Files}}"@@ -158,6 +173,16 @@ msgstr ""msgid "{0, plural, one {Folder} other {Folders}}"msgstr ""+#. placeholder {0}: result.fileCount+#: src/components/ProblemsPanel.tsx+msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"+msgstr ""++#. placeholder {0}: labels[key]+#: src/components/settings/CustomThemeEditor.tsx+msgid "{0} hex value"+msgstr ""+#. placeholder {0}: templates.length#: src/components/empty-state/CreateView.tsxmsgid "{0} templates available"@@ -329,6 +354,11 @@ msgstr ""msgid "{docName} is {0}. OpenKnowledge currently opens files up to {1}."msgstr ""+#. placeholder {0}: entries.length+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "{enabledCount}/{0} on"+msgstr ""+#: src/components/FileTree.tsxmsgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"msgstr ""@@ -376,6 +406,11 @@ msgstr ""msgid "{keyName} value"msgstr ""+#. placeholder {0}: diagnostics.length+#: src/components/DocPanel.tsx+msgid "{label} ({0})"+msgstr ""+#: src/components/GraphPanel.tsxmsgid "{linkCount, plural, one {# link} other {# links}}"msgstr ""@@ -558,6 +593,10 @@ msgstr ""msgid "📝 or assets/icon.png"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."msgstr ""@@ -599,6 +638,10 @@ msgstr ""msgid "A non-empty folder already exists at this path. Pick a different folder."msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."+msgstr ""+#: src/components/CreateProjectDialog.tsxmsgid "A project already exists at this location. Pick a different parent folder."msgstr ""@@ -659,6 +702,10 @@ msgstr ""msgid "Above"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Accent"+msgstr ""+#: src/components/DiffView.tsxmsgid "Accept"msgstr ""@@ -1024,6 +1071,10 @@ msgstr ""msgid "Authorize in browser"msgstr ""+#: src/components/settings/ColorThemePicker.tsx+msgid "Auto"+msgstr ""+#: src/components/settings/TerminalSection.tsxmsgid "Auto-approve settings not yet loaded — try again in a moment"msgstr ""@@ -1087,6 +1138,10 @@ msgstr ""msgid "Back to document view"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Background"+msgstr ""+#: src/components/LinksPanel.tsxmsgid "Backlinks"msgstr ""@@ -1151,6 +1206,10 @@ msgstr ""msgid "Bold"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Border"+msgstr ""+#: src/components/GraphPanel.tsxmsgid "Both"msgstr ""@@ -1527,6 +1586,10 @@ msgstr ""msgid "Clusters"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Code"+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Code block"msgstr ""@@ -1597,6 +1660,10 @@ msgstr ""msgid "Collapsible section with a clickable summary."msgstr ""+#: src/components/settings/SettingsDialogBody.tsx+msgid "Color theme"+msgstr ""+#: src/components/CommandPalette.tsxmsgid "Command failed."msgstr ""@@ -1621,6 +1688,10 @@ msgstr ""msgid "Commits happen automatically"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Common markdown issues — hard tabs, heading increments, list markers, and more."+msgstr ""+#: src/components/HelpPopover.tsxmsgid "Community"msgstr ""@@ -1675,6 +1746,10 @@ msgstr ""msgid "Config sharing unchanged — see details below."msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Configuration warnings"+msgstr ""+#: src/components/settings/SettingsDialogShell.tsxmsgid "Configure user, project, and integration settings."msgstr ""@@ -1788,6 +1863,10 @@ msgstr ""msgid "Content root"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Content rules not yet loaded — try again in a moment"+msgstr ""+#: src/editor/bubble-menu/FootnoteBubbleButton.tsxmsgid "Convert selection to footnote"msgstr ""@@ -2398,10 +2477,18 @@ msgstr ""msgid "Custom open-knowledge entry — not managed by OpenKnowledge"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Custom theme"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Customize how the editor looks and behaves."msgstr ""+#: src/components/settings/ColorThemePicker.tsx+msgid "Dark"+msgstr ""+#: src/components/PropertyWidgets.tsxmsgid "Date"msgstr ""@@ -2418,6 +2505,11 @@ msgstr ""msgid "Default properties"msgstr ""+#. placeholder {0}: formatOptionConfigValue(spec.default)+#: src/components/settings/rule-option-field.tsx+msgid "Default: <0>{0}</0>"+msgstr ""+#: src/components/DeleteConfirmationDialog.tsx#: src/components/skill-actions.tsx#: src/components/TemplateRow.tsx@@ -2568,6 +2660,13 @@ msgstr ""msgid "Diff unavailable"msgstr ""+#. placeholder {0}: plugin.label+#. placeholder {0}: rule.name+#: src/components/settings/LintingSection.tsx+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Disable {0}"+msgstr ""+#: src/components/settings/LinkPreviewsSection.tsxmsgid "Disable external link previews"msgstr ""@@ -2584,6 +2683,10 @@ msgstr ""msgid "Disable sync"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Disable Themes"+msgstr ""+#: src/components/TemplateProperties.tsxmsgid "Disambiguates similarly-named templates in the menu."msgstr ""@@ -2663,6 +2766,15 @@ msgstr ""msgid "Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Documentation"+msgstr ""++#. placeholder {0}: rule.id+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Documentation for {0} (opens in browser)"+msgstr ""+#: src/components/FileTree.tsxmsgid "Documents response did not match expected shape."msgstr ""@@ -2792,6 +2904,10 @@ msgstr ""msgid "Edit {keyName}"msgstr ""+#: src/components/settings/rule-option-field.tsx+msgid "Edit in config file"+msgstr ""+#: src/editor/extensions/InternalLinkPropPanel.tsxmsgid "Edit markdown link"msgstr ""@@ -2844,6 +2960,10 @@ msgstr ""msgid "Editors to install skills into"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Edits apply live. Light or dark is chosen from the background."+msgstr ""+#: src/editor/slash-command/component-items.tsxmsgid "Edits at the source land here — no copy-paste drift."msgstr ""@@ -2897,6 +3017,13 @@ msgstr ""msgid "Empty starting content"msgstr ""+#. placeholder {0}: plugin.label+#. placeholder {0}: rule.name+#: src/components/settings/LintingSection.tsx+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Enable {0}"+msgstr ""+#: src/components/AutoSyncOnboardingDialog.tsx#: src/components/EnableSyncConfirmDialog.tsx#: src/components/share-receive-miss-content.tsx@@ -2932,6 +3059,10 @@ msgstr ""msgid "Enable terminal for this project"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Enable Themes"+msgstr ""+#: src/components/ActivityModeContent.tsxmsgid "Ended"msgstr ""@@ -2940,6 +3071,10 @@ msgstr ""msgid "Eng specs"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Enter a 6-digit hex like #1A2B3C"+msgstr ""+#: src/components/SeedDialog.tsxmsgid "Enter a folder name (e.g. brain)."msgstr ""@@ -3254,10 +3389,23 @@ msgstr ""msgid "Failed to reorder"msgstr ""+#. placeholder {0}: humanFormat(result.error)+#: src/components/settings/LintingSection.tsx+msgid "Failed to save content rules — {0}"+msgstr ""++#: src/components/settings/LintingSection.tsx+msgid "Failed to save theme setting"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Failed to update attachment location — {detail}"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Failed to update markdownlint rules"+msgstr ""+#: src/components/ObjectWidget.tsx#: src/components/PropertyPanel.tsxmsgid "Failed to update property"@@ -3399,10 +3547,23 @@ msgstr ""msgid "Fit width"msgstr ""+#: src/components/ProblemsPanel.tsx+#: src/editor/extensions/markdown-lint-decorations.ts+msgid "Fix"+msgstr ""++#: src/components/ProblemsPanel.tsx+msgid "Fix {flatId}"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Fixed folder in content root"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Flag common markdown issues in the editor. Powered by <0>markdownlint<1/></0>."+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Fold or unfold source"msgstr ""@@ -3566,6 +3727,15 @@ msgstr ""msgid "Go to line"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Go to line {displayLine}"+msgstr ""++#. placeholder {0}: file.file+#: src/components/ProblemsPanel.tsx+msgid "Go to line {displayLine} in {0}"+msgstr ""+#: src/components/DocPanel.tsx#: src/components/GraphPanel.tsxmsgid "Graph"@@ -3624,10 +3794,18 @@ msgstr ""msgid "heading-slug"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Headings"+msgstr ""+#: src/components/AutoSyncEnableWarning.tsxmsgid "Heads up"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."+msgstr ""+#: src/editor/slash-command/embed-starter-items.tsxmsgid "Hello, world!"msgstr ""@@ -4106,10 +4284,18 @@ msgstr ""msgid "Level"msgstr ""+#: src/components/settings/ColorThemePicker.tsx+msgid "Light"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Light, dark, or follow the OS."msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "line {displayLine}"+msgstr ""+#: src/editor/bubble-menu/LinkEditPopover.tsx#: src/editor/slash-command/component-items.tsxmsgid "Link"@@ -4152,10 +4338,18 @@ msgstr ""msgid "Links"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Links & images"+msgstr ""+#: src/components/PropertyWidgets.tsxmsgid "List"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Lists"+msgstr ""+#: src/components/PageHeaderWidgets.tsx#: src/components/SkillsSidebarSection.tsx#: src/editor/components/TagDialog.tsx@@ -4405,6 +4599,7 @@ msgid "Missing page: {linkTitle}. Click to create."msgstr ""#: src/components/FolderOverview.tsx+#: src/components/settings/markdownlint-rule-browser.tsxmsgid "Modified"msgstr ""@@ -4689,6 +4884,10 @@ msgstr ""msgid "Next tab"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."+msgstr ""+#: src/components/FileSidebar.tsxmsgid "No AI agents installed"msgstr ""@@ -4860,6 +5059,10 @@ msgstr ""msgid "No patterns yet. Type a folder or file name below to start hiding files."msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "No problems found."+msgstr ""+#: src/components/settings/SkillsManagerSection.tsxmsgid "No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."msgstr ""@@ -4885,6 +5088,10 @@ msgstr ""msgid "No results"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "No rules match your filters."+msgstr ""+#: src/components/SkillsSidebarSection.tsxmsgid "No skills yet."msgstr ""@@ -5059,6 +5266,10 @@ msgstr ""msgid "Only markdown files"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Only modified"+msgstr ""+#: src/editor/components/TagDialog.tsxmsgid "Only the current document uses <0>#{tag}</0>."msgstr ""@@ -5572,10 +5783,22 @@ msgstr ""msgid "Permission denied"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Pick “Custom” above to use this palette."+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."msgstr ""+#: src/components/settings/SettingsDialogBody.tsx+msgid "Pick a built-in IDE color palette, or define your own."+msgstr ""++#: src/components/settings/SettingsDialogBody.tsx+msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Pick a name"msgstr ""@@ -5600,6 +5823,11 @@ msgstr ""msgid "Please enter a valid email address."msgstr ""+#: src/components/settings/LintingSection.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Plugins"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsx#: src/components/settings/SettingsDialogShell.tsxmsgid "Preferences"@@ -5633,6 +5861,10 @@ msgstr ""msgid "Previous tab"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Primary"+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Private"msgstr ""@@ -5645,6 +5877,16 @@ msgstr ""msgid "probe failed"msgstr ""+#: src/components/DocPanel.tsx+#: src/components/ProblemsPanel.tsx+msgid "Problems"+msgstr ""++#. placeholder {0}: file.file+#: src/components/ProblemsPanel.tsx+msgid "Problems in {0}"+msgstr ""+#: src/components/HelpPopover.tsxmsgid "Product updates"msgstr ""@@ -5658,6 +5900,7 @@ msgid "project"msgstr ""#: src/components/CommandPalette.tsx+#: src/components/PanelScopeHeader.tsx#: src/lib/skill-scope.tsmsgid "Project"msgstr ""@@ -5674,6 +5917,10 @@ msgstr ""msgid "Project name"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Project plugins are your project's authoring standard — turn them on or off here. The choice is committed to config.yml and shared with every collaborator via git. Each enabled plugin gets its own page under Plugins in the settings sidebar."+msgstr ""+#: src/components/FileTree.tsx#: src/components/SeedDialog.tsxmsgid "Project root"@@ -5847,6 +6094,10 @@ msgstr ""msgid "Reconnecting…"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Refresh audit"+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsx#: src/components/settings/SettingsDialogBody.tsxmsgid "Reinstall"@@ -6104,10 +6355,20 @@ msgstr ""msgid "research-note"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Reset"+msgstr ""++#. placeholder {0}: rule.id+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Reset {0} to default"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset {labelText} to default"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset to default"msgstr ""@@ -6261,6 +6522,10 @@ msgstr ""msgid "root"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "Run a project audit from the Problems panel."+msgstr ""+#: src/components/settings/TerminalSection.tsxmsgid "Run a real terminal docked inside OpenKnowledge, starting in this project's folder."msgstr ""@@ -6269,6 +6534,10 @@ msgstr ""msgid "Run this in your terminal"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Running project audit"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Same folder as current file"msgstr ""@@ -6320,6 +6589,7 @@ msgid "Saving"msgstr ""#: src/components/NewSkillDialog.tsx+#: src/components/PanelScopeHeader.tsxmsgid "Scope"msgstr ""@@ -6386,6 +6656,14 @@ msgstr ""msgid "Search projects..."msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Search rules"+msgstr ""++#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Search rules by id, alias, or name"+msgstr ""+#: src/components/settings/SearchSection.tsxmsgid "Search settings not yet loaded — try again in a moment"msgstr ""@@ -7003,6 +7281,10 @@ msgstr ""msgid "Strikethrough"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Style"+msgstr ""+#: src/components/SeedDialog.tsxmsgid "Subfolder name"msgstr ""@@ -7036,6 +7318,10 @@ msgstr ""msgid "Summarize everything I changed this week"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Surface"+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Switch and update branch"msgstr ""@@ -7297,6 +7583,7 @@ msgid "Terminal settings not yet loaded — try again in a moment"msgstr ""#: src/components/PropertyWidgets.tsx+#: src/components/settings/CustomThemeEditor.tsxmsgid "Text"msgstr ""@@ -7329,6 +7616,10 @@ msgstr ""msgid "The agent's persona, values, and voice."msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "The audit could not be completed. Try again."+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr ""@@ -7416,10 +7707,20 @@ msgstr ""msgid "Theme"msgstr ""+#: src/components/settings/LintingSection.tsx+#: src/components/settings/SettingsDialogBody.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Themes"+msgstr ""+#: src/components/TerminalRefusalNotice.tsxmsgid "There's no project folder for this window, so a terminal can't start here."msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "These rules come from your project's <0>{configFile}</0> file, which fully governs linting for this project. Turn rules on or off and edit their options here; changes write back to the file."+msgstr ""+#: src/components/share-receive-miss-content.tsxmsgid "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>, and that change hasn't synced yet."msgstr ""@@ -7471,6 +7772,10 @@ msgstr ""msgid "This branch is checked out in:"msgstr ""+#: src/components/PanelScopeHeader.tsx+msgid "This doc"+msgstr ""+#: src/components/ShareFreshnessWarning.tsxmsgid "This doc has unpushed changes. Recipients will see the last pushed version."msgstr ""@@ -8047,6 +8352,10 @@ msgstr ""msgid "User"msgstr ""+#: src/components/settings/LintingSection.tsx+msgid "User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."+msgstr ""+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Using the <0>OK_EMBEDDINGS_API_KEY</0> environment variable (managed outside OpenKnowledge)."msgstr ""@@ -8215,6 +8524,10 @@ msgstr ""msgid "Where should it live?"msgstr ""+#: src/components/settings/markdownlint-rule-browser.tsx+msgid "Whitespace"+msgstr ""+#: src/components/CreatedItemsList.tsxmsgid "Who you are, so the agent has your context."msgstr ""diff --git a/packages/app/tests/integration/advisory-warnings.test.ts b/packages/app/tests/integration/advisory-warnings.test.tsindex d213543de..49865caea 100644--- a/packages/app/tests/integration/advisory-warnings.test.ts+++ b/packages/app/tests/integration/advisory-warnings.test.ts@@ -78,14 +78,16 @@ describe('advisory warnings on POST /api/agent-write-md', () => {expect(body.warning).toBeUndefined();});- test('valid fences and fence-less docs carry no renderWarnings field', async () => {+ test('valid fences and fence-less docs carry no render warnings', async () => {+ // Filter to render entries: lint-violation advisories (e.g. MD047 on a+ // fixture without a trailing newline) legitimately ride the same array.const valid = await writeMd(VALID_FENCE, uniqueDoc('rw-valid'));expect(valid.status).toBe(200);- expect(valid.body.warnings).toBeUndefined();+ expect((valid.body.warnings ?? []).filter((w) => w.kind === 'mermaid-parse-error')).toEqual([]);const plain = await writeMd('# Plain\n\nNo diagrams.', uniqueDoc('rw-plain'));expect(plain.status).toBe(200);- expect(plain.body.warnings).toBeUndefined();+ expect((plain.body.warnings ?? []).filter((w) => w.kind === 'mermaid-parse-error')).toEqual([]);});test('append composition is validated on the post-write state', async () => {@@ -93,12 +95,13 @@ describe('advisory warnings on POST /api/agent-write-md', () => {// An unclosed fence is valid mermaid on its own (CommonMark runs it to// EOF) — the appended prose lands INSIDE the fence body and breaks it.const first = await writeMd('```mermaid\ngraph LR\n A-->B', docName);- expect(first.body.warnings).toBeUndefined();+ expect((first.body.warnings ?? []).filter((w) => w.kind === 'mermaid-parse-error')).toEqual([]);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];+ const render = (second.body.warnings ?? []).filter((w) => w.kind === 'mermaid-parse-error');+ expect(render).toHaveLength(1);+ const w = render[0];expect(w?.kind === 'mermaid-parse-error' && w.fenceFirstLine).toBe('graph LR');});@@ -208,3 +211,35 @@ describe('advisory warnings on POST /api/agent-patch', () => {expect(body.warnings).toBeUndefined();});});++describe('content-rule (lint) violations on the agent write path', () => {+ test('markdownlint violations ride warnings[] so agents see what the GUI shows', async () => {+ const { writeFileSync } = await import('node:fs');+ const { join } = await import('node:path');+ // markdownlint is opt-in (off by default); enable it for this project so the+ // write-path advisory surfaces the violation the GUI would show. The base+ // config is read fresh per request, so writing it here takes effect on the+ // write below. Restore it afterward so sibling tests keep the default (off).+ const cfgPath = join(server.contentDir, '.ok', 'config.yml');+ writeFileSync(cfgPath, 'contentRules:\n markdownlint:\n enabled: true\n', 'utf-8');+ try {+ const docName = uniqueDoc('rw-lint-style');+ // The body carries a hard tab (markdownlint MD010). Agent writes surface+ // the same content-rule violations the editor GUI shows — whole-doc,+ // advisory only, capped — so an MCP client learns about them without a+ // separate `lint` round-trip.+ const { status, body } = await writeMd(+ '---\ntitle: Hi\n---\n\n# Doc\n\n\tindented\n',+ docName,+ );+ expect(status).toBe(200);+ const lint = (body.warnings ?? []).filter((w) => w.kind === 'lint-violation');+ expect(lint.length).toBeGreaterThan(0);+ const md010 = lint.find((w) => w.kind === 'lint-violation' && w.code === 'MD010');+ expect(md010?.kind === 'lint-violation' && md010.source).toBe('markdownlint');+ expect(md010?.kind === 'lint-violation' && md010.line).toBe(7);+ } finally {+ writeFileSync(cfgPath, '', 'utf-8');+ }+ });+});diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.tsindex 6d28930eb..accea3f14 100644--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts@@ -63,6 +63,12 @@ const REQUIRED_HANDLERS = [// (extractActorIdentity for the timeline + extractAgentIdentity for the// session) like the other content-write handlers.'handleSkillUpdate',+ // `/api/lint/fix` — apply markdownlint's auto-fixes to a document through the+ // agent-write spine (applyAgentMarkdownWrite). A mutating CRDT content-doc+ // write, so it threads extractAgentIdentity at entry to attribute the fix to+ // the calling agent (never the anonymous `file-system` writer a shell+ // `ok lint --fix` produces).+ 'handleLintFix',];/**@@ -113,6 +119,17 @@ const EXEMPT_HANDLERS = new Set([// seed/sync/local-op handlers. No agent identity needed.'handleFolderConfig','handleTemplate',+ // `/api/lint/config` (GET) + `/api/lint/markdownlint-config` (POST) — the markdown+ // linter's effective-config read and the native `.markdownlint.*` rule write.+ // Project-configuration writes (lint rules), not agent-authored document+ // content — same rationale as `handleFolderConfig`. No agent identity needed.+ 'handleGetLintConfig',+ 'handleWriteMarkdownlintRule',+ // `/api/lint` (GET) + `/api/lint/audit` (GET) — read-only lint of a single doc+ // / the whole project. No writes, no agent identity — same rationale as the+ // other read handlers below.+ 'handleLintDoc',+ 'handleLintAudit',// `/api/templates` — project-wide flat enumeration of every template// (read-only). Returns the union of all `<folder>/.ok/templates/*.md`;// same rationale as `handleTagsList` — read path, no agent identity.diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.tsindex 2c65e5ab0..94e0b077d 100644--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts@@ -63,6 +63,11 @@ const REQUIRED_HANDLERS = ['handleSkillFile','handleSkillFilePut','handleSkillUpdate',+ // `/api/lint/fix` — auto-fix a document's markdownlint violations through+ // `applyAgentMarkdownWrite`, which refuses a mid-conflict doc+ // (`DocInConflictError` → `respondDocInConflict`), so the gate rides the+ // shared agent-write spine.+ 'handleLintFix',];/**@@ -94,6 +99,17 @@ const EXEMPT_HANDLERS = new Set(['handleTagsForName','handlePages','handleFolderConfig',+ // `/api/lint/config` (GET) + `/api/lint/markdownlint-config` (POST) — read the+ // effective lint config / write the native `.markdownlint.*` rules. No Y.Doc+ // target (config files, not documents), so the per-doc conflict gate does not+ // apply — same posture as `handleFolderConfig`.+ 'handleGetLintConfig',+ 'handleWriteMarkdownlintRule',+ // `/api/lint` (GET) + `/api/lint/audit` (GET) — read-only lint of one doc /+ // the project. No Y.Doc target (reads from disk), so the per-doc conflict gate+ // does not apply.+ 'handleLintDoc',+ 'handleLintAudit',// `/api/templates` — project-wide flat enumeration of every template// (read-only). Walks `<folder>/.ok/templates/*.md`; no Y.Doc target,// so the per-doc conflict gate does not apply.diff --git a/packages/app/tests/integration/lint-config-cascade.test.ts b/packages/app/tests/integration/lint-config-cascade.test.tsnew file mode 100644index 000000000..7f6ef3ff8--- /dev/null+++ b/packages/app/tests/integration/lint-config-cascade.test.ts@@ -0,0 +1,176 @@+/**+ * L1 integration coverage for per-doc lint-config resolution over HTTP:+ * `GET /api/lint/config?doc=` follows the markdownlint-cli2 cascade (the+ * nearest `.markdownlint.*` file on the doc→root walk governs WHOLESALE), a+ * governing file is honored pure-native (no OK-tuned underlay), problems are+ * reported loudly, and the agent write path lints with the same per-doc+ * config.+ */++import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { DEFAULT_MARKDOWNLINT_CONFIG } from '@inkeep/open-knowledge-core';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestServer, type TestServer } from './test-harness.ts';++let server: TestServer;++beforeAll(async () => {+ // markdownlint is opt-in (off by default); this file exercises the lint+ // config cascade, so enable it for the whole test server.+ server = await createTestServer({ markdownlintEnabled: true });+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+});++interface LintConfigBody {+ effective?: {+ plugins?: { markdownlint?: { rules?: Record<string, unknown> } };+ };+ configFile?: string | null;+ configProblems?: string[];+}++async function getLintConfig(doc?: string): Promise<LintConfigBody> {+ const query = doc ? `?doc=${encodeURIComponent(doc)}` : '';+ const res = await fetch(`http://127.0.0.1:${server.port}/api/lint/config${query}`);+ expect(res.status).toBe(200);+ return (await res.json()) as LintConfigBody;+}++function rules(body: LintConfigBody): Record<string, unknown> | undefined {+ return body.effective?.plugins?.markdownlint?.rules;+}++describe('GET /api/lint/config per-doc cascade', () => {+ test('no native file → OK tuned defaults, configFile null', async () => {+ const body = await getLintConfig('some-doc');+ expect(rules(body)).toEqual(DEFAULT_MARKDOWNLINT_CONFIG);+ expect(body.configFile).toBeNull();+ expect(body.configProblems).toEqual([]);+ });++ test('a governing root file is honored pure-native (wholesale, no OK underlay)', async () => {+ writeFileSync(+ join(server.contentDir, '.markdownlint.json'),+ JSON.stringify({ MD013: false }),+ 'utf-8',+ );+ try {+ const body = await getLintConfig('some-doc');+ // Exactly the file's config — MD033/MD041 tuned disables do NOT leak in.+ expect(rules(body)).toEqual({ MD013: false });+ expect(body.configFile).toBe('.markdownlint.json');+ } finally {+ rmSync(join(server.contentDir, '.markdownlint.json'), { force: true });+ }+ });++ test('the nearest folder file governs docs under it; the root file governs the rest', async () => {+ const folder = join(server.contentDir, 'cascade-notes');+ mkdirSync(folder, { recursive: true });+ writeFileSync(+ join(server.contentDir, '.markdownlint.json'),+ JSON.stringify({ MD013: false, MD041: false }),+ 'utf-8',+ );+ writeFileSync(join(folder, '.markdownlint.json'), JSON.stringify({ MD010: false }), 'utf-8');+ try {+ const inFolder = await getLintConfig('cascade-notes/doc');+ expect(rules(inFolder)).toEqual({ MD010: false });+ expect(inFolder.configFile).toBe(join('cascade-notes', '.markdownlint.json'));++ const atRoot = await getLintConfig('root-doc');+ expect(rules(atRoot)).toEqual({ MD013: false, MD041: false });+ expect(atRoot.configFile).toBe('.markdownlint.json');+ } finally {+ rmSync(join(server.contentDir, '.markdownlint.json'), { force: true });+ rmSync(folder, { recursive: true, force: true });+ }+ });++ test('a malformed governing file keeps defaults and reports the problem loudly', async () => {+ writeFileSync(join(server.contentDir, '.markdownlint.json'), '{ not valid', 'utf-8');+ try {+ const body = await getLintConfig('some-doc');+ expect(rules(body)).toEqual(DEFAULT_MARKDOWNLINT_CONFIG);+ expect(body.configProblems).toEqual([+ expect.stringContaining('malformed markdownlint config'),+ ]);+ } finally {+ rmSync(join(server.contentDir, '.markdownlint.json'), { force: true });+ }+ });++ test('a severity-string rule value loads verbatim instead of failing the fetch', async () => {+ writeFileSync(+ join(server.contentDir, '.markdownlint.json'),+ JSON.stringify({ MD010: 'error', MD013: 'warning' }),+ 'utf-8',+ );+ try {+ const body = await getLintConfig('some-doc');+ expect(rules(body)).toEqual({ MD010: 'error', MD013: 'warning' });+ expect(body.configFile).toBe('.markdownlint.json');+ // Severity strings are native markdownlint vocabulary, not a config problem.+ expect(body.configProblems).toEqual([]);+ } finally {+ rmSync(join(server.contentDir, '.markdownlint.json'), { force: true });+ }+ });++ test('lint still runs on a doc governed by a severity-string config', async () => {+ const folder = join(server.contentDir, 'severity-notes');+ mkdirSync(folder, { recursive: true });+ // 'error' enables MD010 (truthy, default params) — the hard-tab body must warn.+ writeFileSync(join(folder, '.markdownlint.json'), JSON.stringify({ MD010: 'error' }), 'utf-8');+ try {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ markdown: '# Doc\n\n\tindented with a hard tab\n',+ position: 'replace',+ docName: `severity-notes/tabbed-${crypto.randomUUID().slice(0, 8)}`,+ }),+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as { warnings?: { kind: string; code?: string }[] };+ const lint = (body.warnings ?? []).filter((w) => w.kind === 'lint-violation');+ expect(lint.find((w) => w.code === 'MD010')).toBeDefined();+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });++ test('agent writes lint with the folder-governed config, not the root one', async () => {+ const folder = join(server.contentDir, 'cascade-agent');+ mkdirSync(folder, { recursive: true });+ // Folder file disables MD010 (hard tabs) — the hard-tab body must NOT warn.+ writeFileSync(+ join(folder, '.markdownlint.json'),+ JSON.stringify({ MD010: false, MD047: false }),+ 'utf-8',+ );+ try {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ markdown: '# Doc\n\n\tindented with a hard tab\n',+ position: 'replace',+ docName: `cascade-agent/tabbed-${crypto.randomUUID().slice(0, 8)}`,+ }),+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as { warnings?: { kind: string; code?: string }[] };+ const lint = (body.warnings ?? []).filter((w) => w.kind === 'lint-violation');+ expect(lint.find((w) => w.code === 'MD010')).toBeUndefined();+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });+});diff --git a/packages/app/tests/integration/lint-http.test.ts b/packages/app/tests/integration/lint-http.test.tsnew file mode 100644index 000000000..8d61f09d8--- /dev/null+++ b/packages/app/tests/integration/lint-http.test.ts@@ -0,0 +1,203 @@+/**+ * L1 integration coverage for the agent-facing lint HTTP surface, against a+ * real server + tmp contentDir (hermetic — runs on CI, unlike the git-child+ * constrained MCP-tool unit suite): `GET /api/lint?doc=` (single doc),+ * `GET /api/lint/audit` (project/sub-path), and+ * `POST /api/lint/markdownlint-config` (native rule write).+ *+ * Contract-level assertions only (status codes, wire-schema shape, disk+ * effect) — the write/read internals are free to evolve underneath.+ */++import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import {+ type LintAuditResponse,+ LintAuditResponseSchema,+ type LintConfigResponse,+ LintConfigResponseSchema,+ type LintDocResult,+ LintDocResultSchema,+ type LintFixResult,+ LintFixResultSchema,+} from '@inkeep/open-knowledge-core';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestServer, type TestServer } from './test-harness.ts';++let server: TestServer;++beforeAll(async () => {+ // markdownlint is opt-in (off by default); this file exercises the lint+ // endpoints, so enable it for the whole test server.+ server = await createTestServer({ markdownlintEnabled: true });+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+});++// A hard tab in the body trips MD010, enabled in OK's tuned defaults.+const TABBED_BODY = '# Doc\n\n\tindented with a hard tab\n';++function api(pathAndQuery: string): string {+ return `http://127.0.0.1:${server.port}${pathAndQuery}`;+}++describe('GET /api/lint (single document)', () => {+ test('a seeded doc with a violation lints to 200 + schema-valid diagnostics', async () => {+ const folder = join(server.contentDir, 'lint-http');+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, 'tabbed.md'), TABBED_BODY, 'utf-8');+ try {+ const res = await fetch(api('/api/lint?doc=lint-http%2Ftabbed'));+ expect(res.status).toBe(200);+ const body: LintDocResult = LintDocResultSchema.parse(await res.json());+ expect(body.file).toBe('lint-http/tabbed.md');+ const md010 = body.diagnostics.find((d) => d.code === 'MD010');+ expect(md010).toBeDefined();+ expect(md010?.source).toBe('markdownlint');+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });++ test('a missing doc param is a 400', async () => {+ const res = await fetch(api('/api/lint'));+ expect(res.status).toBe(400);+ });++ test('an unknown doc is a 404', async () => {+ const res = await fetch(api(`/api/lint?doc=no-such-doc-${crypto.randomUUID().slice(0, 8)}`));+ expect(res.status).toBe(404);+ });+});++describe('GET /api/lint/audit', () => {+ test('groups diagnostics per file across seeded docs; ?path= scopes the walk', async () => {+ const folder = join(server.contentDir, 'lint-http-audit');+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, 'a.md'), TABBED_BODY, 'utf-8');+ writeFileSync(join(folder, 'b.md'), TABBED_BODY, 'utf-8');+ try {+ const full = await fetch(api('/api/lint/audit'));+ expect(full.status).toBe(200);+ const fullBody: LintAuditResponse = LintAuditResponseSchema.parse(await full.json());+ // Other tests may contribute in-scope docs; assert containment, not equality.+ const fullFiles = fullBody.files.map((f) => f.file);+ expect(fullFiles).toEqual(+ expect.arrayContaining(['lint-http-audit/a.md', 'lint-http-audit/b.md']),+ );+ for (const f of fullBody.files) {+ expect(f.diagnostics.length).toBeGreaterThan(0);+ }+ expect(fullBody.fileCount).toBeGreaterThanOrEqual(2);++ const scoped = await fetch(api('/api/lint/audit?path=lint-http-audit'));+ expect(scoped.status).toBe(200);+ const scopedBody: LintAuditResponse = LintAuditResponseSchema.parse(await scoped.json());+ expect(scopedBody.files.map((f) => f.file).sort()).toEqual([+ 'lint-http-audit/a.md',+ 'lint-http-audit/b.md',+ ]);+ expect(scopedBody.fileCount).toBe(2);+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });+});++describe('POST /api/lint/fix', () => {+ async function postFix(docName: string): Promise<Response> {+ return fetch(api('/api/lint/fix'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ docName, agentId: 'lint-fix-agent' }),+ });+ }++ test('auto-fixes a fixable violation in place, preserving frontmatter', async () => {+ const folder = join(server.contentDir, 'lint-fix');+ mkdirSync(folder, { recursive: true });+ const file = join(folder, 'tabbed.md');+ writeFileSync(+ file,+ '---\ntitle: Keep Me\n---\n\n# Doc\n\n\tindented with a hard tab\n',+ 'utf-8',+ );+ try {+ const res = await postFix('lint-fix/tabbed');+ expect(res.status).toBe(200);+ const body: LintFixResult = LintFixResultSchema.parse(await res.json());+ expect(body.file).toBe('lint-fix/tabbed.md');+ expect(body.fixedCount).toBeGreaterThanOrEqual(1);+ // MD010 (hard tabs) is auto-fixable — gone from the remaining set.+ expect(body.diagnostics.find((d) => d.code === 'MD010')).toBeUndefined();+ // Disk effect: the tab is fixed and the frontmatter survives verbatim.+ const onDisk = readFileSync(file, 'utf-8');+ expect(onDisk).not.toContain('\t');+ expect(onDisk).toContain('title: Keep Me');+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });++ test('a clean doc is a no-op: fixedCount 0, no remaining diagnostics', async () => {+ const folder = join(server.contentDir, 'lint-fix-clean');+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, 'ok.md'), '# Clean\n\nNo problems here.\n', 'utf-8');+ try {+ const res = await postFix('lint-fix-clean/ok');+ expect(res.status).toBe(200);+ const body = LintFixResultSchema.parse(await res.json());+ expect(body.fixedCount).toBe(0);+ expect(body.diagnostics).toHaveLength(0);+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ });++ test('an unknown doc is a 404', async () => {+ const res = await postFix(`no-such-doc-${crypto.randomUUID().slice(0, 8)}`);+ expect(res.status).toBe(404);+ });+});++describe('POST /api/lint/markdownlint-config', () => {+ async function postRule(ruleId: string, value: unknown): Promise<Response> {+ return fetch(api('/api/lint/markdownlint-config'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ruleId, value }),+ });+ }++ test('setting a rule returns the recomputed effective config and lands on disk', async () => {+ const nativeFile = join(server.contentDir, '.markdownlint.json');+ try {+ const res = await postRule('MD012', { maximum: 3 });+ expect(res.status).toBe(200);+ const body: LintConfigResponse = LintConfigResponseSchema.parse(await res.json());+ expect(body.effective.plugins.markdownlint.rules.MD012).toEqual({ maximum: 3 });+ expect(body.configFile).toBe('.markdownlint.json');++ expect(existsSync(nativeFile)).toBe(true);+ expect(readFileSync(nativeFile, 'utf-8')).toContain('"MD012"');+ } finally {+ rmSync(nativeFile, { force: true });+ }+ });++ test('an executable native config declines the write with a 409', async () => {+ const cjsFile = join(server.contentDir, '.markdownlint.cjs');+ writeFileSync(cjsFile, 'module.exports = { MD010: false };\n', 'utf-8');+ try {+ const res = await postRule('MD012', false);+ expect(res.status).toBe(409);+ // The executable module is refused, never rewritten.+ expect(readFileSync(cjsFile, 'utf-8')).toBe('module.exports = { MD010: false };\n');+ } finally {+ rmSync(cjsFile, { force: true });+ }+ });+});diff --git a/packages/app/tests/integration/lint-symlink-escape.test.ts b/packages/app/tests/integration/lint-symlink-escape.test.tsnew file mode 100644index 000000000..8c11881c2--- /dev/null+++ b/packages/app/tests/integration/lint-symlink-escape.test.ts@@ -0,0 +1,116 @@+/**+ * L1 integration coverage for symlink containment on the lint HTTP surface:+ * `GET /api/lint?doc=` refuses a symlink escaping the content dir with a+ * path-escape 400, `GET /api/lint/audit?path=` over an escaped symlinked+ * scope returns 200 with a warning and no leaked source text, and symlinks+ * resolving inside the content dir keep linting normally. Also pins that+ * `?doc=` accepts an extension-carrying docName.+ */++import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestServer, type TestServer } from './test-harness.ts';++let server: TestServer;+let outside: string;++const SECRET = 'TOP-SECRET-OUTSIDE-CONTENT-8f3a';+// With markdownlint enabled, MD010 (hard tabs) flags a doc with a tab.+const DOC_WITH_TAB = '# Title\n\n\tindented with a tab\n';++beforeAll(async () => {+ // markdownlint is opt-in (off by default); this file exercises the lint+ // endpoint, so enable it for the whole test server.+ server = await createTestServer({ markdownlintEnabled: true });+ outside = mkdtempSync(join(tmpdir(), 'ok-lint-outside-'));+ writeFileSync(join(outside, 'secret.md'), `# Secret\n\n\t${SECRET}\n`, 'utf-8');+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ rmSync(outside, { recursive: true, force: true });+ await server.cleanup();+});++async function getLint(doc: string): Promise<Response> {+ return fetch(`http://127.0.0.1:${server.port}/api/lint?doc=${encodeURIComponent(doc)}`);+}++describe('GET /api/lint symlink containment', () => {+ test('a symlink escaping the content dir is refused with a path-escape 400', async () => {+ symlinkSync(join(outside, 'secret.md'), join(server.contentDir, 'lint-escape.md'));+ const res = await getLint('lint-escape');+ expect(res.status).toBe(400);+ const text = await res.text();+ expect((JSON.parse(text) as { type: string }).type).toBe('urn:ok:error:path-escape');+ expect(text).not.toContain(SECRET);+ });++ test('a symlink resolving inside the content dir lints normally', async () => {+ writeFileSync(join(server.contentDir, 'lint-inside-real.md'), DOC_WITH_TAB, 'utf-8');+ symlinkSync(+ join(server.contentDir, 'lint-inside-real.md'),+ join(server.contentDir, 'lint-inside-alias.md'),+ );+ const res = await getLint('lint-inside-alias');+ expect(res.status).toBe(200);+ const body = (await res.json()) as { diagnostics: { code: string }[] };+ expect(body.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ });++ test('an extension-carrying docName resolves', async () => {+ writeFileSync(join(server.contentDir, 'lint-explicit-ext.md'), DOC_WITH_TAB, 'utf-8');+ const res = await getLint('lint-explicit-ext.md');+ expect(res.status).toBe(200);+ const body = (await res.json()) as { file: string; diagnostics: { code: string }[] };+ expect(body.file).toBe('lint-explicit-ext.md');+ expect(body.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ });+});++describe('POST /api/lint/fix symlink containment', () => {+ test('a symlink escaping the content dir is refused and leaks no content', async () => {+ symlinkSync(join(outside, 'secret.md'), join(server.contentDir, 'lint-fix-escape.md'));+ const res = await fetch(`http://127.0.0.1:${server.port}/api/lint/fix`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ docName: 'lint-fix-escape', agentId: 'sym-fix-agent' }),+ });+ // The mutating fix endpoint must refuse the escape (never linting/returning+ // or writing back the outside secret) — same containment the read path has.+ expect(res.status).toBe(400);+ const text = await res.text();+ expect((JSON.parse(text) as { type: string }).type).toBe('urn:ok:error:path-escape');+ expect(text).not.toContain(SECRET);+ });+});++describe('GET /api/lint/audit symlink containment', () => {+ test('a scope through an escaped symlinked dir warns and leaks no content', async () => {+ symlinkSync(outside, join(server.contentDir, 'lint-audit-linked'));+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/lint/audit?path=lint-audit-linked`,+ );+ expect(res.status).toBe(200);+ const text = await res.text();+ const body = JSON.parse(text) as { files: unknown[]; warnings: string[] };+ expect(body.files).toEqual([]);+ expect(body.warnings).toEqual([expect.stringContaining('symlink-escape')]);+ expect(text).not.toContain(SECRET);+ });++ test('a scope targeting an escaping symlinked file warns and leaks no content', async () => {+ symlinkSync(join(outside, 'secret.md'), join(server.contentDir, 'lint-audit-escape.md'));+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/lint/audit?path=lint-audit-escape.md`,+ );+ expect(res.status).toBe(200);+ const text = await res.text();+ const body = JSON.parse(text) as { files: unknown[]; warnings: string[] };+ expect(body.files).toEqual([]);+ expect(body.warnings).toEqual([expect.stringContaining('symlink-escape')]);+ expect(text).not.toContain(SECRET);+ });+});diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex 014f75156..4aecb30d4 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -188,6 +188,13 @@ export interface CreateTestServerOptions {* grows byte-faithful.*/mdManager?: MarkdownManager;+ /**+ * Seed the project `.ok/config.yml` with the markdownlint plugin enabled.+ * markdownlint is opt-in (off by default), so lint tests that exercise real+ * diagnostics must turn it on — mirrors a project that enabled it. Only+ * applies to fresh contentDirs (`options.contentDir === undefined`).+ */+ markdownlintEnabled?: boolean;}export async function createTestServer(options: CreateTestServerOptions = {}): Promise<TestServer> {@@ -234,7 +241,12 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P// is trying to reload.if (options.contentDir === undefined) {mkdirSync(join(contentDir, '.ok'), { recursive: true });- writeFileSync(join(contentDir, '.ok', 'config.yml'), '', 'utf-8');+ // markdownlint is off by default; opt it in for lint tests that need+ // real diagnostics (readLinterBaseConfig reads this file fresh per request).+ const seedConfig = options.markdownlintEnabled+ ? 'contentRules:\n markdownlint:\n enabled: true\n'+ : '';+ writeFileSync(join(contentDir, '.ok', 'config.yml'), seedConfig, 'utf-8');}// Mirror the production auto-git-init path: every fresh tmpDir gets a realdiff --git a/packages/app/tests/stress/markdown-lint.e2e.ts b/packages/app/tests/stress/markdown-lint.e2e.tsnew file mode 100644index 000000000..6818ac1b0--- /dev/null+++ b/packages/app/tests/stress/markdown-lint.e2e.ts@@ -0,0 +1,682 @@+/**+ * Playwright E2E for the client-side markdown-lint composed flow.+ *+ * This is the real-browser rung that jsdom `dom.test.tsx` structurally cannot+ * cover: CodeMirror 6's `@codemirror/lint` paints decorations against a real+ * layout, and the Problems panel is driven live off `Y.Text('source')` through+ * `useDocDiagnostics`. Unit/dom tests assert the hook returns diagnostics and+ * the panel renders static props; only a browser proves the decoration paints+ * and the config→lint→decoration/panel wiring composes end-to-end.+ *+ * Covered seams (see reports test-substrate audit): S7 source-mode CM6+ * decorations, S9 Problems-panel badge+list+nav composition, plus the live+ * re-lint observer path and the no-false-positive negative case.+ *+ * markdownlint is opt-in (off by default), so `beforeEach` enables the plugin+ * for the worker's project (`.ok/config.yml`); a hard tab then trips MD010.+ *+ * Requires: Playwright browsers installed. Dev server started by+ * playwright.config.ts webServer on VITE_PORT (or default 5173).+ */++import { randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import {+ type ApiHelpers,+ expect,+ filterCriticalErrors,+ type LogEntry,+ test,+ waitForActiveProviderSynced as waitForProvider,+} from './_helpers';++// A body whose first line carries a hard tab → markdownlint MD010 (no-hard-tabs).+// Kept to a single block so the violation maps to one line/node.+const HARD_TAB_BODY = '# Heading\n\n\tindented with a hard tab\n';+const CLEAN_BODY = '# Heading\n\nA clean paragraph with no violations.\n';+const MD010 = 'markdownlint/MD010';+// An H1 followed by an H3 skips a level → MD001 (heading-increment). The hard+// tab keeps a second, independent violation in the doc so "MD010 still fires"+// is the positive signal that a re-lint ran with the new config (an MD001+// zero-count alone would also pass against a dead linter).+const MD001_AND_TAB_BODY = '# Heading\n\n### Skipped level\n\n\tindented with a hard tab\n';+const MD001 = 'markdownlint/MD001';++/** Switch to source mode and wait for CodeMirror to paint. */+async function switchToSource(page: Page) {+ await page.getByRole('radio', { name: 'Markdown source' }).click();+ await page.waitForSelector('.cm-content', { timeout: 10_000 });+ await page.waitForFunction(() => document.querySelectorAll('.cm-line').length > 0, null, {+ timeout: 5_000,+ });+}++/** Open the right-rail Problems tab. */+async function openProblemsTab(page: Page) {+ await page.locator('#tab-problems').click();+ // The panel wrapper has no stable id; wait for its body (list or empty state).+ await expect(+ page.locator('ul[aria-label="Problems"]').or(page.getByText('No problems found')),+ ).toBeVisible({ timeout: 5_000 });+}++/**+ * 1-based `.cm-line` index containing the DOM selection anchor. The source+ * editor renders no line-number gutter, so the focused cursor's real DOM+ * selection is the observable position signal.+ */+async function activeSourceLine(page: Page): Promise<number> {+ return page.evaluate(() => {+ const anchor = window.getSelection()?.anchorNode ?? null;+ const element = anchor instanceof Element ? anchor : (anchor?.parentElement ?? null);+ const line = element?.closest('.cm-line') ?? null;+ if (!line) return -1;+ return Array.from(document.querySelectorAll('.cm-content .cm-line')).indexOf(line) + 1;+ });+}++const errors: LogEntry[] = [];+let testDocName = '';++test.beforeEach(async ({ page, api, workerServer }) => {+ // markdownlint is opt-in (off by default); enable the plugin for the worker's+ // project so the linter runs. readLinterBaseConfig reads this fresh per request.+ mkdirSync(join(workerServer.contentDir, '.ok'), { recursive: true });+ writeFileSync(+ join(workerServer.contentDir, '.ok', 'config.yml'),+ 'contentRules:\n markdownlint:\n enabled: true\n',+ 'utf-8',+ );+ errors.length = 0;+ page.on('pageerror', (err) => errors.push({ type: 'uncaught', text: err.message }));+ page.on('console', (msg) => {+ if (msg.type() === 'error') {+ const loc = msg.location();+ errors.push({ type: 'error', text: msg.text(), url: loc.url, line: loc.lineNumber });+ }+ });++ testDocName = `mdlint-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${testDocName}.md`);+ await page.goto(`/#/${testDocName}`);+ await waitForProvider(page);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');+});++test.afterEach(() => {+ expect(filterCriticalErrors(errors), 'Expected zero critical console errors').toEqual([]);+});++test.afterAll(({ workerServer }) => {+ // Restore the default (markdownlint off) so any e2e file sharing this worker+ // isn't left with the plugin silently enabled.+ writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');+});++test.describe('markdown lint — source-mode decorations', () => {+ test('a hard tab paints a CM6 lint range + gutter marker', async ({ page, api }) => {+ await seed(api, testDocName, HARD_TAB_BODY);+ await switchToSource(page);++ // @codemirror/lint renders the diagnostic as a .cm-lintRange underline and a+ // .cm-lint-marker in the gutter. Neither exists in jsdom — this is the rung.+ await expect(page.locator('.cm-content .cm-lintRange')).not.toHaveCount(0);+ await expect(page.locator('.cm-gutter .cm-lint-marker').first()).toBeVisible();+ });++ test('a clean document paints no lint ranges (no false positives)', async ({ page, api }) => {+ // An empty `.cm-lintRange` set is not a settle barrier: it reads the same before the+ // debounced pass runs and after it runs clean, so a bare `toHaveCount(0)` would pass+ // even against a dead linter. Paint a known violation first (a positive wait that+ // proves the source linter is live), then clear to clean — the range disappearing is+ // the deterministic signal that a relint cycle actually ran on the clean text.+ await seed(api, testDocName, HARD_TAB_BODY);+ await switchToSource(page);+ await expect(page.locator('.cm-content .cm-lintRange')).not.toHaveCount(0);++ await seed(api, testDocName, CLEAN_BODY);+ await expect(page.locator('.cm-content .cm-lintRange')).toHaveCount(0);+ });++ test('editing to introduce a violation live-relints the open editor', async ({ page, api }) => {+ await seed(api, testDocName, CLEAN_BODY);+ await switchToSource(page);+ await expect(page.locator('.cm-content .cm-lintRange')).toHaveCount(0);++ // Mutate Y.Text out-of-band through the same provider the editor is bound to;+ // useDocDiagnostics observes Y.Text('source') and re-lints on the debounce.+ await seed(api, testDocName, HARD_TAB_BODY);+ await expect(page.locator('.cm-content .cm-lintRange')).not.toHaveCount(0);+ });+});++test.describe('markdown lint — Problems panel composition', () => {+ test('the violation surfaces in the panel with its rule code and a count badge', async ({+ page,+ api,+ }) => {+ await seed(api, testDocName, HARD_TAB_BODY);+ await openProblemsTab(page);++ const violations = page.locator('ul[aria-label="Problems"] > li');+ await expect(violations).not.toHaveCount(0);+ await expect(page.getByText(MD010)).toBeVisible();++ // The Problems tab shows a destructive count badge when diagnostics exist —+ // mode-agnostic, driven off the same useDocDiagnostics source.+ await expect(page.locator('#tab-problems').getByText(/^\d+$/)).toBeVisible();+ });++ test('a clean document shows the empty state and no badge', async ({ page, api }) => {+ // The empty state renders from the panel's initial `diagnostics === []` before the+ // first lint pass resolves, so asserting it directly would pass against a dead+ // pipeline. Surface a real violation first (proves the panel is live), then clear it;+ // the flip back to the empty state and the dropped badge is the deterministic settle.+ await seed(api, testDocName, HARD_TAB_BODY);+ await openProblemsTab(page);+ await expect(page.locator('ul[aria-label="Problems"] > li')).not.toHaveCount(0);++ await seed(api, testDocName, CLEAN_BODY);+ await expect(page.getByText('No problems found')).toBeVisible();+ await expect(page.locator('#tab-problems').getByText(/^\d+$/)).toHaveCount(0);+ });++ test('clicking a violation row emits a lint-nav event with the target line', async ({+ page,+ api,+ }) => {+ await seed(api, testDocName, HARD_TAB_BODY);+ await openProblemsTab(page);++ const navLine = page.evaluate<number>(+ () =>+ new Promise((resolve) => {+ window.addEventListener(+ 'open-knowledge:lint-nav',+ (e) => resolve((e as CustomEvent).detail?.line ?? -1),+ { once: true },+ );+ }),+ );+ await page.locator('ul[aria-label="Problems"] > li button').first().click();+ // The hard tab is on line 3 of HARD_TAB_BODY.+ expect(await navLine).toBe(3);+ });+});++test.describe('markdown lint — Problems panel project scope', () => {+ test('project scope lists violating files with per-file counts on demand', async ({+ page,+ api,+ workerServer,+ }) => {+ // A second violating doc that is never opened in the editor — project+ // scope must surface it anyway.+ const doc2 = `mdlint-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${doc2}.md`);+ await seed(api, doc2, HARD_TAB_BODY); // one violation: MD010+ await seed(api, testDocName, MD001_AND_TAB_BODY); // two violations: MD001 + MD010++ // The audit walks the content dir on disk; wait for the persistence+ // debounce to flush both seeded docs before running it.+ await expect+ .poll(+ () => {+ try {+ return (+ readFileSync(join(workerServer.contentDir, `${testDocName}.md`), 'utf-8').includes(+ '### Skipped level',+ ) && readFileSync(join(workerServer.contentDir, `${doc2}.md`), 'utf-8').includes('\t')+ );+ } catch {+ return false;+ }+ },+ { timeout: 15_000 },+ )+ .toBe(true);++ await openProblemsTab(page);+ await page.getByTestId('panel-scope-project').click();++ const scopeBody = page.getByTestId('problems-project-scope');+ const group1 = scopeBody.getByTestId('problems-audit-group').filter({ hasText: testDocName });+ const group2 = scopeBody.getByTestId('problems-audit-group').filter({ hasText: doc2 });+ await expect(group1).toBeVisible({ timeout: 10_000 });+ await expect(group2).toBeVisible();+ await expect(group1.getByTestId('problems-audit-file-count')).toHaveText('2');+ await expect(group2.getByTestId('problems-audit-file-count')).toHaveText('1');+ // Groups render their diagnostics expanded by default.+ await expect(group1.getByText(MD001)).toBeVisible();+ await expect(group2.getByText(MD010)).toBeVisible();+ // The audit-wide error/warning counts render above the groups (substring+ // tolerant of the singular/plural form — leftover docs from earlier tests+ // in this worker legitimately contribute to the totals).+ await expect(page.getByTestId('problems-audit-summary')).toContainText('warning');+ });++ test('clicking a project-scope diagnostic for a closed doc opens it at the diagnostic line', async ({+ page,+ api,+ workerServer,+ }) => {+ // The jump target lives in a doc that is never opened before the click.+ const doc2 = `mdlint-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${doc2}.md`);+ await seed(api, doc2, HARD_TAB_BODY); // MD010 on line 3+ await seed(api, testDocName, CLEAN_BODY);++ // The audit walks the content dir on disk; wait for the persistence+ // debounce to flush the seeded doc before running it.+ await expect+ .poll(+ () => {+ try {+ return readFileSync(join(workerServer.contentDir, `${doc2}.md`), 'utf-8').includes(+ '\t',+ );+ } catch {+ return false;+ }+ },+ { timeout: 15_000 },+ )+ .toBe(true);++ // Editor mode is a user-global preference: with source mode active before+ // the click, the target doc opens straight into a source editor and the+ // banked lint intent replays there.+ await switchToSource(page);+ await openProblemsTab(page);+ await page.getByTestId('panel-scope-project').click();++ const group = page.getByTestId('problems-audit-group').filter({ hasText: doc2 });+ await expect(group).toBeVisible({ timeout: 10_000 });+ await group.getByRole('button', { name: /Hard tabs/ }).click();++ // Hash navigation to the closed doc…+ await expect.poll(() => new URL(page.url()).hash).toBe(`#/${doc2}`);+ await waitForProvider(page);+ // …whose source editor mounts with the doc content…+ await expect(page.locator('.cm-content')).toContainText('indented with a hard tab');+ // …and the pending-intent replay lands the cursor on the diagnostic line.+ await expect.poll(() => activeSourceLine(page)).toBe(3);+ });+});++test.describe('markdown lint — settings rule browser', () => {+ test('toggling MD001 off writes the native config file and clears its decorations', async ({+ page,+ api,+ workerServer,+ }) => {+ await seed(api, testDocName, MD001_AND_TAB_BODY);+ await openProblemsTab(page);+ await expect(page.getByText(MD001)).toBeVisible();+ await expect(page.getByText(MD010)).toBeVisible();+ await switchToSource(page);+ await expect(page.locator('.cm-content .cm-lintRange')).not.toHaveCount(0);++ // The browser writes into the worker's own contentDir; remove the file+ // afterwards so later tests in this worker lint against OK defaults again.+ const configPath = join(workerServer.contentDir, '.markdownlint.json');+ try {+ await page.goto('/#settings');+ await page.getByTestId('settings-sidebar-item-plugin:markdownlint').click();+ const search = page.getByTestId('markdownlint-rule-search');+ await expect(search).toBeVisible({ timeout: 10_000 });+ await search.fill('MD001');+ const toggle = page.getByTestId('markdownlint-rule-toggle-MD001');+ await expect(toggle).toHaveAttribute('aria-checked', 'true');+ await toggle.click();++ // The Modified badge flips on once the write round-trips through the+ // config endpoint and the panel re-fetches the governing config.+ await expect(page.getByTestId('markdownlint-rule-modified-MD001')).toBeVisible({+ timeout: 10_000,+ });+ await expect(toggle).toHaveAttribute('aria-checked', 'false');+ const config = JSON.parse(readFileSync(configPath, 'utf-8')) as Record<string, unknown>;+ expect(config.MD001).toBe(false);++ await page.goto(`/#/${testDocName}`);+ await waitForProvider(page);+ await switchToSource(page);+ // MD010 still painting proves the re-lint ran with the new config …+ await expect(page.locator('.cm-content .cm-lintRange')).not.toHaveCount(0);+ await openProblemsTab(page);+ await expect(page.getByText(MD010)).toBeVisible();+ // … and the MD001 diagnostic is gone.+ await expect(page.getByText(MD001)).toHaveCount(0);+ } finally {+ rmSync(configPath, { force: true });+ }+ });++ test('editing MD013 line_length through the option field preserves the file’s other keys', async ({+ page,+ workerServer,+ }) => {+ const configPath = join(workerServer.contentDir, '.markdownlint.json');+ // A sibling rule key (MD010) plus a sibling option key (code_blocks) —+ // both must survive the single-option edit.+ writeFileSync(+ configPath,+ `${JSON.stringify({ MD010: false, MD013: { line_length: 120, code_blocks: false } }, null, 2)}\n`,+ );+ try {+ await page.goto('/#settings');+ await page.getByTestId('settings-sidebar-item-plugin:markdownlint').click();+ const search = page.getByTestId('markdownlint-rule-search');+ await expect(search).toBeVisible({ timeout: 10_000 });+ await search.fill('MD013');+ await page.getByTestId('markdownlint-rule-expand-MD013').click();++ const field = page.locator('#rule-option-MD013-line_length');+ // The field is backed by the file's value, not the schema default.+ await expect(field).toHaveValue('120');+ await field.fill('100');+ await field.press('Enter');++ await expect+ .poll(+ () => {+ const config = JSON.parse(readFileSync(configPath, 'utf-8')) as {+ MD013?: { line_length?: unknown };+ };+ return config.MD013?.line_length;+ },+ { timeout: 10_000 },+ )+ .toBe(100);+ const raw = readFileSync(configPath, 'utf-8');+ expect(JSON.parse(raw)).toEqual({+ MD010: false,+ MD013: { line_length: 100, code_blocks: false },+ });+ // Row-replace only rewrites the edited rule's value: the untouched+ // sibling line keeps its formatting byte-for-byte.+ expect(raw).toContain('"MD010": false');+ } finally {+ rmSync(configPath, { force: true });+ }+ });+});++// Three trailing spaces trip MD009 (no-trailing-spaces; br_spaces=2 allows+// exactly two). Chosen deliberately: serialization NORMALIZES trailing spaces+// away, so this violation class only paints in WYSIWYG when the decoration+// pass lints the raw Y.Text source — the rung that proves the source-bytes+// path, not a re-serialization.+const MD009_BODY = '# Heading\n\nFirst paragraph.\n\nLast paragraph with trailing spaces \n';++test.describe('markdown lint — WYSIWYG block decorations + navigation', () => {+ test('a serialization-erased violation (trailing spaces) marks its block in WYSIWYG', async ({+ page,+ api,+ }) => {+ await seed(api, testDocName, MD009_BODY);+ // Stay in WYSIWYG (the default mode) — the block the violation falls in+ // gets the .ok-lint-block node decoration.+ await expect(page.locator('.ProseMirror .ok-lint-block').first()).toBeVisible({+ timeout: 10_000,+ });+ // The decoration must land on the OFFENDING block (the last paragraph),+ // not merely on some block — guards buildDecorationSet's block-index → PM+ // -node mapping against an off-by-one that would underline the wrong+ // paragraph while still passing a bare "some block is marked" check.+ await expect(+ page.locator('.ProseMirror .ok-lint-block', {+ hasText: 'Last paragraph with trailing spaces',+ }),+ ).toHaveCount(1);+ await expect(+ page.locator('.ProseMirror .ok-lint-block', { hasText: 'First paragraph' }),+ ).toHaveCount(0);++ // Clearing the violation clears the decoration — proves a live re-lint+ // cycle on the current bytes, not a stale set.+ await seed(api, testDocName, CLEAN_BODY);+ await expect(page.locator('.ProseMirror .ok-lint-block')).toHaveCount(0);+ });++ test('decorations render in a doc that ends with a heading (trailing empty paragraph)', async ({+ page,+ api,+ }) => {+ // Mirrors the user-test repro: a heading-final doc makes the PM doc carry+ // a trailing empty paragraph with no source counterpart, so a strict+ // block-count comparison never matches and decorations silently never+ // paint (and row clicks never navigate).+ const headingFinalBody =+ '# Lint demo\n\nTrailing spaces here. \n\n- dash item\n* star item\n\n### End heading\n';+ await seed(api, testDocName, headingFinalBody);+ await expect(page.locator('.ProseMirror .ok-lint-block').first()).toBeVisible({+ timeout: 10_000,+ });+ });++ test('a textless block (thematic break / image) gets a visible outline, not an invisible underline', async ({+ page,+ api,+ }) => {+ // MD035 fires on the second (differently-styled) thematic break — a+ // textless block, so the base wavy underline paints nothing and it must+ // fall back to the .ok-lint-block-atom outline. (Images are textless too+ // but a fake src 404s the console-error gate, so a thematic break is the+ // clean textless probe.)+ await seed(api, testDocName, '# Title\n\n---\n\ntext\n\n***\n\nEnd.\n');+ const atoms = page.locator('.ProseMirror .ok-lint-block-atom');+ await expect(atoms.first()).toBeVisible({ timeout: 10_000 });+ // Every atom-decorated block renders a real outline (the visible fallback).+ const outlined = await atoms.evaluateAll((els) =>+ els.every((el) => getComputedStyle(el).outlineStyle !== 'none'),+ );+ expect(outlined).toBe(true);+ });++ test('clicking a Problems row in WYSIWYG actually scrolls the block into view', async ({+ page,+ api,+ }) => {+ // A doc tall enough that the violation sits well below the fold, so a+ // real scroll is observable (the earlier selection-only assertion could+ // pass without the viewport ever moving). Heading-final to also exercise+ // the trailing-empty-paragraph path.+ const filler = Array.from({ length: 40 }, (_, i) => `Filler paragraph number ${i + 1}.`).join(+ '\n\n',+ );+ const tallBody = `# Top heading\n\n${filler}\n\nParagraph with trailing spaces here. \n\n### Bottom heading\n`;+ await seed(api, testDocName, tallBody);+ await openProblemsTab(page);+ await expect(page.getByText('markdownlint/MD009')).toBeVisible();++ const scroller = page.getByTestId('editor-scroll-container');+ await expect(scroller).toBeVisible();+ const before = await scroller.evaluate((el) => el.scrollTop);++ await page.locator('ul[aria-label="Problems"] > li button').first().click();++ // The container must actually scroll down toward the violation.+ await expect+ .poll(async () => scroller.evaluate((el) => el.scrollTop))+ .toBeGreaterThan(before + 100);+ // And the offending block must settle within the visible viewport, clear+ // of the 3.5rem toolbar overlay (scroll-pt-14 alignment). Poll so the+ // smooth-scroll animation has time to settle; small tolerance on the+ // toolbar band for sub-pixel rounding.+ await expect+ .poll(async () =>+ page.evaluate(() => {+ const pm = document.querySelector('.ProseMirror:not(.composer-prosemirror)');+ const scrollEl = document.querySelector('[data-testid="editor-scroll-container"]');+ if (!pm || !scrollEl) return false;+ const target = Array.from(pm.children).find((c) =>+ c.textContent?.includes('Paragraph with trailing spaces here.'),+ );+ if (!target) return false;+ const t = target.getBoundingClientRect();+ const s = scrollEl.getBoundingClientRect();+ return t.top >= s.top + 48 && t.top <= s.bottom;+ }),+ )+ .toBe(true);+ });++ test('clicking a Problems row in source mode scrolls the ancestor container to the line', async ({+ page,+ api,+ }) => {+ // Regression for the source-mode scroll no-op: in full-page source mode the+ // CM editor renders at content height with no internal scrollport, so+ // scrollIntoView(y:'center'|'nearest') measures the target as already visible+ // against CM's own scrollDOM and never scrolls the real ancestor+ // (ScrollPreservingContainer). Only y:'start' propagates the scroll. A tall+ // doc puts the violation well below the fold so a real scroll is observable —+ // the bug is invisible whenever the whole doc fits the viewport.+ const filler = Array.from({ length: 40 }, (_, i) => `Filler paragraph number ${i + 1}.`).join(+ '\n\n',+ );+ const tallBody = `# Top heading\n\n${filler}\n\nParagraph with trailing spaces here. \n`;+ await seed(api, testDocName, tallBody);+ await switchToSource(page);+ await openProblemsTab(page);+ await expect(page.getByText('markdownlint/MD009')).toBeVisible();++ const scroller = page.getByTestId('editor-scroll-container');+ await expect(scroller).toBeVisible();+ const before = await scroller.evaluate((el) => el.scrollTop);++ await page.locator('ul[aria-label="Problems"] > li button').first().click();++ // The ancestor container must actually scroll down toward the violation line.+ await expect+ .poll(async () => scroller.evaluate((el) => el.scrollTop))+ .toBeGreaterThan(before + 100);+ });++ test('clicking a Problems row in WYSIWYG selects and scrolls to the offending block', async ({+ page,+ api,+ }) => {+ await seed(api, testDocName, MD009_BODY);+ await openProblemsTab(page);+ await expect(page.getByText('markdownlint/MD009')).toBeVisible();++ await page.locator('ul[aria-label="Problems"] > li button').first().click();++ // The violation is on the LAST paragraph (top-level block index 2:+ // heading, paragraph, paragraph). The nav handler puts the selection+ // inside that block in the visible WYSIWYG editor.+ await expect+ .poll(async () =>+ page.evaluate(() => {+ const anchor = window.getSelection()?.anchorNode ?? null;+ const element = anchor instanceof Element ? anchor : (anchor?.parentElement ?? null);+ const pm = document.querySelector('.ProseMirror:not(.composer-prosemirror)');+ if (!pm || !element) return -1;+ const top = Array.from(pm.children).find((child) => child.contains(element));+ return top ? Array.from(pm.children).indexOf(top) : -1;+ }),+ )+ .toBe(2);+ });++ test('project-scope click on a closed doc opens it AND scrolls on the first click', async ({+ page,+ api,+ workerServer,+ }) => {+ // Regression: the cross-doc project path banks the intent and opens the+ // doc WITHOUT dispatching the live event, so the WYSIWYG editor must+ // REPLAY it on mount — otherwise the first click only navigates and a+ // second click is needed to scroll.+ const doc2 = `mdlint-${randomUUID().slice(0, 8)}`;+ await api.createPage(`${doc2}.md`);+ const filler = Array.from({ length: 40 }, (_, i) => `Filler line ${i + 1}.`).join('\n\n');+ const doc2Body = `# ${doc2}\n\n${filler}\n\nParagraph with trailing spaces here. \n\n### Bottom heading\n`;+ await seed(api, doc2, doc2Body);+ await seed(api, testDocName, CLEAN_BODY);++ // The audit walks disk; wait for the persistence debounce to flush doc2.+ await expect+ .poll(+ () => {+ try {+ return readFileSync(join(workerServer.contentDir, `${doc2}.md`), 'utf-8').includes(+ 'trailing spaces here.',+ );+ } catch {+ return false;+ }+ },+ { timeout: 15_000 },+ )+ .toBe(true);++ await openProblemsTab(page);+ await page.getByTestId('panel-scope-project').click();+ const group = page.getByTestId('problems-audit-group').filter({ hasText: doc2 });+ await expect(group).toBeVisible({ timeout: 10_000 });++ // A single click: navigate to the closed doc …+ await group+ .getByRole('button', { name: /Trailing spaces/ })+ .first()+ .click();+ await expect.poll(() => new URL(page.url()).hash).toBe(`#/${doc2}`);+ await waitForProvider(page);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');++ // … and the offending block scrolls into view without a second click.+ // Two scroll containers exist (the previous doc stays pool-mounted but+ // hidden) — target the visible one.+ const scroller = page.locator('[data-testid="editor-scroll-container"]:visible');+ await expect(scroller).toBeVisible();+ await expect.poll(async () => scroller.evaluate((el) => el.scrollTop)).toBeGreaterThan(100);+ });+});++test.describe('markdown lint — auto-fix', () => {+ // MD009 (trailing spaces) is auto-fixable; the fix deletes the trailing run.+ const FIXABLE_BODY = '# Title\n\nParagraph with trailing spaces. \n';++ test('the Problems panel Fix button applies the fix and the violation clears', async ({+ page,+ api,+ }) => {+ await seed(api, testDocName, FIXABLE_BODY);+ await openProblemsTab(page);+ await expect(page.getByText('markdownlint/MD009')).toBeVisible();+ const fix = page.getByTestId('problems-fix').first();+ await expect(fix).toBeAttached();+ await fix.click();+ // The write lands on Y.Text('source'); useDocDiagnostics re-lints and the+ // row disappears, and the WYSIWYG squiggle clears without navigating.+ await expect(page.getByText('markdownlint/MD009')).toHaveCount(0);+ await expect(page.getByText('No problems found')).toBeVisible();+ await expect(page.locator('.ProseMirror .ok-lint-block')).toHaveCount(0);+ });++ test('the WYSIWYG tooltip Fix button applies the fix', async ({ page, api }) => {+ await seed(api, testDocName, FIXABLE_BODY);+ // Stay in WYSIWYG. Hover the decorated paragraph to raise the tooltip.+ const block = page.locator('.ProseMirror .ok-lint-block').first();+ await expect(block).toBeVisible({ timeout: 10_000 });+ await block.hover();+ const tooltipFix = page.locator('.ok-lint-tooltip-fix');+ await expect(tooltipFix).toBeVisible();+ await tooltipFix.click();+ // The stale squiggle must clear WITHOUT navigating away: a source-only fix+ // leaves the PM doc unchanged, so the decoration relies on the+ // LINT_SOURCE_FIXED_EVENT nudge to re-lint and drop the mark.+ await expect(page.locator('.ProseMirror .ok-lint-block')).toHaveCount(0);+ });+});++/** Seed content via agent-write-md (replace mode). */+async function seed(api: ApiHelpers, docName: string, markdown: string) {+ await api.replaceDoc(docName, markdown);+}diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 91df534a4..837318290 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -39,6 +39,7 @@ import { createRealDetectDeps, detectDesktop, launchDesktop } from './commands/dimport { diagnoseCommand } from './commands/diagnose.ts';import { embeddingsCommand } from './commands/embeddings/index.ts';import { initCommand } from './commands/init.ts';+import { lintCommand } from './commands/lint.ts';import { mcpCommand } from './commands/mcp.ts';import { migrateCommand } from './commands/migrate.ts';import { openCommand } from './commands/open.ts';@@ -222,6 +223,9 @@ program.addCommand(skillsCommand());const preview = previewCommand(() => resolvedConfig);program.addCommand(preview);+// lint command — headless markdown linting (whole project, a folder, or a file)+program.addCommand(lintCommand(() => resolvedConfig));+// ui command — serves the React editor (sibling of `start`).const ui = uiCommand(() => resolvedConfig);program.addCommand(ui);diff --git a/packages/cli/src/commands/lint.test.ts b/packages/cli/src/commands/lint.test.tsnew file mode 100644index 000000000..0373e2df5--- /dev/null+++ b/packages/cli/src/commands/lint.test.ts@@ -0,0 +1,98 @@+/**+ * Unit tests for the `ok lint` human-readable report formatter. The walk/lint+ * pipeline is covered by `content/lint-runner.test.ts`; here we pin the output+ * shaping against a synthetic result (no fs).+ */++import { describe, expect, test } from 'bun:test';+import { isAbsolute } from 'node:path';+import type { LintRunResult } from '../content/lint-runner.ts';+import { formatLintReport, resolveTarget } from './lint.ts';++function result(over: Partial<LintRunResult> = {}): LintRunResult {+ return {+ contentDir: '/x',+ files: [],+ warnings: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ fixedCount: 0,+ ...over,+ };+}++describe('formatLintReport', () => {+ test('reports a clean run', async () => {+ const out = formatLintReport(result({ fileCount: 3 }));+ expect(out).toContain('No problems in 3 files');+ });++ test('groups diagnostics under their file with a summary', async () => {+ const out = formatLintReport(+ result({+ fileCount: 1,+ warningCount: 1,+ files: [+ {+ file: 'a.md',+ fixed: false,+ diagnostics: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ },+ ],+ },+ ],+ }),+ );+ expect(out).toContain('a.md');+ expect(out).toContain('Hard tabs');+ expect(out).toContain('markdownlint/MD010');+ expect(out).toContain('1 problem');+ });++ test('marks fixed files and shows a fixed summary', async () => {+ const out = formatLintReport(+ result({+ fileCount: 1,+ fixedCount: 1,+ files: [{ file: 'a.md', fixed: true, diagnostics: [] }],+ }),+ );+ expect(out).toContain('Fixed 1 file');+ });++ test('surfaces runner warnings', async () => {+ const out = formatLintReport(result({ warnings: ['could not read directory drafts'] }));+ expect(out).toContain('could not read directory drafts');+ });+});++describe('resolveTarget', () => {+ const cwd = '/home/user/project';++ test('joins a relative path onto the invocation cwd', () => {+ expect(resolveTarget('guides/intro.md', cwd)).toBe('/home/user/project/guides/intro.md');+ });++ test('normalizes a leading-dot relative path (no doubled segment)', () => {+ expect(resolveTarget('./foo', cwd)).toBe('/home/user/project/foo');+ });++ test('returns a POSIX-absolute input unchanged', () => {+ expect(resolveTarget('/etc/docs', cwd)).toBe('/etc/docs');+ });++ test('produces a single absolute path (never the cwd-prefixed concat bug)', () => {+ // The prior hand-rolled `startsWith('/')` join produced `${cwd}/C:\docs`+ // on Windows-style inputs; resolve() yields one well-formed absolute path.+ const out = resolveTarget('sub/dir', cwd);+ expect(isAbsolute(out)).toBe(true);+ expect(out.includes(`${cwd}/${cwd}`)).toBe(false);+ });+});diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.tsnew file mode 100644index 000000000..211af175e--- /dev/null+++ b/packages/cli/src/commands/lint.ts@@ -0,0 +1,119 @@+/**+ * `ok lint [path]` — headless markdown linting over a project, a folder, or a+ * single file. Reuses the same engine as the source editor (project+ * `contentRules` base + native `.markdownlint.*` rules). Exits non-zero when+ * problems are found (CI-friendly), or only on errors with `--errors-only`.+ */++import { resolve } from 'node:path';+import {+ DEFAULT_LINTER_CONFIG,+ type LinterConfig,+ type PersistedLinterConfig,+ toEffectiveBase,+} from '@inkeep/open-knowledge-core';+import { type Config, resolveContentDir } from '@inkeep/open-knowledge-server';+import { Command } from 'commander';+import { type FileLintResult, type LintRunResult, runLint } from '../content/lint-runner.ts';+import { getInvocationCwd } from '../project-anchor.ts';+import { accent, dim, error as red, success, warning as yellow } from '../ui/colors.ts';++interface LintOptions {+ json?: boolean;+ fix?: boolean;+ errorsOnly?: boolean;+}++export function lintCommand(getConfig: () => Config): Command {+ return new Command('lint')+ .description('Lint markdown content (headless) — whole project, a folder, or a single file')+ .argument('[path]', 'Folder or file to lint, relative to where you run the command')+ .option('--json', 'Emit structured JSON instead of formatted text')+ .option('--fix', 'Auto-fix fixable issues in place (markdownlint rules only)')+ .option(+ '--errors-only',+ 'Exit non-zero only on error-severity problems (findings are warning-severity unless your .markdownlint.* assigns a rule "error")',+ )+ .action(async (path: string | undefined, opts: LintOptions) => {+ const config = getConfig();+ const projectDir = process.cwd();+ const contentDir = resolveContentDir(config, projectDir);+ // `lint` is a project-anchored command, so cwd is the project root; the+ // user's `[path]` is relative to where they actually invoked it.+ const targetPath = path === undefined ? undefined : resolveTarget(path, getInvocationCwd());+ // Persisted config omits markdownlint `rules` (native-file sourced); lift it+ // to an effective base, and runLint fills `rules` from the native file.+ const persistedLinter = config.contentRules as PersistedLinterConfig | undefined;+ const baseConfig: LinterConfig = persistedLinter+ ? toEffectiveBase(persistedLinter)+ : DEFAULT_LINTER_CONFIG;++ const result = await runLint({+ projectDir,+ contentDir,+ baseConfig,+ targetPath,+ fix: opts.fix === true,+ });++ if (opts.json === true) {+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ } else {+ process.stdout.write(`${formatLintReport(result)}\n`);+ }++ const failed = opts.errorsOnly === true ? result.errorCount > 0 : hasProblems(result);+ if (failed) process.exitCode = 1;+ });+}++export function resolveTarget(path: string, invocationCwd: string): string {+ return resolve(invocationCwd, path);+}++function hasProblems(result: LintRunResult): boolean {+ return result.errorCount > 0 || result.warningCount > 0;+}++/** Render one file's heading + its diagnostics as report lines. */+function renderFileBlock(file: FileLintResult): string[] {+ const lines: string[] = [accent(file.file) + (file.fixed ? dim(' (fixed)') : '')];+ for (const d of file.diagnostics) {+ // Report locations are 1-based (editor convention); ranges are 0-based LSP.+ const loc = dim(`${d.range.start.line + 1}:${d.range.start.character + 1}`.padEnd(7));+ const sev = d.severity === 'error' ? red('error ') : yellow('warning');+ lines.push(` ${loc} ${sev} ${d.message} ${dim(`${d.source}/${d.code}`)}`);+ }+ lines.push('');+ return lines;+}++/** Render an eslint/markdownlint-style grouped report. */+export function formatLintReport(result: LintRunResult): string {+ const lines: string[] = [];+ for (const file of result.files) {+ if (file.diagnostics.length > 0) lines.push(...renderFileBlock(file));+ }++ for (const w of result.warnings) lines.push(yellow(`! ${w}`));+ if (result.warnings.length > 0) lines.push('');++ const problemTotal = result.errorCount + result.warningCount;+ if (problemTotal === 0) {+ lines.push(+ success(`✓ No problems in ${result.fileCount} file${result.fileCount === 1 ? '' : 's'}.`),+ );+ } else {+ const parts = [`${problemTotal} problem${problemTotal === 1 ? '' : 's'}`];+ parts.push(`${result.errorCount} error${result.errorCount === 1 ? '' : 's'}`);+ parts.push(`${result.warningCount} warning${result.warningCount === 1 ? '' : 's'}`);+ lines.push(+ `${red(parts[0] ?? '')} (${parts[1]}, ${parts[2]}) across ${result.fileCount} file${result.fileCount === 1 ? '' : 's'}.`,+ );+ }+ if (result.fixedCount > 0) {+ lines.push(dim(`Fixed ${result.fixedCount} file${result.fixedCount === 1 ? '' : 's'}.`));+ }++ return lines.join('\n');+}diff --git a/packages/cli/src/content/lint-runner.test.ts b/packages/cli/src/content/lint-runner.test.tsnew file mode 100644index 000000000..f0875fe4d--- /dev/null+++ b/packages/cli/src/content/lint-runner.test.ts@@ -0,0 +1,143 @@+/**+ * Integration tests for the headless lint runner over a real temp project:+ * the walk, ignore filtering, native-file config resolution, the lint pass,+ * and `--fix` write-back. A real temp dir (not in-memory) is used so the+ * `createContentFilter` ignore-file path and the fs seams are exercised as in+ * production.+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DEFAULT_LINTER_CONFIG } from '@inkeep/open-knowledge-core';+import { runLint } from './lint-runner.ts';++let root: string;++function write(rel: string, content: string): void {+ const abs = join(root, rel);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, content, 'utf-8');+}++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-lint-run-')));+ write('.ok/config.yml', 'content:\n dir: .\n');+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function run(opts: Partial<Parameters<typeof runLint>[0]> = {}) {+ return runLint({+ projectDir: root,+ contentDir: root,+ // markdownlint is opt-in (off by default); these tests exercise the linter,+ // so enable the plugin explicitly on the base config.+ baseConfig: {+ ...DEFAULT_LINTER_CONFIG,+ plugins: { markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true } },+ },+ ...opts,+ });+}++describe('runLint — walk + lint', () => {+ test('lints every in-scope doc and counts problems', async () => {+ write('a.md', '# A\n\ntext with a\ttab\n');+ write('b.md', '# B\n\n#bad heading\n');+ const result = await run();+ expect(result.fileCount).toBe(2);+ const a = result.files.find((f) => f.file === 'a.md');+ expect(a?.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ expect(result.warningCount).toBeGreaterThan(0);+ });++ test('does not flag OK non-HTML superset syntax', async () => {+ // Defaults match vscode-markdownlint (all on except MD013): raw-HTML MDX+ // (MD033) and a frontmatter title beside an H1 (MD025) DO flag, as in VS+ // Code — so the clean fixture covers only the non-HTML superset.+ write(+ 'clean.md',+ '---\nstatus: draft\n---\n\n# H\n\nA [[wiki]], math $x^2$, ==hl==.\n\n> [!NOTE]\n> alert\n',+ );+ const result = await run();+ expect(result.files.find((f) => f.file === 'clean.md')?.diagnostics).toEqual([]);+ });++ test('skips files under ignored/.ok and non-doc files', async () => {+ write('keep.md', '# Keep\n');+ write('notes.txt', 'not markdown\n');+ const result = await run();+ expect(result.files.map((f) => f.file)).toEqual(['keep.md']);+ });+});++describe('runLint — native markdownlint config', () => {+ test('the native .markdownlint.json disables a rule project-wide', async () => {+ // markdownlint rules live in the project's own `.markdownlint.*`, discovered+ // at the content root and injected into the effective config.+ write('.markdownlint.json', JSON.stringify({ MD010: false }));+ write('strict/tabs.md', '# H\n\nhas a\ttab\n');+ const result = await run();+ const note = result.files.find((f) => f.file === join('strict', 'tabs.md'));+ expect(note?.diagnostics.some((d) => d.code === 'MD010')).toBe(false);+ });+});++describe('runLint — scope', () => {+ test('scopes to a single folder', async () => {+ write('a.md', '# A\n');+ write('sub/b.md', '# B\n');+ const result = await run({ targetPath: join(root, 'sub') });+ expect(result.files.map((f) => f.file)).toEqual([join('sub', 'b.md')]);+ });++ test('scopes to a single file', async () => {+ write('a.md', '# A\n\na\tb\n');+ write('b.md', '# B\n');+ const result = await run({ targetPath: join(root, 'a.md') });+ expect(result.files.map((f) => f.file)).toEqual(['a.md']);+ });+});++describe('runLint — fix', () => {+ test('rewrites fixable issues in place and reports residual', async () => {+ write('a.md', '# A\n\ntext with a\ttab\n');+ const result = await run({ fix: true });+ expect(result.fixedCount).toBe(1);+ expect(readFileSync(join(root, 'a.md'), 'utf-8')).not.toContain('\t');+ expect(result.files[0]?.fixed).toBe(true);+ });++ test('does not write when there is nothing to fix', async () => {+ write('a.md', '# A\n\nclean paragraph.\n');+ const before = readFileSync(join(root, 'a.md'), 'utf-8');+ const result = await run({ fix: true });+ expect(result.fixedCount).toBe(0);+ expect(readFileSync(join(root, 'a.md'), 'utf-8')).toBe(before);+ });+});++describe('runLint — per-dir cascade (cli2 semantics)', () => {+ test('the nearest .markdownlint.json governs its subtree wholesale', async () => {+ // Root file leaves MD010 (hard tabs) ON; the folder file turns it off.+ write('.markdownlint.json', JSON.stringify({ MD047: false }));+ write('notes/.markdownlint.json', JSON.stringify({ MD010: false, MD047: false }));+ write('tabbed-root.md', '# A\n\na\tb\n');+ write('notes/tabbed-sub.md', '# B\n\na\tb\n');+ const result = await run({});+ const byFile = new Map(result.files.map((f) => [f.file, f.diagnostics]));+ expect(byFile.get('tabbed-root.md')?.some((d) => d.code === 'MD010')).toBe(true);+ expect(byFile.get(join('notes', 'tabbed-sub.md'))?.some((d) => d.code === 'MD010')).toBe(false);+ });++ test('a malformed native file surfaces a loud warning, not silence', async () => {+ write('.markdownlint.json', '{ nope');+ write('a.md', '# A\n');+ const result = await run({});+ expect(result.warnings).toEqual([expect.stringContaining('malformed markdownlint config')]);+ });+});diff --git a/packages/cli/src/content/lint-runner.ts b/packages/cli/src/content/lint-runner.tsnew file mode 100644index 000000000..6266170fd--- /dev/null+++ b/packages/cli/src/content/lint-runner.ts@@ -0,0 +1,201 @@+/**+ * Headless markdown linter — walks a content directory (or a sub-path), lints+ * every in-scope `.md`/`.mdx` document with the core engine, and optionally+ * applies fixes in place. The effective config is the project's `contentRules`+ * base with the native `.markdownlint.*` rules injected (same resolution the+ * server uses).+ */++import {+ readdirSync,+ readFileSync,+ renameSync,+ statSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import {+ fixDocument,+ type LintDiagnostic,+ type LinterConfig,+ lintDocument,+ SUPPORTED_DOC_EXTENSIONS,+} from '@inkeep/open-knowledge-core';+import {+ composeEffectiveLinterConfig,+ createContentFilter,+ resolveNativeConfigForDoc,+} from '@inkeep/open-knowledge-server';++export interface FileLintResult {+ /** Path relative to `contentDir` (as produced by `node:path`). */+ file: string;+ diagnostics: LintDiagnostic[];+ /** True when `--fix` rewrote this file. */+ fixed: boolean;+}++export interface LintRunResult {+ contentDir: string;+ files: FileLintResult[];+ /** Non-fatal issues (unreadable dir/file, …). */+ warnings: string[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ fixedCount: number;+}++export interface RunLintOptions {+ projectDir: string;+ contentDir: string;+ /** The project-level content-rules config (from merged `config.contentRules`). */+ baseConfig: LinterConfig;+ /** Absolute path to a file or folder to scope the run to. Defaults to contentDir. */+ targetPath?: string;+ fix?: boolean;+}++export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {+ const { projectDir, contentDir, baseConfig, targetPath, fix = false } = opts;++ const warnings: string[] = [];+ const filter = createContentFilter({ projectDir, contentDir });++ // markdownlint `rules` come from the project's native `.markdownlint.*`+ // files, resolved per doc with cli2 cascade semantics (nearest file on the+ // doc→root walk governs wholesale; OK's tuned defaults only when no file+ // governs) — the same resolution the server uses. Memoized per directory:+ // every doc in a folder shares one governing file.+ const cfgByDir = new Map<string, LinterConfig>();+ const seenConfigProblems = new Set<string>();+ const configForDoc = (rel: string): LinterConfig => {+ const dir = dirname(rel);+ const cached = cfgByDir.get(dir);+ if (cached) return cached;+ const native = resolveNativeConfigForDoc(contentDir, rel, (problem) => {+ if (seenConfigProblems.has(problem)) return;+ seenConfigProblems.add(problem);+ warnings.push(problem);+ });+ const cfg = composeEffectiveLinterConfig(baseConfig, native);+ cfgByDir.set(dir, cfg);+ return cfg;+ };++ const docFiles: string[] = [];+ const scope = resolveScope(targetPath, contentDir);+ if (scope.kind === 'file') {+ docFiles.push(relative(contentDir, scope.path));+ } else {+ walk(scope.path);+ }++ function walk(absDir: string): void {+ let entries: import('node:fs').Dirent[];+ try {+ entries = readdirSync(absDir, { withFileTypes: true });+ } catch (e) {+ warnings.push(+ `could not read directory ${relative(contentDir, absDir) || '.'}: ${errMsg(e)}`,+ );+ return;+ }+ for (const entry of entries) {+ const full = join(absDir, entry.name);+ const rel = relative(contentDir, full);+ if (entry.isDirectory()) {+ if (filter.isDirExcluded(rel)) continue;+ walk(full);+ } else if (entry.isFile()) {+ if (!isDocFile(entry.name)) continue;+ if (filter.isExcluded(rel)) continue;+ docFiles.push(rel);+ }+ }+ }++ docFiles.sort();++ const files: FileLintResult[] = [];+ let errorCount = 0;+ let warningCount = 0;+ let fixedCount = 0;++ for (const rel of docFiles) {+ const abs = join(contentDir, rel);+ let text: string;+ try {+ text = readFileSync(abs, 'utf-8');+ } catch (e) {+ warnings.push(`could not read ${rel}: ${errMsg(e)}`);+ continue;+ }++ const cfg = configForDoc(rel);+ let wasFixed = false;+ if (fix && cfg.enabled) {+ const fixedText = fixDocument(text, cfg);+ if (fixedText !== text) {+ // tmp + rename so an interrupted write can never leave the document+ // half-written (mirrors the server's markdownlint-write pattern).+ const tmp = `${abs}.tmp.${process.pid}.${Date.now()}`;+ try {+ writeFileSync(tmp, fixedText, 'utf-8');+ renameSync(tmp, abs);+ text = fixedText;+ wasFixed = true;+ fixedCount++;+ } catch (e) {+ try {+ unlinkSync(tmp);+ } catch {+ // tmp may not exist if the write itself failed.+ }+ warnings.push(`could not write fix to ${rel}: ${errMsg(e)}`);+ }+ }+ }++ const diagnostics = await lintDocument(text, cfg, rel);+ for (const d of diagnostics) {+ if (d.severity === 'error') errorCount++;+ else warningCount++;+ }+ files.push({ file: rel, diagnostics, fixed: wasFixed });+ }++ return {+ contentDir,+ files,+ warnings,+ fileCount: docFiles.length,+ errorCount,+ warningCount,+ fixedCount,+ };+}++type Scope = { kind: 'dir' | 'file'; path: string };++/** Resolve the scope to an absolute file or directory under `contentDir`. */+function resolveScope(targetPath: string | undefined, contentDir: string): Scope {+ if (targetPath === undefined || targetPath === '') return { kind: 'dir', path: contentDir };+ const abs = isAbsolute(targetPath) ? targetPath : resolve(contentDir, targetPath);+ try {+ if (statSync(abs).isFile()) return { kind: 'file', path: abs };+ } catch {+ // Fall through — treat as a directory; the walk warns if it's unreadable.+ }+ return { kind: 'dir', path: abs };+}++function isDocFile(name: string): boolean {+ const lower = name.toLowerCase();+ return SUPPORTED_DOC_EXTENSIONS.some((ext) => lower.endsWith(ext));+}++function errMsg(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}diff --git a/packages/cli/src/project-anchor.ts b/packages/cli/src/project-anchor.tsindex f827a34ec..4bb6b380b 100644--- a/packages/cli/src/project-anchor.ts+++ b/packages/cli/src/project-anchor.ts@@ -32,6 +32,7 @@ const PROJECT_ANCHORED_COMMANDS: ReadonlySet<string> = new Set(['ui','mcp','preview',+ 'lint',// `deinit` removes THIS project's OK footprint, so it must anchor to the// enclosing project root when run from a subdirectory. `uninstall` is global// and deliberately NOT anchored (it discovers projects itself).diff --git a/packages/core/package.json b/packages/core/package.jsonindex 71ee7b837..79a04c850 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -57,6 +57,7 @@"@tiptap/starter-kit": "^3.22.3","decode-named-character-reference": "^1.3.0","diff-match-patch": "^1.0.5",+ "markdownlint": "^0.41.0","mdast-util-from-markdown": "^2.0.3","mdast-util-math": "^3.0.0","mdast-util-mdx": "3.0.0",@@ -94,6 +95,7 @@"test:perf:regression": "bun run tests/perf/run-regression-gate.ts","test:health:unit": "bun test tests/health/parse-health-gate.test.ts","test:health": "bun run tests/health/parse-health-gate.ts tests/health/baseline.json",+ "generate:lint-catalog": "bun run scripts/generate-markdownlint-catalog.ts && biome check --write src/markdown/lint/rule-catalog.generated.ts","regen-schema-snapshot": "bun run scripts/regen-schema-snapshot.ts"},"devDependencies": {diff --git a/packages/core/scripts/generate-markdownlint-catalog.ts b/packages/core/scripts/generate-markdownlint-catalog.tsnew file mode 100644index 000000000..fdd411930--- /dev/null+++ b/packages/core/scripts/generate-markdownlint-catalog.ts@@ -0,0 +1,344 @@+/**+ * Regenerates `src/markdown/lint/rule-catalog.generated.ts` from the config+ * schema vendored in the installed markdownlint package. Run via:+ *+ * bun run generate:lint-catalog (packages/core)+ *+ * The schema is fully self-describing: one property per canonical rule+ * (`MD###`), byte-identical alias duplicates, tag toggles, and three meta+ * keys. Every property MUST classify into one of those buckets and every+ * description MUST match its grammar — anything else throws, so upstream+ * grammar drift fails regeneration (and the catalog drift test) loudly+ * instead of silently dropping rules.+ *+ * markdownlint's exports map has no `./schema` subpath, so the schema path is+ * derived from the resolvable main entry — never a hardcoded node_modules+ * path.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { RuleCatalogEntry, RuleOptionSpec } from '../src/markdown/lint/types.ts';++const CANONICAL_RULE_KEY_RE = /^MD\d+$/;+/**+ * Rule descriptions read `MD013/line-length : Line length : https://…`; a+ * rule with several aliases chains them (`MD025/single-title/single-h1 : …`).+ */+const RULE_DESCRIPTION_RE = /^(MD\d+)((?:\/[a-z0-9-]+)+) : (.+?) : (https:\/\/\S+)$/;+/** Tag descriptions read `whitespace : MD009, MD010, …`. */+const TAG_DESCRIPTION_RE = /^([a-z_]+) : (MD\d+(?:, MD\d+)*)$/;+const META_KEYS = new Set(['$schema', 'default', 'extends']);+const SEVERITY_ENUM = JSON.stringify(['error', 'warning']);++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function fail(context: string, detail: string): never {+ throw new Error(+ `markdownlint catalog codegen: ${context}: ${detail} — the vendored schema's shape ` ++ 'changed; update scripts/generate-markdownlint-catalog.ts to match it.',+ );+}++export function resolveMarkdownlintSchemaPath(): string {+ const require = createRequire(import.meta.url);+ return join(+ dirname(require.resolve('markdownlint')),+ '..',+ 'schema',+ 'markdownlint-config-schema.json',+ );+}++/** The `oneOf` options-object branch every rule schema carries. */+function requireRuleOptionsBranch(+ id: string,+ prop: Record<string, unknown>,+): Record<string, unknown> {+ const oneOf = prop.oneOf;+ if (!Array.isArray(oneOf) || oneOf.length !== 3) {+ fail(`rule "${id}"`, 'expected a 3-way oneOf (boolean | severity | options object)');+ }+ const [booleanBranch, severityBranch, objectBranch] = oneOf as unknown[];+ if (!isRecord(booleanBranch) || booleanBranch.type !== 'boolean') {+ fail(`rule "${id}"`, 'oneOf[0] is not the boolean branch');+ }+ if (!isRecord(severityBranch) || JSON.stringify(severityBranch.enum) !== SEVERITY_ENUM) {+ fail(`rule "${id}"`, 'oneOf[1] is not the ["error","warning"] severity branch');+ }+ if (+ !isRecord(objectBranch) ||+ objectBranch.type !== 'object' ||+ !isRecord(objectBranch.properties)+ ) {+ fail(`rule "${id}"`, 'oneOf[2] is not an options object with properties');+ }+ if (!('enabled' in objectBranch.properties) || !('severity' in objectBranch.properties)) {+ fail(`rule "${id}"`, 'options object is missing the enabled/severity keys');+ }+ return objectBranch.properties;+}++function requireTagShape(tag: string, prop: Record<string, unknown>): void {+ const oneOf = prop.oneOf;+ if (!Array.isArray(oneOf) || oneOf.length !== 2) {+ fail(`tag "${tag}"`, 'expected a 2-way oneOf (boolean | severity)');+ }+ const [booleanBranch, severityBranch] = oneOf as unknown[];+ if (!isRecord(booleanBranch) || booleanBranch.type !== 'boolean') {+ fail(`tag "${tag}"`, 'oneOf[0] is not the boolean branch');+ }+ if (!isRecord(severityBranch) || JSON.stringify(severityBranch.enum) !== SEVERITY_ENUM) {+ fail(`tag "${tag}"`, 'oneOf[1] is not the ["error","warning"] severity branch');+ }+}++function isStringArray(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string');+}++function requireOptionalBoolean(value: unknown, context: string): boolean | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== 'boolean') fail(context, `expected a boolean, got ${JSON.stringify(value)}`);+ return value;+}++function requireOptionalNumber(value: unknown, context: string): number | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== 'number') fail(context, `expected a number, got ${JSON.stringify(value)}`);+ return value;+}++function requireOptionalString(value: unknown, context: string): string | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== 'string') fail(context, `expected a string, got ${JSON.stringify(value)}`);+ return value;+}++function requireOptionalStringArray(value: unknown, context: string): string[] | undefined {+ if (value === undefined) return undefined;+ if (!isStringArray(value)) fail(context, `expected a string array, got ${JSON.stringify(value)}`);+ return value;+}++function buildOptionSpec(ruleId: string, key: string, spec: unknown): RuleOptionSpec {+ const context = `rule "${ruleId}" option "${key}"`;+ if (!isRecord(spec)) fail(context, 'expected an object schema');+ const description = spec.description;+ if (typeof description !== 'string' || description.length === 0) {+ fail(context, 'missing a string description');+ }+ const unsupported = (): RuleOptionSpec =>+ spec.default === undefined+ ? { key, type: 'unsupported', description }+ : { key, type: 'unsupported', description, default: spec.default };+ const type = spec.type;+ // Type unions (e.g. integer|array) and any shape outside the widget+ // vocabulary deliberately classify as `unsupported` (read-only in the GUI)+ // rather than failing — only self-inconsistency is an error.+ if (Array.isArray(type)) return unsupported();+ switch (type) {+ case 'boolean': {+ const def = requireOptionalBoolean(spec.default, `${context} default`);+ return def === undefined+ ? { key, type: 'boolean', description }+ : { key, type: 'boolean', description, default: def };+ }+ case 'integer': {+ const def = requireOptionalNumber(spec.default, `${context} default`);+ const minimum = requireOptionalNumber(spec.minimum, `${context} minimum`);+ const maximum = requireOptionalNumber(spec.maximum, `${context} maximum`);+ return {+ key,+ type: 'integer',+ description,+ ...(def !== undefined ? { default: def } : {}),+ ...(minimum !== undefined ? { minimum } : {}),+ ...(maximum !== undefined ? { maximum } : {}),+ };+ }+ case 'string': {+ const def = requireOptionalString(spec.default, `${context} default`);+ const enumValues = spec.enum;+ if (enumValues === undefined) {+ return def === undefined+ ? { key, type: 'string', description }+ : { key, type: 'string', description, default: def };+ }+ if (!isStringArray(enumValues) || enumValues.length === 0) {+ fail(context, 'enum option values are not a non-empty string array');+ }+ return {+ key,+ type: 'enum',+ enum: enumValues,+ description,+ ...(def !== undefined ? { default: def } : {}),+ };+ }+ case 'array': {+ if (!isRecord(spec.items) || spec.items.type !== 'string') return unsupported();+ const def = requireOptionalStringArray(spec.default, `${context} default`);+ return def === undefined+ ? { key, type: 'string-array', description }+ : { key, type: 'string-array', description, default: def };+ }+ default: {+ return unsupported();+ }+ }+}++function buildRuleEntry(id: string, prop: unknown, tags: readonly string[]): RuleCatalogEntry {+ if (!isRecord(prop) || typeof prop.description !== 'string') {+ fail(`rule "${id}"`, 'missing a string description');+ }+ const match = prop.description.match(RULE_DESCRIPTION_RE);+ if (!match) {+ fail(+ `rule "${id}"`,+ `description does not match "MDnnn/alias : Name : url": ${JSON.stringify(prop.description)}`,+ );+ }+ const [, descriptionId, aliasChain, name, docUrl] = match;+ if (descriptionId !== id) {+ fail(`rule "${id}"`, `description names a different rule id ${JSON.stringify(descriptionId)}`);+ }+ const aliases = aliasChain.slice(1).split('/');+ const alias = aliases[0];+ const optionProps = requireRuleOptionsBranch(id, prop);+ const options: RuleOptionSpec[] = [];+ for (const [key, spec] of Object.entries(optionProps)) {+ if (key === 'enabled' || key === 'severity') continue;+ options.push(buildOptionSpec(id, key, spec));+ }+ return { id, alias, aliases, name, docUrl, tags, options };+}++/**+ * Parse the vendored markdownlint config schema into catalog entries.+ * Deterministic over a given schema (property order is preserved), so the+ * drift test can deep-equal a fresh parse against the checked-in module.+ */+export function buildMarkdownlintRuleCatalog(schema: unknown): RuleCatalogEntry[] {+ if (!isRecord(schema) || !isRecord(schema.properties)) {+ fail('schema root', 'expected an object with a `properties` record');+ }+ const properties = schema.properties;+ const canonicalIds = new Set(+ Object.keys(properties).filter((key) => CANONICAL_RULE_KEY_RE.test(key)),+ );++ const ruleTags = new Map<string, string[]>();+ for (const [key, prop] of Object.entries(properties)) {+ if (CANONICAL_RULE_KEY_RE.test(key) || META_KEYS.has(key)) continue;+ if (!isRecord(prop) || typeof prop.description !== 'string') {+ fail(`property "${key}"`, 'missing a string description');+ }+ const ruleMatch = prop.description.match(RULE_DESCRIPTION_RE);+ if (ruleMatch) {+ // Alias-keyed duplicate. Skipping it is only safe while it stays+ // byte-identical to its canonical rule, so verify that.+ const id = ruleMatch[1];+ const canonical = properties[id];+ if (!canonicalIds.has(id) || canonical === undefined) {+ fail(`alias "${key}"`, `references unknown rule ${JSON.stringify(id)}`);+ }+ if (JSON.stringify(prop) !== JSON.stringify(canonical)) {+ fail(+ `alias "${key}"`,+ `differs from its canonical rule "${id}" — skipping it would lose data`,+ );+ }+ continue;+ }+ const tagMatch = prop.description.match(TAG_DESCRIPTION_RE);+ if (!tagMatch) {+ fail(+ `property "${key}"`,+ 'description matches neither the rule grammar ("MDnnn/alias : Name : url") nor the tag ' ++ `grammar ("tag : MDnnn, …"): ${JSON.stringify(prop.description)}`,+ );+ }+ requireTagShape(key, prop);+ for (const id of tagMatch[2].split(', ')) {+ if (!canonicalIds.has(id)) {+ fail(`tag "${key}"`, `references unknown rule ${JSON.stringify(id)}`);+ }+ const tags = ruleTags.get(id) ?? [];+ tags.push(tagMatch[1]);+ ruleTags.set(id, tags);+ }+ }++ const entries: RuleCatalogEntry[] = [];+ for (const [key, prop] of Object.entries(properties)) {+ if (!CANONICAL_RULE_KEY_RE.test(key)) continue;+ entries.push(buildRuleEntry(key, prop, ruleTags.get(key) ?? []));+ }+ return entries;+}++export function renderRuleCatalogModule(catalog: readonly RuleCatalogEntry[]): string {+ const lines: string[] = [+ '/**',+ ' * GENERATED FILE — do not edit by hand. Regenerated by',+ ' * `bun run generate:lint-catalog` (packages/core) from the config schema',+ ' * vendored in the installed markdownlint package; the catalog drift test',+ ' * fails when this file is stale.',+ ' */',+ "import type { RuleCatalogEntry } from './types.ts';",+ '',+ 'export const MARKDOWNLINT_RULE_CATALOG: readonly RuleCatalogEntry[] = [',+ ];+ for (const entry of catalog) {+ lines.push(' {');+ lines.push(` id: ${JSON.stringify(entry.id)},`);+ lines.push(` alias: ${JSON.stringify(entry.alias)},`);+ lines.push(` aliases: ${JSON.stringify(entry.aliases)},`);+ lines.push(` name: ${JSON.stringify(entry.name)},`);+ lines.push(` docUrl: ${JSON.stringify(entry.docUrl)},`);+ lines.push(` tags: ${JSON.stringify(entry.tags)},`);+ if (entry.options.length === 0) {+ lines.push(' options: [],');+ } else {+ lines.push(' options: [');+ for (const option of entry.options) {+ const fields = [+ `key: ${JSON.stringify(option.key)}`,+ `type: ${JSON.stringify(option.type)}`,+ `description: ${JSON.stringify(option.description)}`,+ ];+ if (option.type === 'enum') fields.push(`enum: ${JSON.stringify(option.enum)}`);+ if (option.default !== undefined) fields.push(`default: ${JSON.stringify(option.default)}`);+ if (option.type === 'integer') {+ if (option.minimum !== undefined)+ fields.push(`minimum: ${JSON.stringify(option.minimum)}`);+ if (option.maximum !== undefined)+ fields.push(`maximum: ${JSON.stringify(option.maximum)}`);+ }+ lines.push(` { ${fields.join(', ')} },`);+ }+ lines.push(' ],');+ }+ lines.push(' },');+ }+ lines.push('];');+ lines.push('');+ return lines.join('\n');+}++if (import.meta.main) {+ const schemaPath = resolveMarkdownlintSchemaPath();+ const schema: unknown = JSON.parse(readFileSync(schemaPath, 'utf8'));+ const catalog = buildMarkdownlintRuleCatalog(schema);+ const outputPath = resolve(+ dirname(fileURLToPath(import.meta.url)),+ '../src/markdown/lint/rule-catalog.generated.ts',+ );+ writeFileSync(outputPath, renderRuleCatalogModule(catalog), 'utf8');+ console.log(`lint-catalog: wrote ${catalog.length} rules to ${outputPath}`);+}diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex 8f9d95287..c014b1413 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,4 +1,3 @@-import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 8bfdb40cd..005627195 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,4 +1,3 @@-import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex c18c086d5..8890f6739 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 463e89595..9d9c244b0 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,4 +1,3 @@-const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 3c927eb47..3ab9cc6ef 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -38,7 +38,6 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: stringreturn parts.join('\n');}-export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 592f0b956..e67f33b40 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,4 +1,3 @@-const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 0be5203e4..754dc5cc2 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;-interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}-/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}-export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex dca644141..af20de1e2 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,4 +1,3 @@-/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 5734ecbb1..2f2803887 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -143,7 +143,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'expect(allowlisted).toEqual([]);});- test('user-strict fields cover agents.autoApproveOkTools + appearance.preview.autoOpen + appearance.theme + editor.wordWrap', () => {+ test('user-strict fields cover agents.autoApproveOkTools + appearance.{colorTheme,colorThemeEnabled,customTheme.*,preview.autoOpen,theme} + editor.wordWrap', () => {const leaves: { path: string[]; schema: unknown }[] = [];walkLeaves(ConfigSchema, [], leaves);const userStrict = leaves@@ -152,13 +152,21 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'.sort();expect(userStrict).toEqual(['agents.autoApproveOkTools',+ 'appearance.colorTheme',+ 'appearance.colorThemeEnabled',+ 'appearance.customTheme.accent',+ 'appearance.customTheme.background',+ 'appearance.customTheme.border',+ 'appearance.customTheme.foreground',+ 'appearance.customTheme.primary',+ 'appearance.customTheme.surface','appearance.preview.autoOpen','appearance.theme','editor.wordWrap',]);});- test('project-strict fields cover autoSync.default + content.* + telemetry.localSink.*', () => {+ test('project-strict fields cover autoSync.default + content.* + contentRules.* + telemetry.localSink.*', () => {// `autoSync.default` is the committed seed for a machine's// `autoSync.enabled` on first open (true/false/null). Project scope is the// whole point — it travels with the repo so a maintainer pre-answers the@@ -178,6 +186,11 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'// defaults shared across collaborators in the committed `config.yml`;// disabling the sink is also a project-level decision (sensitive// workspaces opt out across the whole team).+ //+ // `contentRules.*` is the project's markdown authoring standard — which+ // lint plugins run. Shared via the committed `config.yml` (the OK analog of+ // a checked-in `.markdownlint.json`). Each plugin's slice registers its own+ // leaves under `contentRules.<id>.*`.const leaves: { path: string[]; schema: unknown }[] = [];walkLeaves(ConfigSchema, [], leaves);const projectStrict = leaves@@ -188,6 +201,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''autoSync.default','content.attachmentFolderPath','content.dir',+ 'contentRules.markdownlint.enabled','telemetry.localSink.attributeDenylist','telemetry.localSink.enabled','telemetry.localSink.logs.maxBytes',diff --git a/packages/core/src/config/linter-leaf-registry-consistency.test.ts b/packages/core/src/config/linter-leaf-registry-consistency.test.tsnew file mode 100644index 000000000..adc7846bc--- /dev/null+++ b/packages/core/src/config/linter-leaf-registry-consistency.test.ts@@ -0,0 +1,49 @@+/**+ * Drift guard: the hand-authored `linter` leaf of the config.yml schema+ * (`schema.ts`) must stay in lockstep with the lint plugin registry+ * (`markdown/lint`). The leaf is deliberately NOT derived from the registry —+ * it carries config-system metadata (per-field `scope` / `agentSettable` /+ * `description` + the config-walker registration contract) that doesn't belong+ * on the lint descriptors, and deriving it would couple `markdown/lint` to+ * `config` (the `fieldRegistry` lives here). So it's the one place adding a+ * plugin still needs a manual edit — and these tests make a forgotten edit a+ * loud failure instead of a silent shape mismatch.+ */++import { describe, expect, test } from 'bun:test';+import {+ LINT_PLUGINS,+ LinterConfigSchema,+ type PersistedLinterConfig,+ toEffectiveBase,+} from '../markdown/lint/index.ts';+import { ConfigSchema } from './schema.ts';++describe('config.yml linter leaf ⟷ plugin registry', () => {+ // The resolved default the config.yml schema produces for a project that+ // configures nothing.+ const linterDefault = ConfigSchema.parse({}).contentRules;++ test('the config.yml linter default has exactly the registry plugin ids', () => {+ // Each plugin is a direct child of `contentRules` (no `plugins` wrapper).+ expect(Object.keys(linterDefault).sort()).toEqual(+ LINT_PLUGINS.map((plugin) => plugin.id).sort(),+ );+ });++ test('the lifted config.yml linter default validates against the registry-derived schema', () => {+ // Persisted config.yml omits markdownlint `rules` (native-file sourced), so+ // lift it to an effective config first. If a plugin's persisted slice drifts+ // from its descriptor sliceSchema, the effective LinterConfigSchema rejects it.+ const result = LinterConfigSchema.safeParse(+ toEffectiveBase(linterDefault as unknown as PersistedLinterConfig),+ );+ expect(result.success).toBe(true);+ });++ test('every registered plugin has a config.yml slice (default carries it)', () => {+ for (const plugin of LINT_PLUGINS) {+ expect(linterDefault).toHaveProperty(plugin.id);+ }+ });+});diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.tsindex a74ab349a..f69a421c9 100644--- a/packages/core/src/config/schema.test.ts+++ b/packages/core/src/config/schema.test.ts@@ -192,3 +192,20 @@ describe('legacy upload.* keys remain non-authoritative', () => {expect(result.success).toBe(true);});});++describe('contentRules forward compatibility', () => {+ test('an unknown plugin slice survives parse instead of being stripped', () => {+ // A NEWER OK version's plugin config (a direct child of `contentRules`) must+ // round-trip through an older version's parse→write-back cycle, not silently+ // disappear.+ const parsed = ConfigSchema.parse({+ contentRules: { 'future-linter': { enabled: true, level: 'strict' } },+ });+ expect(parsed.contentRules['future-linter']).toEqual({+ enabled: true,+ level: 'strict',+ });+ // The known slice still defaults alongside the unknown one (off by default).+ expect(parsed.contentRules.markdownlint).toEqual({ enabled: false });+ });+});diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 4d5d3c860..6ca2a6a16 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -1,5 +1,6 @@import { z } from 'zod';import { DEFAULT_ATTACHMENT_FOLDER_PATH } from '../constants/upload.ts';+import { THEME_PLUGIN_IDS } from '../theme/theme-plugins.ts';import { fieldRegistry } from './field-registry.ts';// Credential attribute key denylist for the local telemetry file sink. The@@ -186,6 +187,103 @@ export const ConfigSchema = z.looseObject({"Editor color theme: 'light', 'dark', or 'system' (follow the OS). A personal preference (user scope) — not shared with the project.",}).optional(),+ // The IDE color palette layered on top of the light/dark `theme` mode+ // above. `default` defers entirely to `theme`; the named palettes+ // (Dracula, Catppuccin Frappé, Catppuccin Latte, …) are self-contained+ // themes that force their own light/dark mode; `custom` applies the+ // user's own `appearance.customTheme` seed below. A personal preference+ // (user scope). The id list is DERIVED from the `THEME_PLUGINS` registry+ // (`packages/core/src/theme/theme-plugins.ts`) via `THEME_PLUGIN_IDS` — add+ // a theme there and this enum follows, with no edit here.+ colorTheme: z+ .enum(THEME_PLUGIN_IDS)+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ "IDE color palette: 'default' (follows the light/dark theme), one of 'dracula', 'catppuccin-frappe', 'catppuccin-latte', 'monokai', 'gruvbox', 'solarized', or 'custom' (your own colors from appearance.customTheme). A personal preference (user scope) — not shared with the project.",+ })+ .optional(),+ // Whether the Themes plugin appears under Settings → Plugins. The theme is+ // a user-scope plugin (personal, not shared via git), toggled on the Plugins+ // management page like the lint plugins. Default on (absent → enabled).+ colorThemeEnabled: z+ .boolean()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ 'Whether the Themes plugin appears in Settings → Plugins. A personal preference (user scope). Default on.',+ })+ .optional(),+ // Six seed colors for the `custom` color theme. The app derives the full+ // token set from these (text contrast, muted text, accents) — see+ // `expandCustomSeed` in `packages/app/src/lib/color-themes.ts`. Each value+ // is a `#rrggbb` hex string; light-vs-dark mode is auto-detected from the+ // background's luminance. A personal preference (user scope).+ customTheme: z+ .looseObject({+ background: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description: 'Custom theme: editor canvas background, as a #rrggbb hex string.',+ })+ .optional(),+ surface: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ 'Custom theme: elevated surfaces (cards, sidebar, popovers), as a #rrggbb hex string.',+ })+ .optional(),+ foreground: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description: 'Custom theme: primary text color, as a #rrggbb hex string.',+ })+ .optional(),+ primary: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ 'Custom theme: accent color for buttons, links, and focus, as a #rrggbb hex string.',+ })+ .optional(),+ accent: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description:+ 'Custom theme: secondary accent (syntax highlights, charts), as a #rrggbb hex string.',+ })+ .optional(),+ border: z+ .string()+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description: 'Custom theme: hairline border + input color, as a #rrggbb hex string.',+ })+ .optional(),+ })+ .optional(),preview: z.looseObject({autoOpen: z@@ -534,6 +632,47 @@ export const ConfigSchema = z.looseObject({model: DEFAULT_EMBEDDINGS_MODEL,},}),+ // Content rules (the markdown linter). PROJECT scope: lint standards (which+ // rules run, whether linting is on) are an authoring decision shared with the+ // team via git — the OK equivalent of a committed `.markdownlint.json`. The+ // no-code settings section + the desktop View-menu toggle write here; the+ // CodeMirror lint facet reads it. Defaults match `DEFAULT_LINTER_CONFIG` in+ // `markdown/lint`.+ contentRules: z+ .looseObject({+ // Lint plugins. Each entry is one built-in lint family with its own+ // per-plugin `enabled`; diagnostics from enabled plugins are concatenated.+ //+ // This leaf is hand-authored (not folded from the lint registry) because it+ // carries config-system metadata — per-field scope / agentSettable /+ // description + the walker registration contract — and deriving it would+ // couple markdown/lint to config. Adding a plugin means adding its slice+ // here too; `linter-leaf-registry-consistency.test.ts` fails loudly if this+ // drifts from LINT_PLUGINS.+ //+ // looseObject: a plugin slice written by a NEWER OK version must survive+ // an older version's parse→write-back cycle instead of being stripped. Each+ // plugin is a direct child of `contentRules` (no `plugins` wrapper).+ markdownlint: z+ .object({+ enabled: z+ .boolean()+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description: 'Whether the markdownlint plugin (body rules) contributes diagnostics.',+ })+ .default(false),+ // The markdownlint `rules` are NOT persisted here. They live in the+ // project's own `.markdownlint.{json,jsonc,yaml,yml}` (native file =+ // source of truth, discovered server-side and injected into the+ // effective config; OK's tuned defaults layer under it). OK config+ // persists only this toggle.+ })+ .default({ enabled: false }),+ })+ .default({ markdownlint: { enabled: false } }),// PROJECT-LOCAL scope: external link-hover previews send the hovered URL to// the destination site to fetch its metadata (egress), so — like semantic// search — each teammate opts in on their own machine rather than inheritingdiff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.tsindex cf07c3289..311089c6c 100644--- a/packages/core/src/handoff/urn-ipc-registry.ts+++ b/packages/core/src/handoff/urn-ipc-registry.ts@@ -292,6 +292,10 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>(['urn:ok:error:handoff-target-not-installed','urn:ok:error:handoff-spawn-timeout','urn:ok:error:handoff-spawn-failed',+ // Lint config write (`POST /api/lint/markdownlint-config` → 409 when the+ // native `.markdownlint.*` file can't be written). HTTP-only — the lint+ // config surface is REST, with no IPC counterpart.+ 'urn:ok:error:config-not-writable',]);/**diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex e948da79a..8e4df1a93 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -396,6 +396,54 @@ export {mdastToMarkdown,} from './markdown/html-to-mdast.ts';export { MarkdownManager, type SerializeCallOptions } from './markdown/index.ts';+// Markdown linter (the content-rules lint-plugin registry). Browser-safe;+// consumed by the editor's CodeMirror lint facet + the no-code Settings GUI.+export {+ applyTextEdits,+ canonicalRuleId,+ DEFAULT_LINTER_CONFIG,+ DEFAULT_MARKDOWNLINT_CONFIG,+ displayCategoryForRule,+ findRuleConfigEntry,+ fixDocument,+ fixMarkdownText,+ LINT_PLUGINS,+ type LintAuditResponse,+ LintAuditResponseSchema,+ type LintConfigResponse,+ LintConfigResponseSchema,+ type LintDiagnostic,+ type LintDocResult,+ LintDocResultSchema,+ type LinterConfig,+ LinterConfigSchema,+ type LintFixRequest,+ LintFixRequestSchema,+ type LintFixResult,+ LintFixResultSchema,+ type LintPlugin,+ type LintPluginId,+ type LintPosition,+ type LintRange,+ type LintSeverity,+ type LintTextEdit,+ lintDocument,+ MARKDOWNLINT_RULE_CATALOG,+ type MarkdownlintRuleSetting,+ type MarkdownlintRuleSeverity,+ MarkdownlintRuleWriteRequestSchema,+ type MarkdownlintRuleWriteValue,+ type MarkdownlintSlice,+ type PersistedLinterConfig,+ RULE_DISPLAY_CATEGORIES,+ type RuleCatalogEntry,+ type RuleDisplayCategory,+ type RuleOptionSpec,+ type RuleOptionType,+ resolveMarkdownlintConfig,+ runMarkdownlint,+ toEffectiveBase,+} from './markdown/lint/index.ts';export { markdownToHtml, mdastToHtml } from './markdown/mdast-to-html.ts';export { normalizeDocRelativeAssetUrl } from './markdown/resolve-image-url.ts';export {@@ -625,6 +673,8 @@ export {LinkPreviewRequestSchema,type LinkPreviewResponse,LinkPreviewResponseSchema,+ type LintViolationWarning,+ LintViolationWarningSchema,type LocalOpAuthEmptySuccess,LocalOpAuthEmptySuccessSchema,type LocalOpAuthHostRequest,@@ -928,6 +978,16 @@ export {type DerivedViewChannel,DerivedViewChannelSchema,} from './schemas/cc1.ts';+export type { ColorThemeBase, ThemePlugin, ThemePluginId } from './theme/theme-plugins.ts';+export {+ colorThemeMode,+ expandPalette,+ generateColorThemesCss,+ isDarkTheme,+ resolveThemePlugin,+ THEME_PLUGIN_IDS,+ THEME_PLUGINS,+} from './theme/theme-plugins.ts';export {HIDDEN_CONFIG_BASENAMES,isHiddenDocName,diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex a363dfd54..83d47404a 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,4 +1,3 @@-import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 47f0d07e4..193e286b0 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex b6299a948..ece5c02a1 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,4 +1,3 @@-import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex acd398aa6..54774764a 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex fb5ac8e8a..c7518d614 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,4 +1,3 @@-const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 6931623c7..00f5771ee 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}-interface GfmExample {section: string;markdown: string;@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}-interface MdxCrashEntry {id: string;input: string;@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}-export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}-export interface NgPinnedCase {id: string;name: string;@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}-export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex daa3ef82b..8b1eb8519 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;-function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}-const WORDS = ['lorem','ipsum',@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}-type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}-function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 32c055c5b..420dc0fe5 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,7 +7,6 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';-export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 283913255..2653473da 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,4 +1,3 @@-export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex 7a22e8016..f758cf737 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 2f082e6d0..78fdfeb02 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,4 +1,3 @@-import type { Root as HastRoot } from 'hast';import type { Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -76,8 +75,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified()- .use(rehypeParse, { fragment: true });+ const processor = unified().use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 994eb6917..706fa9afb 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,4 +1,3 @@-import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 3e39501d5..a5827a5d0 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromPmMark,@@ -197,7 +196,6 @@ export class MarkdownManager {}}-const registry = createRegistry();function destructureAttrs(@@ -246,7 +244,6 @@ function destructureAttrs(return result;}-function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -266,7 +263,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}-function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -335,7 +331,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}-import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -582,7 +577,6 @@ function buildMdastToPmHandlers(}));}-if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -662,7 +656,6 @@ function buildMdastToPmHandlers(}));}-if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -941,7 +934,6 @@ function buildMdastToPmHandlers(};}-const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1067,7 +1059,6 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}-function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsnew file mode 100644index 000000000..e78a1381d--- /dev/null+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -0,0 +1,101 @@+import { z } from 'zod';+import { agentIdentityFields, safeDocNameField, summaryField } from '../../schemas/api/_shared.ts';+import { DEFAULT_MARKDOWNLINT_CONFIG } from './default-config.ts';+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';+import type { MarkdownlintRuleSetting } from './types.ts';++interface PersistedMarkdownlintSlice {+ enabled: boolean;+ rules?: Record<string, MarkdownlintRuleSetting>;+}+export interface PersistedLinterConfig {+ enabled?: boolean;+ markdownlint: PersistedMarkdownlintSlice;+}++export function toEffectiveBase(persisted: PersistedLinterConfig): LinterConfig {+ return {+ enabled: persisted.enabled ?? true,+ plugins: {+ markdownlint: {+ ...persisted.markdownlint,+ rules: persisted.markdownlint.rules ?? DEFAULT_MARKDOWNLINT_CONFIG,+ },+ },+ };+}++const fullPluginShape = Object.fromEntries(+ LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),+) as z.ZodRawShape;++export const LinterConfigSchema = z.object({+ enabled: z.boolean(),+ plugins: z.object(fullPluginShape),+}) as unknown as z.ZodType<LinterConfig>;++export const LintConfigResponseSchema = z.object({+ effective: LinterConfigSchema,+ configFile: z.string().nullable().optional(),+ configProblems: z.array(z.string()).optional(),+});++const MarkdownlintRuleWriteValueSchema = z.union([z.boolean(), z.record(z.string(), z.unknown())]);++export const MarkdownlintRuleWriteRequestSchema = z.object({+ ruleId: z+ .string()+ .min(1)+ .max(64)+ .regex(/^[A-Za-z][A-Za-z0-9_-]*$/),+ value: z.union([MarkdownlintRuleWriteValueSchema, z.null()]),+});++export type LintConfigResponse = z.infer<typeof LintConfigResponseSchema>;++const LintPositionSchema = z.object({ line: z.number(), character: z.number() });+const LintRangeSchema = z.object({ start: LintPositionSchema, end: LintPositionSchema });++const LintDiagnosticSchema = z.object({+ range: LintRangeSchema,+ severity: z.enum(['error', 'warning', 'info', 'hint']),+ source: z.string(),+ code: z.string(),+ message: z.string(),+ fixes: z.array(z.object({ range: LintRangeSchema, newText: z.string() })).optional(),+});++export const LintDocResultSchema = z.object({+ file: z.string(),+ diagnostics: z.array(LintDiagnosticSchema),+});++export const LintAuditResponseSchema = z.object({+ files: z.array(LintDocResultSchema),+ fileCount: z.number(),+ errorCount: z.number(),+ warningCount: z.number(),+ warnings: z.array(z.string()),+});++export type LintDocResult = z.infer<typeof LintDocResultSchema>;+export type LintAuditResponse = z.infer<typeof LintAuditResponseSchema>;++export const LintFixRequestSchema = z+ .object({+ docName: safeDocNameField,+ summary: summaryField,+ ...agentIdentityFields,+ })+ .loose();+export type LintFixRequest = z.infer<typeof LintFixRequestSchema>;++export const LintFixResultSchema = z.object({+ file: z.string(),+ fixedCount: z.number(),+ diagnostics: z.array(LintDiagnosticSchema),+ errorCount: z.number(),+ warningCount: z.number(),+ warning: z.string().optional(),+});+export type LintFixResult = z.infer<typeof LintFixResultSchema>;diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsnew file mode 100644index 000000000..d48eea5e4--- /dev/null+++ b/packages/core/src/markdown/lint/default-config.ts@@ -0,0 +1,13 @@+import type { Configuration } from 'markdownlint';+import type { MarkdownlintRuleSetting } from './types.ts';++export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting> = {+ default: true,+ MD013: false,+};++export function resolveMarkdownlintConfig(+ rules: Record<string, MarkdownlintRuleSetting> | undefined,+): Configuration {+ return rules ?? DEFAULT_MARKDOWNLINT_CONFIG;+}diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsnew file mode 100644index 000000000..d1a5ab4dc--- /dev/null+++ b/packages/core/src/markdown/lint/index.ts@@ -0,0 +1,78 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';+import type { LintDiagnostic } from './types.ts';++export async function lintDocument(+ text: string,+ config: LinterConfig,+ docName?: string,+): Promise<LintDiagnostic[]> {+ if (!config.enabled) return [];+ const diagnostics: LintDiagnostic[] = [];+ for (const plugin of LINT_PLUGINS) {+ const slice = config.plugins[plugin.id];+ if (!slice.enabled) continue;+ diagnostics.push(+ ...(await plugin.lint(text, slice as Parameters<typeof plugin.lint>[1], { docName })),+ );+ }+ return diagnostics;+}++export function fixDocument(text: string, config: LinterConfig): string {+ if (!config.enabled) return text;+ let out = text;+ for (const plugin of LINT_PLUGINS) {+ const slice = config.plugins[plugin.id];+ if (!slice.enabled || !plugin.fix) continue;+ out = plugin.fix(out, slice as Parameters<NonNullable<typeof plugin.fix>>[1]);+ }+ return out;+}++export {+ type LintAuditResponse,+ LintAuditResponseSchema,+ type LintConfigResponse,+ LintConfigResponseSchema,+ type LintDocResult,+ LintDocResultSchema,+ LinterConfigSchema,+ type LintFixRequest,+ LintFixRequestSchema,+ type LintFixResult,+ LintFixResultSchema,+ MarkdownlintRuleWriteRequestSchema,+ type PersistedLinterConfig,+ toEffectiveBase,+} from './config-schemas.ts';+export { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';+export { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';+export {+ DEFAULT_LINTER_CONFIG,+ LINT_PLUGINS,+ type LinterConfig,+ type LintPlugin,+ type LintPluginId,+} from './plugins.ts';+export { canonicalRuleId, findRuleConfigEntry } from './rule-aliases.ts';+export { MARKDOWNLINT_RULE_CATALOG } from './rule-catalog.generated.ts';+export {+ displayCategoryForRule,+ RULE_DISPLAY_CATEGORIES,+ type RuleDisplayCategory,+} from './rule-catalog-categories.ts';+export { applyTextEdits } from './text-edits.ts';+export type {+ LintDiagnostic,+ LintPosition,+ LintRange,+ LintSeverity,+ LintTextEdit,+ MarkdownlintRuleSetting,+ MarkdownlintRuleSeverity,+ MarkdownlintRuleWriteValue,+ MarkdownlintSlice,+ RuleCatalogEntry,+ RuleOptionSpec,+ RuleOptionType,+} from './types.ts';diff --git a/packages/core/src/markdown/lint/markdownlint-runner.ts b/packages/core/src/markdown/lint/markdownlint-runner.tsnew file mode 100644index 000000000..194c637c1--- /dev/null+++ b/packages/core/src/markdown/lint/markdownlint-runner.ts@@ -0,0 +1,109 @@+import { applyFixes, type Configuration, type FixInfo, type LintError } from 'markdownlint';+import { lint } from 'markdownlint/sync';+import type { LintDiagnostic, LintTextEdit } from './types.ts';++const STRING_ID = 'doc';++export function fixMarkdownText(text: string, config: Configuration): string {+ const results = lint({ strings: { [STRING_ID]: text }, config });+ return applyFixes(text, results[STRING_ID] ?? []);+}++export function runMarkdownlint(text: string, config: Configuration): LintDiagnostic[] {+ const results = lint({ strings: { [STRING_ID]: text }, config });+ const errors = results[STRING_ID] ?? [];+ const lines = text.split('\n');+ const severities = buildSeverityIndex(config);+ return errors.map((error) => toDiagnostic(error, lines, severityFor(error, severities)));+}++type RuleSeverity = 'error' | 'warning';+type SeverityIndex = ReadonlyMap<string, { entryIndex: number; severity: RuleSeverity }>;++function buildSeverityIndex(config: Configuration): SeverityIndex {+ const map = new Map<string, { entryIndex: number; severity: RuleSeverity }>();+ Object.entries(config).forEach(([key, value], entryIndex) => {+ const upper = key.toUpperCase();+ if (upper === 'DEFAULT') return;+ let severity: RuleSeverity | null = null;+ if (value === 'error' || value === 'warning') {+ severity = value;+ } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {+ const s = (value as { severity?: unknown }).severity;+ if (s === 'error' || s === 'warning') severity = s;+ }+ if (severity !== null) map.set(upper, { entryIndex, severity });+ });+ return map;+}++function severityFor(error: LintError, severities: SeverityIndex): RuleSeverity {+ let governing: { entryIndex: number; severity: RuleSeverity } | undefined;+ for (const name of error.ruleNames) {+ const hit = severities.get(name.toUpperCase());+ if (hit !== undefined && (governing === undefined || hit.entryIndex > governing.entryIndex)) {+ governing = hit;+ }+ }+ return governing?.severity ?? 'warning';+}++function toDiagnostic(error: LintError, lines: string[], severity: RuleSeverity): LintDiagnostic {+ const [column, length] = error.errorRange ?? [1, null];+ const line = error.lineNumber - 1;+ const startCharacter = (column ?? 1) - 1;+ const lineLength = lines[line]?.length ?? 0;+ const endCharacter = length == null ? lineLength : Math.min(startCharacter + length, lineLength);+ const fixes = error.fixInfo ? [fixInfoToEdit(error.fixInfo, error.lineNumber, lines)] : undefined;+ return {+ range: {+ start: { line, character: startCharacter },+ end: { line, character: Math.max(endCharacter, startCharacter) },+ },+ severity,+ source: 'markdownlint',+ code: error.ruleNames[0] ?? 'MD000',+ message: error.errorDetail+ ? `${error.ruleDescription}: ${error.errorDetail}`+ : error.ruleDescription,+ ...(fixes ? { fixes } : {}),+ };+}++function fixInfoToEdit(fixInfo: FixInfo, diagnosticLine: number, lines: string[]): LintTextEdit {+ const lineNumber = fixInfo.lineNumber ?? diagnosticLine; // 1-based+ const line = lineNumber - 1;+ if (fixInfo.deleteCount === -1) {+ if (lineNumber < lines.length) {+ return {+ range: { start: { line, character: 0 }, end: { line: line + 1, character: 0 } },+ newText: '',+ };+ }+ if (line > 0) {+ const prevLength = lines[line - 1]?.length ?? 0;+ return {+ range: {+ start: { line: line - 1, character: prevLength },+ end: { line, character: lines[line]?.length ?? 0 },+ },+ newText: '',+ };+ }+ return {+ range: {+ start: { line: 0, character: 0 },+ end: { line: 0, character: lines[0]?.length ?? 0 },+ },+ newText: '',+ };+ }+ const startCharacter = (fixInfo.editColumn ?? 1) - 1;+ return {+ range: {+ start: { line, character: startCharacter },+ end: { line, character: startCharacter + Math.max(0, fixInfo.deleteCount ?? 0) },+ },+ newText: fixInfo.insertText ?? '',+ };+}diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsnew file mode 100644index 000000000..1cd40ef3a--- /dev/null+++ b/packages/core/src/markdown/lint/plugins.ts@@ -0,0 +1,60 @@+import { z } from 'zod';+import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';+import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';+import {+ type LintDiagnostic,+ type LintPluginId,+ MARKDOWNLINT_RULE_SEVERITIES,+ type MarkdownlintSlice,+} from './types.ts';++const MarkdownlintRuleSettingSchema = z.union([+ z.boolean(),+ z.enum(MARKDOWNLINT_RULE_SEVERITIES),+ z.record(z.string(), z.unknown()),+]);++export interface LintPlugin<Id extends LintPluginId, Slice> {+ id: Id;+ sliceSchema: z.ZodType<Slice>;+ defaultSlice: Slice;+ lint(text: string, slice: Slice, ctx: { docName?: string }): Promise<LintDiagnostic[]>;+ fix?(text: string, slice: Slice): string;+}++const markdownlintPlugin: LintPlugin<'markdownlint', MarkdownlintSlice> = {+ id: 'markdownlint',+ sliceSchema: z.object({+ enabled: z.boolean(),+ rules: z.record(z.string(), MarkdownlintRuleSettingSchema),+ }),+ defaultSlice: { enabled: false, rules: DEFAULT_MARKDOWNLINT_CONFIG },+ async lint(text, slice) {+ return runMarkdownlint(text, resolveMarkdownlintConfig(slice.rules));+ },+ fix(text, slice) {+ return fixMarkdownText(text, resolveMarkdownlintConfig(slice.rules));+ },+};++export const LINT_PLUGINS = [markdownlintPlugin] as const;++type LintPluginEntry = (typeof LINT_PLUGINS)[number];++export type { LintPluginId };++export type LinterConfig = {+ enabled: boolean;+ plugins: {+ [K in LintPluginId]: Extract<LintPluginEntry, { id: K }> extends LintPlugin<K, infer S>+ ? S+ : never;+ };+};++export const DEFAULT_LINTER_CONFIG: LinterConfig = {+ enabled: true,+ plugins: Object.fromEntries(+ LINT_PLUGINS.map((plugin) => [plugin.id, plugin.defaultSlice]),+ ) as LinterConfig['plugins'],+};diff --git a/packages/core/src/markdown/lint/rule-aliases.ts b/packages/core/src/markdown/lint/rule-aliases.tsnew file mode 100644index 000000000..c1bc45270--- /dev/null+++ b/packages/core/src/markdown/lint/rule-aliases.ts@@ -0,0 +1,36 @@+import { MARKDOWNLINT_RULE_CATALOG } from './rule-catalog.generated.ts';++const keyToCanonicalId: ReadonlyMap<string, string> = (() => {+ const map = new Map<string, string>();+ for (const entry of MARKDOWNLINT_RULE_CATALOG) {+ map.set(entry.id.toUpperCase(), entry.id);+ for (const alias of entry.aliases) {+ map.set(alias.toUpperCase(), entry.id);+ }+ }+ return map;+})();++export function canonicalRuleId(key: string): string | null {+ return keyToCanonicalId.get(key.toUpperCase()) ?? null;+}++interface RuleConfigEntry {+ key: string;+ value: unknown;+}++export function findRuleConfigEntry(+ rules: Readonly<Record<string, unknown>>,+ ruleId: string,+): RuleConfigEntry | undefined {+ const canonical = canonicalRuleId(ruleId);+ if (canonical === null) return undefined;+ let found: RuleConfigEntry | undefined;+ for (const [key, value] of Object.entries(rules)) {+ if (canonicalRuleId(key) === canonical) {+ found = { key, value };+ }+ }+ return found;+}diff --git a/packages/core/src/markdown/lint/rule-catalog-categories.ts b/packages/core/src/markdown/lint/rule-catalog-categories.tsnew file mode 100644index 000000000..7c10cc876--- /dev/null+++ b/packages/core/src/markdown/lint/rule-catalog-categories.ts@@ -0,0 +1,38 @@+import type { RuleCatalogEntry } from './types.ts';++export const RULE_DISPLAY_CATEGORIES = [+ 'Headings',+ 'Lists',+ 'Whitespace',+ 'Code',+ 'Links & images',+ 'Style',+] as const;++export type RuleDisplayCategory = (typeof RULE_DISPLAY_CATEGORIES)[number];++const TAG_DISPLAY_CATEGORY_PRECEDENCE: readonly (readonly [string, RuleDisplayCategory])[] = [+ ['headings', 'Headings'],+ ['bullet', 'Lists'],+ ['ul', 'Lists'],+ ['ol', 'Lists'],+ ['links', 'Links & images'],+ ['images', 'Links & images'],+ ['accessibility', 'Links & images'],+ ['code', 'Code'],+ ['language', 'Code'],+ ['emphasis', 'Style'],+ ['html', 'Style'],+ ['line_length', 'Whitespace'],+ ['whitespace', 'Whitespace'],+ ['hard_tab', 'Whitespace'],+ ['blank_lines', 'Whitespace'],+ ['indentation', 'Whitespace'],+];++export function displayCategoryForRule(rule: Pick<RuleCatalogEntry, 'tags'>): RuleDisplayCategory {+ for (const [tag, category] of TAG_DISPLAY_CATEGORY_PRECEDENCE) {+ if (rule.tags.includes(tag)) return category;+ }+ return 'Style';+}diff --git a/packages/core/src/markdown/lint/rule-catalog.generated.ts b/packages/core/src/markdown/lint/rule-catalog.generated.tsnew file mode 100644index 000000000..204a7f22e--- /dev/null+++ b/packages/core/src/markdown/lint/rule-catalog.generated.ts@@ -0,0 +1,881 @@+import type { RuleCatalogEntry } from './types.ts';++export const MARKDOWNLINT_RULE_CATALOG: readonly RuleCatalogEntry[] = [+ {+ id: 'MD001',+ alias: 'heading-increment',+ aliases: ['heading-increment'],+ name: 'Heading levels should only increment by one level at a time',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md001.md',+ tags: ['headings'],+ options: [+ {+ key: 'front_matter_title',+ type: 'string',+ description: 'RegExp for matching title in front matter',+ default: '^\\s*title\\s*[:=]',+ },+ ],+ },+ {+ id: 'MD003',+ alias: 'heading-style',+ aliases: ['heading-style'],+ name: 'Heading style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md003.md',+ tags: ['headings'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Heading style',+ enum: [+ 'consistent',+ 'atx',+ 'atx_closed',+ 'setext',+ 'setext_with_atx',+ 'setext_with_atx_closed',+ ],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD004',+ alias: 'ul-style',+ aliases: ['ul-style'],+ name: 'Unordered list style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md004.md',+ tags: ['bullet', 'ul'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'List style',+ enum: ['consistent', 'asterisk', 'plus', 'dash', 'sublist'],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD005',+ alias: 'list-indent',+ aliases: ['list-indent'],+ name: 'Inconsistent indentation for list items at the same level',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md005.md',+ tags: ['bullet', 'ul', 'indentation'],+ options: [],+ },+ {+ id: 'MD007',+ alias: 'ul-indent',+ aliases: ['ul-indent'],+ name: 'Unordered list indentation',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md007.md',+ tags: ['bullet', 'ul', 'indentation'],+ options: [+ { key: 'indent', type: 'integer', description: 'Spaces for indent', default: 2, minimum: 1 },+ {+ key: 'start_indented',+ type: 'boolean',+ description: 'Whether to indent the first level of the list',+ default: false,+ },+ {+ key: 'start_indent',+ type: 'integer',+ description: 'Spaces for first level indent (when start_indented is set)',+ default: 2,+ minimum: 1,+ },+ ],+ },+ {+ id: 'MD009',+ alias: 'no-trailing-spaces',+ aliases: ['no-trailing-spaces'],+ name: 'Trailing spaces',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md009.md',+ tags: ['whitespace'],+ options: [+ {+ key: 'br_spaces',+ type: 'integer',+ description: 'Spaces for line break',+ default: 2,+ minimum: 0,+ },+ { key: 'code_blocks', type: 'boolean', description: 'Include code blocks', default: false },+ {+ key: 'list_item_empty_lines',+ type: 'boolean',+ description: 'Allow spaces for empty lines in list items',+ default: false,+ },+ { key: 'strict', type: 'boolean', description: 'Include unnecessary breaks', default: false },+ ],+ },+ {+ id: 'MD010',+ alias: 'no-hard-tabs',+ aliases: ['no-hard-tabs'],+ name: 'Hard tabs',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md010.md',+ tags: ['whitespace', 'hard_tab'],+ options: [+ { key: 'code_blocks', type: 'boolean', description: 'Include code blocks', default: true },+ {+ key: 'ignore_code_languages',+ type: 'string-array',+ description: 'Fenced code languages to ignore',+ default: [],+ },+ {+ key: 'spaces_per_tab',+ type: 'integer',+ description: 'Number of spaces for each hard tab',+ default: 1,+ minimum: 0,+ },+ ],+ },+ {+ id: 'MD011',+ alias: 'no-reversed-links',+ aliases: ['no-reversed-links'],+ name: 'Reversed link syntax',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md011.md',+ tags: ['links'],+ options: [],+ },+ {+ id: 'MD012',+ alias: 'no-multiple-blanks',+ aliases: ['no-multiple-blanks'],+ name: 'Multiple consecutive blank lines',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md012.md',+ tags: ['whitespace', 'blank_lines'],+ options: [+ {+ key: 'maximum',+ type: 'integer',+ description: 'Consecutive blank lines',+ default: 1,+ minimum: 1,+ },+ ],+ },+ {+ id: 'MD013',+ alias: 'line-length',+ aliases: ['line-length'],+ name: 'Line length',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md013.md',+ tags: ['line_length'],+ options: [+ {+ key: 'line_length',+ type: 'integer',+ description: 'Number of characters',+ default: 80,+ minimum: 1,+ },+ {+ key: 'heading_line_length',+ type: 'integer',+ description: 'Number of characters for headings',+ default: 80,+ minimum: 1,+ },+ {+ key: 'code_block_line_length',+ type: 'integer',+ description: 'Number of characters for code blocks',+ default: 80,+ minimum: 1,+ },+ { key: 'code_blocks', type: 'boolean', description: 'Include code blocks', default: true },+ { key: 'tables', type: 'boolean', description: 'Include tables', default: true },+ { key: 'headings', type: 'boolean', description: 'Include headings', default: true },+ { key: 'strict', type: 'boolean', description: 'Strict length checking', default: false },+ { key: 'stern', type: 'boolean', description: 'Stern length checking', default: false },+ ],+ },+ {+ id: 'MD014',+ alias: 'commands-show-output',+ aliases: ['commands-show-output'],+ name: 'Dollar signs used before commands without showing output',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md014.md',+ tags: ['code'],+ options: [],+ },+ {+ id: 'MD018',+ alias: 'no-missing-space-atx',+ aliases: ['no-missing-space-atx'],+ name: 'No space after hash on atx style heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md018.md',+ tags: ['headings', 'atx', 'spaces'],+ options: [],+ },+ {+ id: 'MD019',+ alias: 'no-multiple-space-atx',+ aliases: ['no-multiple-space-atx'],+ name: 'Multiple spaces after hash on atx style heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md019.md',+ tags: ['headings', 'atx', 'spaces'],+ options: [],+ },+ {+ id: 'MD020',+ alias: 'no-missing-space-closed-atx',+ aliases: ['no-missing-space-closed-atx'],+ name: 'No space inside hashes on closed atx style heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md020.md',+ tags: ['headings', 'spaces', 'atx_closed'],+ options: [],+ },+ {+ id: 'MD021',+ alias: 'no-multiple-space-closed-atx',+ aliases: ['no-multiple-space-closed-atx'],+ name: 'Multiple spaces inside hashes on closed atx style heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md021.md',+ tags: ['headings', 'spaces', 'atx_closed'],+ options: [],+ },+ {+ id: 'MD022',+ alias: 'blanks-around-headings',+ aliases: ['blanks-around-headings'],+ name: 'Headings should be surrounded by blank lines',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md022.md',+ tags: ['headings', 'blank_lines'],+ options: [+ {+ key: 'include_front_matter',+ type: 'boolean',+ description: 'Include front matter content',+ default: false,+ },+ {+ key: 'lines_above',+ type: 'unsupported',+ description: 'Blank lines above heading',+ default: 1,+ },+ {+ key: 'lines_below',+ type: 'unsupported',+ description: 'Blank lines below heading',+ default: 1,+ },+ ],+ },+ {+ id: 'MD023',+ alias: 'heading-start-left',+ aliases: ['heading-start-left'],+ name: 'Headings must start at the beginning of the line',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md023.md',+ tags: ['headings', 'spaces'],+ options: [],+ },+ {+ id: 'MD024',+ alias: 'no-duplicate-heading',+ aliases: ['no-duplicate-heading'],+ name: 'Multiple headings with the same content',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md024.md',+ tags: ['headings'],+ options: [+ {+ key: 'siblings_only',+ type: 'boolean',+ description: 'Only check sibling headings',+ default: false,+ },+ ],+ },+ {+ id: 'MD025',+ alias: 'single-title',+ aliases: ['single-title', 'single-h1'],+ name: 'Multiple top-level headings in the same document',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md025.md',+ tags: ['headings'],+ options: [+ {+ key: 'front_matter_title',+ type: 'string',+ description: 'RegExp for matching title in front matter',+ default: '^\\s*title\\s*[:=]',+ },+ {+ key: 'level',+ type: 'integer',+ description: 'Heading level',+ default: 1,+ minimum: 1,+ maximum: 6,+ },+ ],+ },+ {+ id: 'MD026',+ alias: 'no-trailing-punctuation',+ aliases: ['no-trailing-punctuation'],+ name: 'Trailing punctuation in heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md026.md',+ tags: ['headings'],+ options: [+ {+ key: 'punctuation',+ type: 'string',+ description: 'Punctuation characters',+ default: '.,;:!。,;:!',+ },+ ],+ },+ {+ id: 'MD027',+ alias: 'no-multiple-space-blockquote',+ aliases: ['no-multiple-space-blockquote'],+ name: 'Multiple spaces after blockquote symbol',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md027.md',+ tags: ['indentation', 'whitespace', 'blockquote'],+ options: [+ { key: 'list_items', type: 'boolean', description: 'Include list items', default: true },+ ],+ },+ {+ id: 'MD028',+ alias: 'no-blanks-blockquote',+ aliases: ['no-blanks-blockquote'],+ name: 'Blank line inside blockquote',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md028.md',+ tags: ['whitespace', 'blockquote'],+ options: [],+ },+ {+ id: 'MD029',+ alias: 'ol-prefix',+ aliases: ['ol-prefix'],+ name: 'Ordered list item prefix',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md029.md',+ tags: ['ol'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'List style',+ enum: ['one', 'ordered', 'one_or_ordered', 'zero'],+ default: 'one_or_ordered',+ },+ ],+ },+ {+ id: 'MD030',+ alias: 'list-marker-space',+ aliases: ['list-marker-space'],+ name: 'Spaces after list markers',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md030.md',+ tags: ['ul', 'whitespace', 'ol'],+ options: [+ {+ key: 'ul_single',+ type: 'integer',+ description: 'Spaces for single-line unordered list items',+ default: 1,+ minimum: 1,+ },+ {+ key: 'ol_single',+ type: 'integer',+ description: 'Spaces for single-line ordered list items',+ default: 1,+ minimum: 1,+ },+ {+ key: 'ul_multi',+ type: 'integer',+ description: 'Spaces for multi-line unordered list items',+ default: 1,+ minimum: 1,+ },+ {+ key: 'ol_multi',+ type: 'integer',+ description: 'Spaces for multi-line ordered list items',+ default: 1,+ minimum: 1,+ },+ ],+ },+ {+ id: 'MD031',+ alias: 'blanks-around-fences',+ aliases: ['blanks-around-fences'],+ name: 'Fenced code blocks should be surrounded by blank lines',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md031.md',+ tags: ['blank_lines', 'code'],+ options: [+ { key: 'list_items', type: 'boolean', description: 'Include list items', default: true },+ ],+ },+ {+ id: 'MD032',+ alias: 'blanks-around-lists',+ aliases: ['blanks-around-lists'],+ name: 'Lists should be surrounded by blank lines',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md032.md',+ tags: ['bullet', 'ul', 'blank_lines', 'ol'],+ options: [],+ },+ {+ id: 'MD033',+ alias: 'no-inline-html',+ aliases: ['no-inline-html'],+ name: 'Inline HTML',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md033.md',+ tags: ['html'],+ options: [+ {+ key: 'allowed_elements',+ type: 'string-array',+ description: 'Allowed elements',+ default: [],+ },+ {+ key: 'table_allowed_elements',+ type: 'string-array',+ description: 'Allowed elements in tables',+ default: [],+ },+ ],+ },+ {+ id: 'MD034',+ alias: 'no-bare-urls',+ aliases: ['no-bare-urls'],+ name: 'Bare URL used',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md034.md',+ tags: ['links', 'url'],+ options: [],+ },+ {+ id: 'MD035',+ alias: 'hr-style',+ aliases: ['hr-style'],+ name: 'Horizontal rule style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md035.md',+ tags: ['hr'],+ options: [+ { key: 'style', type: 'string', description: 'Horizontal rule style', default: 'consistent' },+ ],+ },+ {+ id: 'MD036',+ alias: 'no-emphasis-as-heading',+ aliases: ['no-emphasis-as-heading'],+ name: 'Emphasis used instead of a heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md036.md',+ tags: ['headings', 'emphasis'],+ options: [+ {+ key: 'punctuation',+ type: 'string',+ description: 'Punctuation characters',+ default: '.,;:!?。,;:!?',+ },+ ],+ },+ {+ id: 'MD037',+ alias: 'no-space-in-emphasis',+ aliases: ['no-space-in-emphasis'],+ name: 'Spaces inside emphasis markers',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md037.md',+ tags: ['whitespace', 'emphasis'],+ options: [],+ },+ {+ id: 'MD038',+ alias: 'no-space-in-code',+ aliases: ['no-space-in-code'],+ name: 'Spaces inside code span elements',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md038.md',+ tags: ['whitespace', 'code'],+ options: [],+ },+ {+ id: 'MD039',+ alias: 'no-space-in-links',+ aliases: ['no-space-in-links'],+ name: 'Spaces inside link text',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md039.md',+ tags: ['whitespace', 'links'],+ options: [],+ },+ {+ id: 'MD040',+ alias: 'fenced-code-language',+ aliases: ['fenced-code-language'],+ name: 'Fenced code blocks should have a language specified',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md040.md',+ tags: ['code', 'language'],+ options: [+ {+ key: 'allowed_languages',+ type: 'string-array',+ description: 'List of languages',+ default: [],+ },+ {+ key: 'language_only',+ type: 'boolean',+ description: 'Require language only',+ default: false,+ },+ ],+ },+ {+ id: 'MD041',+ alias: 'first-line-heading',+ aliases: ['first-line-heading', 'first-line-h1'],+ name: 'First line in a file should be a top-level heading',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md041.md',+ tags: ['headings'],+ options: [+ {+ key: 'allow_preamble',+ type: 'boolean',+ description: 'Allow content before first heading',+ default: false,+ },+ {+ key: 'front_matter_title',+ type: 'string',+ description: 'RegExp for matching title in front matter',+ default: '^\\s*title\\s*[:=]',+ },+ {+ key: 'level',+ type: 'integer',+ description: 'Heading level',+ default: 1,+ minimum: 1,+ maximum: 6,+ },+ ],+ },+ {+ id: 'MD042',+ alias: 'no-empty-links',+ aliases: ['no-empty-links'],+ name: 'No empty links',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md042.md',+ tags: ['links'],+ options: [],+ },+ {+ id: 'MD043',+ alias: 'required-headings',+ aliases: ['required-headings'],+ name: 'Required heading structure',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md043.md',+ tags: ['headings'],+ options: [+ { key: 'headings', type: 'string-array', description: 'List of headings', default: [] },+ { key: 'match_case', type: 'boolean', description: 'Match case of headings', default: false },+ ],+ },+ {+ id: 'MD044',+ alias: 'proper-names',+ aliases: ['proper-names'],+ name: 'Proper names should have the correct capitalization',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md044.md',+ tags: ['spelling'],+ options: [+ { key: 'names', type: 'string-array', description: 'List of proper names', default: [] },+ { key: 'code_blocks', type: 'boolean', description: 'Include code blocks', default: true },+ {+ key: 'html_elements',+ type: 'boolean',+ description: 'Include HTML elements',+ default: true,+ },+ ],+ },+ {+ id: 'MD045',+ alias: 'no-alt-text',+ aliases: ['no-alt-text'],+ name: 'Images should have alternate text (alt text)',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md045.md',+ tags: ['accessibility', 'images'],+ options: [],+ },+ {+ id: 'MD046',+ alias: 'code-block-style',+ aliases: ['code-block-style'],+ name: 'Code block style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md046.md',+ tags: ['code'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Block style',+ enum: ['consistent', 'fenced', 'indented'],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD047',+ alias: 'single-trailing-newline',+ aliases: ['single-trailing-newline'],+ name: 'Files should end with a single newline character',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md047.md',+ tags: ['blank_lines'],+ options: [],+ },+ {+ id: 'MD048',+ alias: 'code-fence-style',+ aliases: ['code-fence-style'],+ name: 'Code fence style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md048.md',+ tags: ['code'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Code fence style',+ enum: ['consistent', 'backtick', 'tilde'],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD049',+ alias: 'emphasis-style',+ aliases: ['emphasis-style'],+ name: 'Emphasis style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md049.md',+ tags: ['emphasis'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Emphasis style',+ enum: ['consistent', 'asterisk', 'underscore'],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD050',+ alias: 'strong-style',+ aliases: ['strong-style'],+ name: 'Strong style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md050.md',+ tags: ['emphasis'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Strong style',+ enum: ['consistent', 'asterisk', 'underscore'],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD051',+ alias: 'link-fragments',+ aliases: ['link-fragments'],+ name: 'Link fragments should be valid',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md051.md',+ tags: ['links'],+ options: [+ {+ key: 'ignore_case',+ type: 'boolean',+ description: 'Ignore case of fragments',+ default: false,+ },+ {+ key: 'ignored_pattern',+ type: 'string',+ description: 'Pattern for ignoring additional fragments',+ default: '',+ },+ ],+ },+ {+ id: 'MD052',+ alias: 'reference-links-images',+ aliases: ['reference-links-images'],+ name: 'Reference links and images should use a label that is defined',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md052.md',+ tags: ['links', 'images'],+ options: [+ {+ key: 'ignored_labels',+ type: 'string-array',+ description: 'Ignored link labels',+ default: ['x'],+ },+ {+ key: 'shortcut_syntax',+ type: 'boolean',+ description: 'Include shortcut syntax',+ default: false,+ },+ ],+ },+ {+ id: 'MD053',+ alias: 'link-image-reference-definitions',+ aliases: ['link-image-reference-definitions'],+ name: 'Link and image reference definitions should be needed',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md053.md',+ tags: ['links', 'images'],+ options: [+ {+ key: 'ignored_definitions',+ type: 'string-array',+ description: 'Ignored definitions',+ default: ['//'],+ },+ ],+ },+ {+ id: 'MD054',+ alias: 'link-image-style',+ aliases: ['link-image-style'],+ name: 'Link and image style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md054.md',+ tags: ['links', 'images'],+ options: [+ { key: 'autolink', type: 'boolean', description: 'Allow autolinks', default: true },+ {+ key: 'inline',+ type: 'boolean',+ description: 'Allow inline links and images',+ default: true,+ },+ {+ key: 'full',+ type: 'boolean',+ description: 'Allow full reference links and images',+ default: true,+ },+ {+ key: 'collapsed',+ type: 'boolean',+ description: 'Allow collapsed reference links and images',+ default: true,+ },+ {+ key: 'shortcut',+ type: 'boolean',+ description: 'Allow shortcut reference links and images',+ default: true,+ },+ {+ key: 'url_inline',+ type: 'boolean',+ description: 'Allow URLs as inline links',+ default: true,+ },+ ],+ },+ {+ id: 'MD055',+ alias: 'table-pipe-style',+ aliases: ['table-pipe-style'],+ name: 'Table pipe style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md055.md',+ tags: ['table'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Table pipe style',+ enum: [+ 'consistent',+ 'leading_only',+ 'trailing_only',+ 'leading_and_trailing',+ 'no_leading_or_trailing',+ ],+ default: 'consistent',+ },+ ],+ },+ {+ id: 'MD056',+ alias: 'table-column-count',+ aliases: ['table-column-count'],+ name: 'Table column count',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md056.md',+ tags: ['table'],+ options: [],+ },+ {+ id: 'MD058',+ alias: 'blanks-around-tables',+ aliases: ['blanks-around-tables'],+ name: 'Tables should be surrounded by blank lines',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md058.md',+ tags: ['table'],+ options: [],+ },+ {+ id: 'MD059',+ alias: 'descriptive-link-text',+ aliases: ['descriptive-link-text'],+ name: 'Link text should be descriptive',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md059.md',+ tags: ['links', 'accessibility'],+ options: [+ {+ key: 'prohibited_texts',+ type: 'string-array',+ description: 'Prohibited link texts',+ default: ['click here', 'here', 'link', 'more'],+ },+ ],+ },+ {+ id: 'MD060',+ alias: 'table-column-style',+ aliases: ['table-column-style'],+ name: 'Table column style',+ docUrl: 'https://github.com/DavidAnson/markdownlint/blob/v0.41.0/doc/md060.md',+ tags: ['table'],+ options: [+ {+ key: 'style',+ type: 'enum',+ description: 'Table column style',+ enum: ['any', 'aligned', 'compact', 'tight'],+ default: 'any',+ },+ {+ key: 'aligned_delimiter',+ type: 'boolean',+ description: 'Aligned delimiter columns',+ default: false,+ },+ ],+ },+];diff --git a/packages/core/src/markdown/lint/text-edits.ts b/packages/core/src/markdown/lint/text-edits.tsnew file mode 100644index 000000000..002407d97--- /dev/null+++ b/packages/core/src/markdown/lint/text-edits.ts@@ -0,0 +1,38 @@+import type { LintPosition, LintTextEdit } from './types.ts';++export function applyTextEdits(text: string, edits: readonly LintTextEdit[]): string {+ if (edits.length === 0) return text;+ const lineStarts = computeLineStarts(text);+ const resolved = edits.map((edit) => ({+ start: offsetAt(text, lineStarts, edit.range.start),+ end: offsetAt(text, lineStarts, edit.range.end),+ newText: edit.newText,+ }));+ resolved.sort((a, b) => b.start - a.start || b.end - a.end);+ let out = text;+ for (const edit of resolved) {+ const start = Math.min(edit.start, edit.end);+ const end = Math.max(edit.start, edit.end);+ out = out.slice(0, start) + edit.newText + out.slice(end);+ }+ return out;+}++function computeLineStarts(text: string): number[] {+ const starts = [0];+ for (let i = 0; i < text.length; i++) {+ if (text[i] === '\n') starts.push(i + 1);+ }+ return starts;+}++function offsetAt(text: string, lineStarts: number[], position: LintPosition): number {+ if (position.line < 0) return 0;+ if (position.line >= lineStarts.length) return text.length;+ const lineStart = lineStarts[position.line] as number;+ const lineEnd =+ position.line + 1 < lineStarts.length+ ? (lineStarts[position.line + 1] as number) - 1 // before the '\n'+ : text.length;+ return Math.min(lineStart + Math.max(0, position.character), lineEnd);+}diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsnew file mode 100644index 000000000..617f6e5b9--- /dev/null+++ b/packages/core/src/markdown/lint/types.ts@@ -0,0 +1,72 @@+export const LINT_PLUGIN_IDS = ['markdownlint'] as const;+export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];++export type LintSeverity = 'error' | 'warning' | 'info' | 'hint';++export interface LintPosition {+ line: number;+ character: number;+}++export interface LintRange {+ start: LintPosition;+ end: LintPosition;+}++export interface LintTextEdit {+ range: LintRange;+ newText: string;+}++export interface LintDiagnostic {+ range: LintRange;+ severity: LintSeverity;+ source: LintPluginId;+ code: string;+ message: string;+ fixes?: LintTextEdit[];+}++type MarkdownlintRuleParams = Record<string, unknown>;++export const MARKDOWNLINT_RULE_SEVERITIES = ['error', 'warning'] as const;+export type MarkdownlintRuleSeverity = (typeof MARKDOWNLINT_RULE_SEVERITIES)[number];++export type MarkdownlintRuleWriteValue = boolean | MarkdownlintRuleParams;++export type MarkdownlintRuleSetting = MarkdownlintRuleWriteValue | MarkdownlintRuleSeverity;++export interface MarkdownlintSlice {+ enabled: boolean;+ rules: Record<string, MarkdownlintRuleSetting>;+}++interface RuleOptionSpecBase {+ key: string;+ description: string;+}++export type RuleOptionSpec =+ | (RuleOptionSpecBase & { type: 'boolean'; default?: boolean })+ | (RuleOptionSpecBase & {+ type: 'integer';+ default?: number;+ minimum?: number;+ maximum?: number;+ })+ | (RuleOptionSpecBase & { type: 'string'; default?: string })+ | (RuleOptionSpecBase & { type: 'enum'; enum: readonly string[]; default?: string })+ | (RuleOptionSpecBase & { type: 'string-array'; default?: readonly string[] })+ | (RuleOptionSpecBase & { type: 'unsupported'; default?: unknown });++export type RuleOptionType = RuleOptionSpec['type'];++export interface RuleCatalogEntry {+ id: string;+ alias: string;+ aliases: readonly string[];+ name: string;+ docUrl: string;+ tags: readonly string[];+ options: readonly RuleOptionSpec[];+}diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex bd79424c7..a5b511f25 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex f84967798..679c72ef7 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex df788a80d..8ce2b2492 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,4 +1,3 @@-import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 17ed2b829..1a897fca8 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 7e4a9a48b..9864b3b60 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,7 +168,6 @@ export function parseRecursive(}}-interface VFilePlace {offset?: number;start?: { offset?: number };@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}-interface Region {start: number;end: number;@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}-export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}-interface SourceBlock {src: string;start: number;@@ -456,7 +452,6 @@ function tryPerBlockFallback(};}-function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex 43d420187..e6ab4fd57 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,4 +1,3 @@-export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 5b9550e90..5d6db7aa8 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex f8f5e8530..5a5e4c42a 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,4 +1,3 @@-import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 860a7b360..51f600876 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,4 +1,3 @@-import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -470,8 +469,7 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- }- else if (first === '[') {+ } else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex ca225ce9b..db10fa54b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,4 +1,3 @@-import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 3a2524a9a..34068d103 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 2279a0189..93151d43b 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex a0f467c42..188f02d83 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4e8542a21..4ba2c3418 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex a3c96b24a..1a74b1272 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex e95cf43d6..de35e7b79 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex ffdb4d5b5..b4be1b2ea 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex e2a96d1a7..3c8d88b7c 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex 0389575ac..cf2c9da8e 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,4 +1,3 @@-import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 542204403..46cc6a074 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,4 +1,3 @@-import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex fe73659e6..be97d4d62 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,4 +1,3 @@-import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex b094885ec..052f4a9fd 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,4 +1,3 @@-import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex c5bfd2386..cd245c38c 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,4 +1,3 @@-import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex ac9f5239b..d578476a7 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,4 +1,3 @@-const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex afd9936fe..6dad26200 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {}}-const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {};}-function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};-const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 2159f6782..07ebc92c5 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -379,6 +379,12 @@ export const ProblemTypeSchema = z.enum(['urn:ok:error:handoff-target-not-installed','urn:ok:error:handoff-spawn-timeout','urn:ok:error:handoff-spawn-failed',+ // `POST /api/lint/markdownlint-config` refuses (409) to rewrite a native+ // markdownlint config that is an executable module (`.cjs`/`.mjs`). Distinct+ // from `invalid-request` (400 shape) so SDK consumers read it as a Conflict —+ // "change the resource (convert to JSON/JSONC/YAML) and retry" — not a+ // never-retry malformed request.+ 'urn:ok:error:config-not-writable',]) satisfies StandardSchemaV1;export type ProblemType = z.infer<typeof ProblemTypeSchema>;diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.tsindex 3bbd51128..d830e893c 100644--- a/packages/core/src/schemas/api/agent-write.ts+++ b/packages/core/src/schemas/api/agent-write.ts@@ -253,6 +253,31 @@ export const RenderWarningSchema = z.loose() satisfies StandardSchemaV1;export type RenderWarning = z.infer<typeof RenderWarningSchema>;+/**+ * A markdown-lint / content-rule violation on the post-write document. Strictly+ * advisory — the write always lands (storage never gates on rules). Emitted by+ * `handleAgentWriteMd` / `handleAgentPatch` against the doc's effective rule+ * config, capped server-side, so an agent writing a doc sees the same+ * violations the editor would show. `kind` is the discriminator; one write can+ * carry several violations.+ */+export const LintViolationWarningSchema = z+ .object({+ kind: z.literal('lint-violation'),+ /** Which plugin produced it — its registry id (e.g. `markdownlint`). */+ source: z.string(),+ /** The engine's native rule id, unprefixed (e.g. `MD010`). */+ code: z.string(),+ /** Human-readable, already-resolved message. */+ message: z.string(),+ severity: z.enum(['error', 'warning', 'info', 'hint']),+ /** 1-based line / column in the source document (agent-facing display units). */+ line: z.number().int().positive(),+ column: z.number().int().positive(),+ })+ .loose() satisfies StandardSchemaV1;+export type LintViolationWarning = z.infer<typeof LintViolationWarningSchema>;+/*** Unified advisory channel on mutating-write success bodies: every advisory* the write produced, discriminated by `kind`. Two families with different@@ -273,6 +298,7 @@ export const AdvisoryWarningSchema = z.discriminatedUnion('kind', [ContentDivergenceWarningSchema,DiskEditReconciledWarningSchema,RenderWarningSchema,+ LintViolationWarningSchema,]);export type AdvisoryWarning = z.infer<typeof AdvisoryWarningSchema>;diff --git a/packages/core/src/theme/theme-plugins.test.ts b/packages/core/src/theme/theme-plugins.test.tsnew file mode 100644index 000000000..9a8bb4532--- /dev/null+++ b/packages/core/src/theme/theme-plugins.test.ts@@ -0,0 +1,107 @@+import { describe, expect, test } from 'bun:test';+import {+ type ColorThemeBase,+ colorThemeMode,+ expandPalette,+ generateColorThemesCss,+ isDarkTheme,+ resolveThemePlugin,+ THEME_PLUGIN_IDS,+ THEME_PLUGINS,+} from './theme-plugins.ts';++// Themes without a static, fully-authored `base`: `default` (no overlay) and+// `custom` (built at runtime from the user seed).+const NON_STATIC = new Set(['default', 'custom']);++describe('THEME_PLUGINS registry', () => {+ test('default is first; default + custom are the system-kind (non-static) themes', () => {+ expect(THEME_PLUGINS[0]?.id).toBe('default');+ expect(THEME_PLUGINS[0]?.base).toBeUndefined();+ const systemThemes = THEME_PLUGINS.filter((t) => t.kind === 'system');+ expect(systemThemes.map((t) => t.id).sort()).toEqual(['custom', 'default']);+ });++ test('every static theme carries a full base palette + a toTokens behavior', () => {+ for (const theme of THEME_PLUGINS) {+ if (NON_STATIC.has(theme.id)) continue;+ // Every static built-in forces its own mode — dark or light.+ expect(['dark', 'light']).toContain(theme.kind);+ expect(theme.base).toBeDefined();+ // The descriptor owns its behavior (the analog of LintPlugin.lint).+ expect(typeof theme.toTokens).toBe('function');+ for (const [key, value] of Object.entries(theme.base as ColorThemeBase)) {+ expect(value, `${theme.id}.${key}`).toMatch(/^#[0-9a-f]{6}$/);+ }+ }+ });++ test('ids are unique', () => {+ const ids = THEME_PLUGINS.map((t) => t.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++describe('config enum derives from the registry', () => {+ // The headline of the plugin refactor: the `appearance.colorTheme` enum is+ // built from THEME_PLUGIN_IDS, which is built from the registry. Adding a+ // ThemePlugin grows the enum with no schema edit — the coupling the old+ // hand-listed enum carried is gone. (The schema-level cross-check that the+ // ConfigSchema enum equals these ids lives in the app's color-themes.test.ts.)+ test('THEME_PLUGIN_IDS is exactly the registry ids, in order', () => {+ expect([...THEME_PLUGIN_IDS]).toEqual(THEME_PLUGINS.map((t) => t.id));+ });+});++describe('resolveThemePlugin / isDarkTheme', () => {+ test('resolveThemePlugin falls back to default for unknown / missing ids', () => {+ expect(resolveThemePlugin(undefined).id).toBe('default');+ expect(resolveThemePlugin('not-a-theme').id).toBe('default');+ expect(resolveThemePlugin('dracula').id).toBe('dracula');+ });++ test('isDarkTheme is true for dark palettes, false for default and light palettes', () => {+ expect(isDarkTheme('default')).toBe(false);+ expect(isDarkTheme(undefined)).toBe(false);+ expect(isDarkTheme('catppuccin-frappe')).toBe(true);+ expect(isDarkTheme('catppuccin-latte')).toBe(false);+ });++ test('colorThemeMode forces a palette mode and defers for system themes', () => {+ expect(colorThemeMode('catppuccin-frappe')).toBe('dark');+ expect(colorThemeMode('catppuccin-latte')).toBe('light');+ // system-kind themes (default/custom) and unknown ids defer to appearance.theme.+ expect(colorThemeMode('default')).toBeUndefined();+ expect(colorThemeMode('custom')).toBeUndefined();+ expect(colorThemeMode(undefined)).toBeUndefined();+ });+});++describe('expandPalette + generateColorThemesCss', () => {+ test('expandPalette emits a representative slice of shadcn tokens', () => {+ const tokens = expandPalette(THEME_PLUGINS[1]?.base as ColorThemeBase);+ for (const required of [+ 'background',+ 'foreground',+ 'primary',+ 'muted-foreground',+ 'border',+ 'ring',+ 'sidebar',+ 'chart-1',+ 'syntax-keyword',+ ]) {+ expect(tokens[required], required).toBeTruthy();+ }+ });++ test('generated CSS emits one attribute rule per dark theme; none for default/custom', () => {+ const css = generateColorThemesCss();+ expect(css).not.toContain('data-color-theme="default"');+ expect(css).not.toContain('data-color-theme="custom"');+ for (const theme of THEME_PLUGINS) {+ if (NON_STATIC.has(theme.id)) continue;+ expect(css).toContain(`html[data-color-theme="${theme.id}"] {`);+ }+ });+});diff --git a/packages/core/src/theme/theme-plugins.ts b/packages/core/src/theme/theme-plugins.tsnew file mode 100644index 000000000..b2416777b--- /dev/null+++ b/packages/core/src/theme/theme-plugins.ts@@ -0,0 +1,335 @@+/**+ * IDE color-theme plugin registry — the single source of truth for the built-in+ * palettes the Settings → Preferences picker offers, and the source the+ * `appearance.colorTheme` config enum is DERIVED from (`THEME_PLUGIN_IDS`, see+ * `config/schema.ts`). Lives in `core` (not `app`) precisely so the config+ * schema can derive its enum from the registry — `core` can't import `app`.+ *+ * This mirrors the content-rules `LintPlugin<Id, Slice>` registry: each entry is+ * a self-describing descriptor (`ThemePlugin`) the host iterates, and a plugin's+ * behavior (`toTokens`) lives on the descriptor the way `lint()` lives on a+ * `LintPlugin`. Adding a built-in theme = append one descriptor here; the config+ * enum, the picker list, and the generated CSS all follow with no edit elsewhere.+ *+ * Each non-`default` built-in is a self-contained palette — `dark` or `light`:+ * selecting one layers its tokens via a `data-color-theme` attribute on `<html>`+ * and forces its own mode (dark or light) so Tailwind `dark:` variants stay+ * correct. `default` carries no palette (defers to the light/dark+ * `appearance.theme` mode); `custom` is built at runtime from the user's seed+ * (app-side; see `buildCustomThemeCss`).+ *+ * The CSS that applies the built-in palettes is GENERATED from this registry into+ * `packages/app/src/color-themes.generated.css`; the app's `color-themes.test.ts`+ * regenerates and fails on drift.+ */++/** A theme's authored base colors. `expandPalette` derives every shadcn token from these. */+export interface ColorThemeBase {+ /** Editor canvas background. */+ bg: string;+ /** Elevated surfaces (cards, popovers, hover states). Lighter than `bg`. */+ bgElevated: string;+ /** Chrome / sidebar background. Darker than `bg` for the "island" depth cue. */+ bgSubtle: string;+ /** Primary body text. */+ fg: string;+ /** Secondary / descriptive text. Must stay legible on `bg`. */+ fgMuted: string;+ /** Hairline borders + inputs. */+ border: string;+ /** Accent for buttons, links, focus ring. */+ primary: string;+ /** Text painted on top of `primary` — pick for contrast. */+ primaryFg: string;+ red: string;+ green: string;+ yellow: string;+ blue: string;+ cyan: string;+ orange: string;+ purple: string;+}++/**+ * A theme plugin descriptor — the theming analog of the content-rules+ * `LintPlugin`. The registry iterates these; consumers read behavior off the+ * descriptor rather than branching per-theme.+ */+export interface ThemePlugin<Id extends string = string> {+ /** Config value under `appearance.colorTheme`, and the picker tile key. */+ id: Id;+ /** Display name. A brand proper-noun (Dracula, Nord, …) — intentionally not translated. */+ label: string;+ /** `dark`/`light` palettes force that mode; `system` follows `appearance.theme`. */+ kind: 'dark' | 'light' | 'system';+ /** Authored colors. Absent on `default` (no palette) and `custom` (runtime seed). */+ base?: ColorThemeBase;+ /**+ * The plugin's behavior: derive the CSS token map this theme applies. Present+ * only on built-ins with a static `base` (the analog of `LintPlugin.lint`);+ * `default`/`custom` have none. The generated CSS calls this per descriptor.+ */+ toTokens?(): Record<string, string>;+}++const DRACULA: ColorThemeBase = {+ bg: '#282a36',+ bgElevated: '#343746',+ bgSubtle: '#21222c',+ fg: '#f8f8f2',+ fgMuted: '#9aa0c5',+ border: '#44475a',+ primary: '#bd93f9',+ primaryFg: '#282a36',+ red: '#ff5555',+ green: '#50fa7b',+ yellow: '#f1fa8c',+ blue: '#8be9fd',+ cyan: '#8be9fd',+ orange: '#ffb86c',+ purple: '#ff79c6',+};++// Catppuccin Frappé — the warm, mid-tone dark flavor. Mauve is the signature accent.+const CATPPUCCIN_FRAPPE: ColorThemeBase = {+ bg: '#303446', // base+ bgElevated: '#414559', // surface0+ bgSubtle: '#292c3c', // mantle+ fg: '#c6d0f5', // text+ fgMuted: '#a5adce', // subtext0+ border: '#51576d', // surface1+ primary: '#ca9ee6', // mauve+ primaryFg: '#303446', // base (reads on mauve)+ red: '#e78284',+ green: '#a6d189',+ yellow: '#e5c890',+ blue: '#8caaee',+ cyan: '#81c8be', // teal+ orange: '#ef9f76', // peach+ purple: '#ca9ee6', // mauve+};++// Catppuccin Latte — the light flavor. bgElevated is white so cards lift off the+// soft-gray canvas; bgSubtle is a touch darker for the sidebar "island" depth.+const CATPPUCCIN_LATTE: ColorThemeBase = {+ bg: '#eff1f5', // base+ bgElevated: '#ffffff', // white cards/popovers lift off the canvas+ bgSubtle: '#e6e9ef', // mantle (sidebar, slightly darker than base)+ fg: '#4c4f69', // text+ fgMuted: '#6c6f85', // subtext0+ border: '#ccd0da', // surface0+ primary: '#8839ef', // mauve+ primaryFg: '#ffffff', // white reads on mauve+ red: '#d20f39',+ green: '#40a02b',+ yellow: '#df8e1d',+ blue: '#1e66f5',+ cyan: '#179299', // teal+ orange: '#fe640b', // peach+ purple: '#8839ef', // mauve+};++const MONOKAI: ColorThemeBase = {+ bg: '#272822',+ bgElevated: '#31322b',+ bgSubtle: '#1e1f1a',+ fg: '#f8f8f2',+ fgMuted: '#a6a28c',+ border: '#49483e',+ primary: '#66d9ef',+ primaryFg: '#272822',+ red: '#f92672',+ green: '#a6e22e',+ yellow: '#e6db74',+ blue: '#66d9ef',+ cyan: '#66d9ef',+ orange: '#fd971f',+ purple: '#ae81ff',+};++const GRUVBOX: ColorThemeBase = {+ bg: '#282828',+ bgElevated: '#32302f',+ bgSubtle: '#1d2021',+ fg: '#ebdbb2',+ fgMuted: '#a89984',+ border: '#3c3836',+ primary: '#83a598',+ primaryFg: '#1d2021',+ red: '#fb4934',+ green: '#b8bb26',+ yellow: '#fabd2f',+ blue: '#83a598',+ cyan: '#8ec07c',+ orange: '#fe8019',+ purple: '#d3869b',+};++const SOLARIZED: ColorThemeBase = {+ bg: '#002b36',+ bgElevated: '#073642',+ bgSubtle: '#00252e',+ fg: '#93a1a1',+ fgMuted: '#6a7f86',+ border: '#0e4a56',+ primary: '#268bd2',+ primaryFg: '#fdf6e3',+ red: '#dc322f',+ green: '#859900',+ yellow: '#b58900',+ blue: '#268bd2',+ cyan: '#2aa198',+ orange: '#cb4b16',+ purple: '#6c71c4',+};++/**+ * Map a base palette to the full shadcn token set (token name → CSS value),+ * keyed without the leading `--`. Order is stable for deterministic CSS+ * generation. Alpha-derived tokens reference `var(--primary)` via relative+ * color syntax so they track the primary with no duplicated literal.+ */+export function expandPalette(b: ColorThemeBase): Record<string, string> {+ return {+ background: b.bg,+ foreground: b.fg,+ card: b.bgElevated,+ 'card-foreground': b.fg,+ popover: b.bgElevated,+ 'popover-foreground': b.fg,+ primary: b.primary,+ 'primary-foreground': b.primaryFg,+ secondary: b.bgElevated,+ 'secondary-foreground': b.fg,+ muted: b.bgElevated,+ 'muted-foreground': b.fgMuted,+ accent: b.bgElevated,+ 'accent-foreground': b.fg,+ destructive: b.red,+ border: b.border,+ input: b.border,+ ring: b.primary,+ 'selection-soft': 'oklch(from var(--primary) l c h / 0.3)',+ 'chart-1': b.primary,+ 'chart-2': b.green,+ 'chart-3': b.yellow,+ 'chart-4': b.purple,+ 'chart-5': b.red,+ sidebar: b.bgSubtle,+ 'sidebar-foreground': b.fg,+ 'sidebar-primary': b.primary,+ 'sidebar-primary-foreground': b.primaryFg,+ 'sidebar-accent': 'oklch(from var(--primary) l c h / 0.14)',+ 'sidebar-accent-foreground': b.primary,+ 'sidebar-hover': b.bgElevated,+ 'sidebar-border': b.border,+ 'sidebar-ring': b.primary,+ 'syntax-keyword': b.purple,+ 'syntax-tag': b.red,+ 'syntax-attr': b.blue,+ 'syntax-string': b.green,+ 'syntax-number': b.orange,+ 'syntax-atom': b.cyan,+ };+}++/** Build a `dark` built-in descriptor whose `toTokens` derives from its palette. */+function darkTheme<const Id extends string>(+ id: Id,+ label: string,+ base: ColorThemeBase,+): ThemePlugin<Id> {+ return { id, label, kind: 'dark', base, toTokens: () => expandPalette(base) };+}++/** Build a `light` built-in descriptor whose `toTokens` derives from its palette. */+function lightTheme<const Id extends string>(+ id: Id,+ label: string,+ base: ColorThemeBase,+): ThemePlugin<Id> {+ return { id, label, kind: 'light', base, toTokens: () => expandPalette(base) };+}++/** Build a `system`-kind descriptor (no static palette): `default` and `custom`. */+function systemTheme<const Id extends string>(id: Id, label: string): ThemePlugin<Id> {+ return { id, label, kind: 'system' };+}++/**+ * The built-in theme registry, in display + execution order. `default` first so+ * it anchors the picker grid. Order here drives both the Settings tile order and+ * the generated CSS order.+ */+export const THEME_PLUGINS = [+ systemTheme('default', 'Default'),+ darkTheme('dracula', 'Dracula', DRACULA),+ darkTheme('catppuccin-frappe', 'Catppuccin Frappé', CATPPUCCIN_FRAPPE),+ lightTheme('catppuccin-latte', 'Catppuccin Latte', CATPPUCCIN_LATTE),+ darkTheme('monokai', 'Monokai', MONOKAI),+ darkTheme('gruvbox', 'Gruvbox', GRUVBOX),+ darkTheme('solarized', 'Solarized', SOLARIZED),+ // `custom` carries no static `base`: its palette is built at runtime from the+ // user's `appearance.customTheme` seed (app-side `buildCustomThemeCss`). `kind`+ // is a placeholder — the real light/dark mode is derived per-seed. Excluded+ // from the generated CSS (no `toTokens`).+ systemTheme('custom', 'Custom'),+] as const;++/** A built-in theme's config id. DERIVED from the registry — the union of every entry's `id`. */+export type ThemePluginId = (typeof THEME_PLUGINS)[number]['id'];++/**+ * The theme ids as a non-empty tuple, DERIVED from the registry, for `z.enum` in+ * `config/schema.ts`. This is what makes `appearance.colorTheme` follow the+ * registry: add a `ThemePlugin` and the config enum grows with no schema edit+ * (the coupling the old hand-listed enum carried). The cast supplies the tuple+ * shape `z.enum` needs; the literal members come from the registry.+ */+export const THEME_PLUGIN_IDS = THEME_PLUGINS.map((t) => t.id) as [+ ThemePluginId,+ ...ThemePluginId[],+];++const THEME_PLUGIN_BY_ID = new Map<string, ThemePlugin>(THEME_PLUGINS.map((t) => [t.id, t]));++/** Resolve a raw config value to a known theme, falling back to `default`. */+export function resolveThemePlugin(id: string | undefined): ThemePlugin {+ return (id && THEME_PLUGIN_BY_ID.get(id)) || THEME_PLUGINS[0];+}++/** True for every theme whose palette forces dark mode. */+export function isDarkTheme(id: string | undefined): boolean {+ return resolveThemePlugin(id).kind === 'dark';+}++/**+ * The light/dark mode a palette theme forces, or `undefined` for a `system`-kind+ * theme (`default`/`custom`) that defers to `appearance.theme`. This is what lets+ * a light built-in force light mode instead of merely "not dark".+ */+export function colorThemeMode(id: string | undefined): 'light' | 'dark' | undefined {+ const kind = resolveThemePlugin(id).kind;+ return kind === 'system' ? undefined : kind;+}++/**+ * Render the generated stylesheet that applies every built-in palette. One rule+ * per dark theme, selected by `html[data-color-theme="<id>"]`. The attribute+ * selector out-specifies the base `:root` / `.dark` blocks, so a single block+ * per theme overrides both regardless of source order. `color-scheme` (the+ * theme's own kind) keeps native scrollbars / form controls correct even before+ * the `.dark` class settles on first paint. The descriptor's own `toTokens`+ * produces the tokens.+ */+export function generateColorThemesCss(): string {+ const header =+ '/* GENERATED by `bun run gen:color-themes` from src/lib/color-themes.ts — do not edit by hand. */\n';+ const blocks = THEME_PLUGINS.filter((t) => t.toTokens).map((theme) => {+ const tokens = (theme.toTokens as () => Record<string, string>)();+ const lines = Object.entries(tokens).map(([name, value]) => ` --${name}: ${value};`);+ const colorScheme = theme.kind === 'light' ? 'light' : 'dark';+ return `html[data-color-theme="${theme.id}"] {\n color-scheme: ${colorScheme};\n${lines.join('\n')}\n}`;+ });+ return `${header}\n${blocks.join('\n\n')}\n`;+}diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex c5716f084..a38673079 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -1,6 +1,6 @@---name: open-knowledge-description: "Authoritative agent-runtime contract for working inside an OpenKnowledge project — a markdown-CRDT knowledge base exposed over MCP. Use whenever reading, listing, searching, or editing any `.md` or `.mdx` file in the project, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, and the rest). Installed by `ok init`, so its presence means this is an OpenKnowledge project and it governs every markdown file here. Covers the read/write tool surface, grounding and linking rules, folder/template conventions, the live browser preview, and the rule that OK's MCP tools — never native file tools — handle in-scope markdown."+description: "Authoritative agent-runtime contract for working inside an OpenKnowledge project — a markdown-CRDT knowledge base exposed over MCP. Use whenever reading, listing, searching, editing, or linting any `.md` or `.mdx` file in the project, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, `lint`, and the rest). Installed by `ok init`, so its presence means this is an OpenKnowledge project and it governs every markdown file here. Covers the read/write tool surface, grounding and linking rules, folder/template conventions, the live browser preview, and the rule that OK's MCP tools — never native file tools — handle in-scope markdown."compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires OpenKnowledge MCP server + code execution."metadata:version: "0.31.0"@@ -24,9 +24,9 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th5. **Direct questions:** a plain business question ("which customers…", "what did we decide about…") routes to `search` / `exec` + a cited chat answer — no "research" keyword needed. Persist only when durable + multi-doc + not already covered, and *offer* first. See `references/corpus-qa.md`.6. **Authoring or improving a skill** ("write/make a skill", "improve this skill", "turn this into a skill"): STOP and invoke the **`open-knowledge-write-skill`** skill — it owns scope choice (project vs global), the SKILL.md contract, evaluation, and install; don't improvise from this skill. Author through the `skill` target (`write({ skill })`), never a raw `.ok/skills/…` document. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.pi/skills/` · `.agents/skills/`** — `install` generates them and overwrites them on the next sync; they are NOT source of truth.-## Tool index — 19 tools (router; the MCP tool descriptions carry each tool's full contract)+## Tool index — 20 tools (router; the MCP tool descriptions carry each tool's full contract)-- **Reads** — `exec` (primary; read-only `cat`/`ls`/`grep`/`find`/`head`/`tail`/`wc`/`sort`/`uniq`/`cut` + frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (versions for a doc), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for a one-call audit), `skills` (find + read skills: omit `name` to LIST every skill across Project + Global, pass `name` to READ one — addressed by `name`+`scope`, NEVER by path), `config` (resolved config), `palette` (markdown-native authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors when no GitHub remote).+- **Reads** — `exec` (primary; read-only `cat`/`ls`/`grep`/`find`/`head`/`tail`/`wc`/`sort`/`uniq`/`cut` + frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (versions for a doc), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for a one-call audit), `skills` (find + read skills: omit `name` to LIST every skill across Project + Global, pass `name` to READ one — addressed by `name`+`scope`, NEVER by path), `config` (resolved config), `palette` (markdown-native authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors when no GitHub remote), `lint` (content-rule / markdown-lint violations: pass `document` for one doc, or omit to audit the whole project — each violation carries `source`/`code` (flat id `source/code`) + `message` + `range` + `severity`; pass `fix: true` with `document` to auto-fix fixable rules in place — attributed and live in the preview, not a shell edit; the rest need `edit`/`write`).- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: { name, description, body, scope? } })` authors a skill → `.ok/skills/<name>/SKILL.md`, a **Draft** until `install`), `edit` (body find/replace OR frontmatter merge-patch; no asset), `delete` (remove), `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` to move Project↔Global — history resets, re-`install`). Output mirrors the input target key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (the Draft → Installed step for a `skill` — projects it into your editors; run after `write({ skill })`), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with. **Authoring/improving a skill? invoke `open-knowledge-write-skill` (TL;DR #6), don't improvise.**- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution + commit; destructive). See `references/conflict-resolution.md`.- **Workflow** — `workflow` (`kind: ingest|research|consolidate|discover`; procedural guides, not data). See `references/workflow-guides.md`.diff --git a/packages/server/package.json b/packages/server/package.jsonindex 92445f986..e66e3758f 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -40,6 +40,7 @@"happy-dom": "^20.10.2","ignore": "^5.3.2","ipaddr.js": "^2.3.0",+ "jsonc-parser": "^3.3.1","just-bash": "^2.14.3","mermaid": "^11.14.0","mrmime": "^2.0.1",diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 9f96dd825..5b4df8aaa 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -65,6 +65,7 @@ import {createWorkspaceSearchDocument,DEFAULT_ATTACHMENT_FOLDER_PATH,DEFAULT_DEDUP_MODE,+ DEFAULT_LINTER_CONFIG,DeadLinksSuccessSchema,DeletePathRequestSchema,DeletePathSuccessSchema,@@ -104,6 +105,13 @@ import {LinkGraphSuccessSchema,LinkPreviewRequestSchema,LinkPreviewResponseSchema,+ LintAuditResponseSchema,+ LintConfigResponseSchema,+ LintDocResultSchema,+ type LinterConfig,+ LintFixRequestSchema,+ LintFixResultSchema,+ type LintViolationWarning,LocalOpAuthEmptySuccessSchema,type LocalOpAuthHostRequest,LocalOpAuthHostRequestSchema,@@ -115,8 +123,10 @@ import {LocalOpEmbeddingsSetKeyRequestSchema,LocalOpOkInitRequestSchema,LocalOpOkInitResponseSchema,+ lintDocument,MANAGED_ARTIFACT_PREFIX_SKILL,MANAGED_ARTIFACT_PREFIX_TEMPLATE,+ MarkdownlintRuleWriteRequestSchema,MetricsAgentPresenceSuccessSchema,MetricsParseHealthSuccessSchema,MetricsReconciliationSuccessSchema,@@ -316,6 +326,13 @@ import {recordSkillInstall,removeSkillInstall,} from './installed-skills-marker.ts';+import { auditProject, lintAndFixSource, lintDoc } from './lint/audit.ts';+import { type WriteMarkdownlintResult, writeMarkdownlintRule } from './lint/markdownlint-write.ts';+import {+ composeEffectiveLinterConfig,+ resolveEffectiveLinterConfig,+ resolveNativeConfigForDoc,+} from './lint/resolve-config.ts';import { validateMermaidFences } from './mermaid-validator.ts';import {extractPageIcon,@@ -2144,12 +2161,21 @@ function classifyDuplicatePathFilesystemProblem(}function docNameExistsWithAnySupportedExtension(contentDir: string, docName: string): boolean {+ return resolveDocFilePath(contentDir, docName) !== null;+}++/**+ * Resolve a docName — extension-carrying or extension-less — to its on-disk+ * contentDir-relative path, or null when no supported file exists.+ */+function resolveDocFilePath(contentDir: string, docName: string): string | null {if (isSupportedDocFile(docName)) {- return existsSync(resolve(contentDir, docName));+ return existsSync(resolve(contentDir, docName)) ? docName : null;}- return SUPPORTED_DOC_EXTENSIONS.some((ext) =>- existsSync(resolve(contentDir, `${docName}${ext}`)),- );+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {+ if (existsSync(resolve(contentDir, `${docName}${ext}`))) return `${docName}${ext}`;+ }+ return null;}function hasSameStemDocumentSibling(contentDir: string, relPath: string): boolean {@@ -2774,6 +2800,13 @@ export interface ApiExtensionOptions {* the real path when omitted.*/embeddingsSecretsFile?: string;+ /**+ * Resolve the project's base `contentRules` config (project scope), read FRESH+ * per request so a config edit takes effect without a restart. The lint+ * endpoints inject the native `.markdownlint.*` rules over this base.+ * Omitted in tests → falls back to `DEFAULT_LINTER_CONFIG`.+ */+ getLinterBaseConfig?: () => LinterConfig;}interface WorkspaceSearchCacheEntry {@@ -2890,6 +2923,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {semanticSearch,getSemanticSimilarityFloor,embeddingsSecretsFile,+ getLinterBaseConfig,ephemeral = false,linkPreviewFetch,getLinkPreviewsEnabled,@@ -5356,6 +5390,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),...(writeMdWarning ? [writeMdWarning] : []),...(renderWarnings ?? []),+ ...(await computeLintViolations(+ session.dc.document.getText('source').toString(),+ resolvedDocName,+ )),];successResponse(res,@@ -7149,6 +7187,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {...(patchDivergenceEntry ? [patchDivergenceEntry] : []),...(patchWarning ? [patchWarning] : []),...(renderWarnings ?? []),+ ...(await computeLintViolations(+ session.dc.document.getText('source').toString(),+ docName,+ )),];successResponse(res,@@ -17483,6 +17525,423 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'semantic-status', method: 'GET', skipBodyParse: true },);+ // ---- Markdown linter: effective config + per-doc lint + project audit ----+ // The editor reads the effective config; the Settings GUI writes native+ // `.markdownlint.*` rules through the markdownlint-config endpoint.++ // Content-rule violations on a post-write document, for the agent write/edit+ // advisory channel. Every enabled lint source rides along — markdownlint+ // included — so agents see the same violations the editor GUI surfaces.+ // Whole-doc semantics: pre-existing violations reappear on every write to+ // the doc, which is why the cap matters. Capped; advisory only — never+ // gates the write. Empty when linting is disabled.+ const LINT_VIOLATION_CAP = 10;+ async function computeLintViolations(+ source: string,+ docName: string,+ ): Promise<LintViolationWarning[]> {+ const base = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ // Advisory-only means advisory-only: by the time this runs the write has+ // already committed (CRDT + disk + snapshot), so a lint engine crash must+ // degrade to zero advisories — never bubble into the handler's catch and+ // turn a committed write into a 500 the agent would retry.+ try {+ const effective = resolveEffectiveLinterConfig(contentDir, base, {+ docName,+ onProblem: (problem) => log.warn({ problem, docName }, '[lint] native config problem'),+ });+ return (await lintDocument(source, effective, docName))+ .slice(0, LINT_VIOLATION_CAP)+ .map((d) => ({+ kind: 'lint-violation' as const,+ source: d.source,+ code: d.code,+ message: d.message,+ severity: d.severity,+ // Advisory display units are 1-based; the diagnostic range is 0-based LSP.+ line: d.range.start.line + 1,+ column: d.range.start.character + 1,+ }));+ } catch (err) {+ log.warn(+ { err, docName },+ '[lint] advisory lint pass failed post-write; omitting advisories',+ );+ return [];+ }+ }++ const handleGetLintConfig = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ // A `?doc=` is accepted (the editor passes the active doc) but the+ // effective config resolves per doc (cli2 cascade: nearest native+ // file on the doc→root walk governs); no `?doc=` → root-level.+ const url = new URL(req.url ?? '', 'http://localhost');+ const docName = url.searchParams.get('doc');+ if (docName !== null && (docName === '' || !isSafeDocName(docName))) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid doc.', {+ handler: 'lint-config',+ });+ return;+ }+ const base = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const configProblems: string[] = [];+ const native = resolveNativeConfigForDoc(contentDir, docName ?? undefined, (problem) =>+ configProblems.push(problem),+ );+ const effective = composeEffectiveLinterConfig(base, native);+ successResponse(+ res,+ 200,+ LintConfigResponseSchema,+ { effective, configFile: native?.file ?? null, configProblems },+ { handler: 'lint-config' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to resolve lint config.',+ {+ handler: 'lint-config',+ cause: e,+ },+ );+ }+ },+ { handler: 'lint-config', method: 'GET', skipBodyParse: true },+ );++ // Edit one rule in the project's native `.markdownlint.*` file (the source of+ // truth). Root-level only for now; returns the recomputed effective config+ // so the settings panel reflects the change.+ const handleWriteMarkdownlintRule = withValidation(+ MarkdownlintRuleWriteRequestSchema,+ async (_req, res, body) => {+ let writeResult: WriteMarkdownlintResult;+ try {+ writeResult = writeMarkdownlintRule(resolve(contentDir), body.ruleId, body.value);+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to write markdownlint config.',+ { handler: 'markdownlint-config', cause: e },+ );+ return;+ }+ // A declined write must not read as success: the settings panel would+ // reload, show the rule silently reverted, and the user would retry.+ if (writeResult.action === 'declined-executable') {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:config-not-writable',+ `The native markdownlint config (${writeResult.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,+ { handler: 'markdownlint-config' },+ );+ return;+ }+ // Past this point the rule IS on disk — a re-read failure must not+ // report the write itself as failed.+ try {+ const base = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const configProblems: string[] = [];+ const native = resolveNativeConfigForDoc(contentDir, undefined, (problem) =>+ configProblems.push(problem),+ );+ const effective = composeEffectiveLinterConfig(base, native);+ successResponse(+ res,+ 200,+ LintConfigResponseSchema,+ { effective, configFile: native?.file ?? null, configProblems },+ { handler: 'markdownlint-config' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'The markdownlint rule was saved, but the effective config could not be re-read.',+ { handler: 'markdownlint-config', cause: e },+ );+ }+ },+ { handler: 'markdownlint-config', method: 'POST' },+ );++ const handleLintDoc = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const docName = url.searchParams.get('doc') ?? '';+ if (docName === '' || !isSafeDocName(docName)) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Missing or invalid doc.', {+ handler: 'lint',+ });+ return;+ }+ const docRelPath = resolveDocFilePath(contentDir, docName);+ if (docRelPath === null) {+ errorResponse(res, 404, 'urn:ok:error:doc-not-found', 'Document not found.', {+ handler: 'lint',+ });+ return;+ }+ const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const result = await lintDoc({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig,+ docRelPath,+ });+ successResponse(res, 200, LintDocResultSchema, result, { handler: 'lint' });+ } catch (e) {+ if (e instanceof SymlinkEscapeError) {+ errorResponse(res, 400, 'urn:ok:error:path-escape', 'Path escape detected.', {+ handler: 'lint',+ });+ return;+ }+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to lint document.', {+ handler: 'lint',+ cause: e,+ });+ }+ },+ { handler: 'lint', method: 'GET', skipBodyParse: true },+ );++ const handleLintAudit = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const rawTarget = url.searchParams.get('path');+ const target = rawTarget === null || rawTarget === '' ? undefined : rawTarget;+ // Absolute paths and traversal must not reach the walker: an audit+ // response carries offending-text snippets, so an unchecked scope is+ // an arbitrary-directory read for any connected agent.+ if (target !== undefined && !isValidRelativeContentPath(target)) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid path.', {+ handler: 'lint-audit',+ });+ return;+ }+ const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const result = await auditProject({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig,+ targetPath: target,+ });+ successResponse(res, 200, LintAuditResponseSchema, result, { handler: 'lint-audit' });+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to audit project.', {+ handler: 'lint-audit',+ cause: e,+ });+ }+ },+ { handler: 'lint-audit', method: 'GET', skipBodyParse: true },+ );++ const handleLintFix = withValidation(+ LintFixRequestSchema,+ async (_req, res, body) => {+ try {+ const effectiveDocName = requireNonEmptyDocName(body.docName, res, 'lint-fix');+ if (effectiveDocName === null) return;+ const resolvedDocName = resolveAlias(effectiveDocName);++ const { agentId, agentName, colorSeed, clientName, clientVersion, label } =+ extractAgentIdentity(body);++ if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:reserved-doc-name',+ `'${resolvedDocName}' is a reserved document name.`,+ { handler: 'lint-fix' },+ );+ return;+ }++ const docRelPath = resolveDocFilePath(contentDir, resolvedDocName);+ if (docRelPath === null) {+ errorResponse(res, 404, 'urn:ok:error:doc-not-found', 'Document not found.', {+ handler: 'lint-fix',+ });+ return;+ }+ // Refuse a symlink whose canonical target escapes the content dir BEFORE+ // loading the session. The read path (lintDoc) guards via realpath; this+ // CRDT-load path must too — otherwise persistence silently drops the+ // escaped load and the endpoint returns a misleading 200 ("clean")+ // instead of a path-escape 400. Throws SymlinkEscapeError → 400 below.+ assertNoSymlinkEscape(resolve(contentDir, docRelPath), contentDir);++ const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const { stored: storedSummary } = summaryResponseFields(normalizeSummary(body.summary));+ const session = await sessionManager.getSession(resolvedDocName, agentId, {+ displayName: agentName,+ colorSeed,+ clientName,+ });++ // Lint + fix the LIVE CRDT source (not disk) so the fix ranges resolve+ // against the bytes we actually mutate. `fixDocument` delegates to+ // upstream markdownlint's `applyFixes` — we author no fix logic.+ const source = session.dc.document.getText('source').toString();+ const { cfg, before, fixed } = await lintAndFixSource({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig,+ docRelPath,+ source,+ });++ let after = before;+ let reLintWarning: string | undefined;+ if (fixed !== source) {+ // Land the fixed bytes through the sanctioned agent-write spine:+ // attributed to the calling agent (never the anonymous `file-system`+ // writer a shell `ok lint --fix` produces), item-preserving (`patch`),+ // conflict- and FM-gated, and bridged to WYSIWYG + the live preview.+ // The setPresence('writing')/touchMode('idle') pairing mirrors+ // `handleAgentWriteMd` so the fix flashes a live "writing" badge; the+ // try/finally shape is structurally enforced by agent-presence.test.ts.+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {+ displayName: agentName,+ icon,+ color,+ currentDoc: resolvedDocName,+ mode: 'writing',+ ts: Date.now(),+ });+ session.dc.document.transact(() => {+ applyAgentMarkdownWrite(+ session.dc.document,+ fixed,+ 'patch',+ options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }+ : undefined,+ );+ }, session.origin);++ recordContributor(+ resolvedDocName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,+ );+ } finally {+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');+ }++ const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'lint-fix');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'lint-fix');+ return;+ }+ flushDocToGit(resolvedDocName, 'lint-fix');++ // Remaining problems: re-lint the ACTUAL post-write source (bridge+ // normalization can shift bytes vs `fixed`), reusing the resolved cfg.+ // The write is already durable here (transacted + flushed to disk ++ // git); a re-lint exception (markdownlint's `lint()` can throw) must+ // NOT surface as a 500 that makes the caller believe the fix failed+ // and retry / take compensating actions on already-fixed content.+ // Fall back to the pre-fix diagnostics and report the re-lint failure+ // as a warning instead.+ try {+ after = await lintDocument(+ session.dc.document.getText('source').toString(),+ cfg,+ docRelPath,+ );+ } catch (relintErr) {+ reLintWarning = `Re-lint after fix failed: ${relintErr instanceof Error ? relintErr.message : String(relintErr)}`;+ log.warn(+ { err: relintErr, handler: 'lint-fix' },+ 'post-write re-lint failed; reporting pre-fix diagnostics',+ );+ after = before;+ }+ }++ const errorCount = after.filter((d) => d.severity === 'error').length;+ const warningCount = after.length - errorCount;+ // Net problems the auto-fix resolved (clamped — a fix never nets negative).+ const fixedCount = Math.max(0, before.length - after.length);++ successResponse(+ res,+ 200,+ LintFixResultSchema,+ {+ file: docRelPath,+ fixedCount,+ diagnostics: after,+ errorCount,+ warningCount,+ ...(reLintWarning ? { warning: reLintWarning } : {}),+ },+ { handler: 'lint-fix' },+ );+ } catch (e) {+ if (e instanceof SymlinkEscapeError) {+ errorResponse(res, 400, 'urn:ok:error:path-escape', 'Path escape detected.', {+ handler: 'lint-fix',+ });+ return;+ }+ if (e instanceof DocInConflictError) {+ respondDocInConflict(res, e, 'lint-fix');+ return;+ }+ if (e instanceof FrontmatterMalformedError) {+ respondFrontmatterMalformed(res, e, 'lint-fix');+ return;+ }+ if (e instanceof AgentSessionCapacityError) {+ errorResponse(+ res,+ 503,+ 'urn:ok:error:too-many-agent-sessions',+ 'Too many agent sessions.',+ { handler: 'lint-fix', cause: e, extraHeaders: { 'Retry-After': '10' } },+ );+ return;+ }+ log.error({ err: e }, '[lint-fix] handler failed');+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to fix document.', {+ handler: 'lint-fix',+ cause: e,+ });+ }+ },+ { handler: 'lint-fix', method: 'POST' },+ );+// ───────────────────── Link preview (external hover cards) ─────────────────// Fetches page metadata for an external link on the user's behalf, so it is// guarded on two independent axes: an anti-proxy gate decides WHO may ask, and@@ -17654,6 +18113,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {'/api/skill-targets': handleSkillTargets,'/api/search': handleSearch,'/api/semantic-status': handleSemanticStatus,+ '/api/lint/config': handleGetLintConfig,+ '/api/lint/markdownlint-config': handleWriteMarkdownlintRule,+ '/api/lint': handleLintDoc,+ '/api/lint/audit': handleLintAudit,+ '/api/lint/fix': handleLintFix,'/api/suggest-links': handleSuggestLinks,'/api/page-headings': handlePageHeadings,'/api/create-page': handleCreatePage,@@ -17728,6 +18192,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// loopback Host header. /api/workspace enforces this inline already.const MUTATING_ROUTES: ReadonlySet<string> = new Set(['/api/upload',+ '/api/lint/markdownlint-config',+ '/api/lint/fix','/api/create-page','/api/create-folder','/api/duplicate-path',diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex ac82a4066..f83ea9503 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -221,6 +221,23 @@ export {ROOT_GITIGNORE_TEMPLATE,writeRootGitignoreForNewRepo,} from './init-project.ts';+export {+ type DiscoveredMarkdownlintConfig,+ discoverMarkdownlintConfig,+ findNativeMarkdownlintFile,+ readOwnNativeRules,+ resolveNativeMarkdownlintConfig,+} from './lint/markdownlint-discovery.ts';+export {+ type WriteMarkdownlintResult,+ writeMarkdownlintRule,+} from './lint/markdownlint-write.ts';+export {+ composeEffectiveLinterConfig,+ type ResolveLinterConfigOptions,+ resolveEffectiveLinterConfig,+ resolveNativeConfigForDoc,+} from './lint/resolve-config.ts';export {createLiveDerivedIndexExtension,LIVE_DERIVED_INDEX_DEBOUNCE_MS,diff --git a/packages/server/src/lint/audit-symlink.test.ts b/packages/server/src/lint/audit-symlink.test.tsnew file mode 100644index 000000000..820eca219--- /dev/null+++ b/packages/server/src/lint/audit-symlink.test.ts@@ -0,0 +1,98 @@+/**+ * Symlink containment for the lint read path: symlinks resolving inside the+ * content dir are supported (realpath-based identity), escapes are refused —+ * lint diagnostics echo source text, so an escaped read is exfiltration.+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';+import { auditProject, lintDoc } from './audit.ts';++let root: string;+let outside: string;++const SECRET = 'TOP-SECRET-OUTSIDE-CONTENT';+// MD010 (hard tabs) is on by default; a doc with a tab produces a diagnostic.+const DOC_WITH_TAB = '# Title\n\n\tindented with a tab\n';++const base: LinterConfig = {+ ...DEFAULT_LINTER_CONFIG,+ plugins: { markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true } },+};++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-symlink-')));+ outside = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-outside-')));+ writeFileSync(join(outside, 'secret.md'), `# Secret\n\n\t${SECRET}\n`, 'utf-8');+});+afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ rmSync(outside, { recursive: true, force: true });+});++describe('lintDoc symlink containment', () => {+ test('refuses a symlink escaping the content dir', async () => {+ symlinkSync(join(outside, 'secret.md'), join(root, 'escape.md'));+ await expect(+ lintDoc({ projectDir: root, contentDir: root, baseConfig: base, docRelPath: 'escape.md' }),+ ).rejects.toThrow(/^symlink-escape: /);+ });++ test('lints a symlink resolving inside the content dir', async () => {+ writeFileSync(join(root, 'real.md'), DOC_WITH_TAB, 'utf-8');+ symlinkSync(join(root, 'real.md'), join(root, 'alias.md'));+ const result = await lintDoc({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ docRelPath: 'alias.md',+ });+ expect(result.file).toBe('alias.md');+ expect(result.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ });+});++describe('auditProject symlink containment', () => {+ test('a scope through an escaped symlinked dir warns and leaks no diagnostics', async () => {+ symlinkSync(outside, join(root, 'linked'));+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: 'linked',+ });+ expect(audit.files).toEqual([]);+ expect(audit.warnings).toEqual([expect.stringContaining('symlink-escape')]);+ expect(JSON.stringify(audit)).not.toContain(SECRET);+ });++ test('a scope targeting an escaping symlinked file warns and leaks no diagnostics', async () => {+ symlinkSync(join(outside, 'secret.md'), join(root, 'escape.md'));+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: 'escape.md',+ });+ expect(audit.files).toEqual([]);+ expect(audit.warnings).toEqual([expect.stringContaining('symlink-escape')]);+ expect(JSON.stringify(audit)).not.toContain(SECRET);+ });++ test('a scope through a symlinked dir resolving inside the content dir lints fine', async () => {+ mkdirSync(join(root, 'realdir'));+ writeFileSync(join(root, 'realdir', 'doc.md'), DOC_WITH_TAB, 'utf-8');+ symlinkSync(join(root, 'realdir'), join(root, 'aliasdir'));+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: 'aliasdir',+ });+ expect(audit.files.map((f) => f.file)).toEqual([join('aliasdir', 'doc.md')]);+ expect(audit.warnings).toEqual([]);+ });+});diff --git a/packages/server/src/lint/audit.test.ts b/packages/server/src/lint/audit.test.tsnew file mode 100644index 000000000..cf923fa55--- /dev/null+++ b/packages/server/src/lint/audit.test.ts@@ -0,0 +1,148 @@+/**+ * Unit tests for project-wide + single-doc lint against a real temp tree:+ * native-file config resolution, content-filter exclusion, and the+ * diagnostics-only audit payload.+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';+import { auditProject, lintDoc } from './audit.ts';++let root: string;++function write(rel: string, content: string): void {+ const abs = join(root, rel);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, content, 'utf-8');+}++// MD010 (hard tabs) is on by default; a doc with a tab produces a diagnostic.+const DOC_WITH_TAB = '# Title\n\n\tindented with a tab\n';+const CLEAN_DOC = '# Title\n\nClean paragraph.\n';++const base: LinterConfig = {+ ...DEFAULT_LINTER_CONFIG,+ plugins: { markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true } },+};++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-')));+});+afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe('lintDoc', () => {+ test('lints a single doc with the base config', async () => {+ write('a.md', DOC_WITH_TAB);+ const result = await lintDoc({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ docRelPath: 'a.md',+ });+ expect(result.file).toBe('a.md');+ expect(result.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ });++ test('honors the native .markdownlint.json (disables a rule)', async () => {+ // markdownlint rules are sourced from the project's own `.markdownlint.*`,+ // discovered server-side and injected into the effective config.+ write('sub/b.md', DOC_WITH_TAB);+ write('.markdownlint.json', JSON.stringify({ MD010: false }));+ const result = await lintDoc({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ docRelPath: 'sub/b.md',+ });+ expect(result.diagnostics.some((d) => d.code === 'MD010')).toBe(false);+ });+});++describe('auditProject', () => {+ test('includes only docs that have diagnostics, counts all files', async () => {+ write('dirty.md', DOC_WITH_TAB);+ write('clean.md', CLEAN_DOC);+ const audit = await auditProject({ projectDir: root, contentDir: root, baseConfig: base });+ expect(audit.fileCount).toBe(2);+ expect(audit.files.map((f) => f.file)).toEqual(['dirty.md']);+ expect(audit.warningCount).toBeGreaterThan(0);+ expect(audit.errorCount).toBe(0);+ });++ test('respects .okignore exclusions', async () => {+ write('keep.md', DOC_WITH_TAB);+ write('drafts/skip.md', DOC_WITH_TAB);+ write('.okignore', 'drafts/\n');+ const audit = await auditProject({ projectDir: root, contentDir: root, baseConfig: base });+ expect(audit.files.map((f) => f.file)).toEqual(['keep.md']);+ expect(audit.fileCount).toBe(1);+ });++ test('scopes to a sub-path when targetPath is a directory', async () => {+ write('top.md', DOC_WITH_TAB);+ write('sub/inner.md', DOC_WITH_TAB);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: 'sub',+ });+ expect(audit.files.map((f) => f.file)).toEqual(['sub/inner.md']);+ });++ test('scopes to a single file when targetPath is a file', async () => {+ write('top.md', DOC_WITH_TAB);+ write('sub/inner.md', DOC_WITH_TAB);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: 'top.md',+ });+ expect(audit.files.map((f) => f.file)).toEqual(['top.md']);+ expect(audit.fileCount).toBe(1);+ });++ test('refuses an absolute targetPath outside the content dir (arbitrary-read guard)', async () => {+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: '/etc',+ });+ expect(audit.files).toEqual([]);+ expect(audit.fileCount).toBe(0);+ expect(audit.warnings).toEqual([+ expect.stringContaining('refusing audit scope outside the content directory'),+ ]);+ });++ test('refuses a relative targetPath that escapes the content dir', async () => {+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: base,+ targetPath: '../outside',+ });+ expect(audit.files).toEqual([]);+ expect(audit.warnings).toEqual([+ expect.stringContaining('refusing audit scope outside the content directory'),+ ]);+ });++ test('returns nothing when linting is disabled', async () => {+ write('dirty.md', DOC_WITH_TAB);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: { ...base, enabled: false },+ });+ expect(audit.files).toEqual([]);+ expect(audit.warningCount).toBe(0);+ });+});diff --git a/packages/server/src/lint/audit.ts b/packages/server/src/lint/audit.tsnew file mode 100644index 000000000..c29e3938b--- /dev/null+++ b/packages/server/src/lint/audit.ts@@ -0,0 +1,223 @@+/**+ * Project-wide + single-doc lint, server-side. Walks the content directory+ * (honoring `.gitignore`/`.okignore` via `createContentFilter`), resolves the+ * effective config (project base + native `.markdownlint.*` rules), and lints+ * with the core engine. Backs the `/api/lint` + `/api/lint/audit` endpoints+ * (Settings audit button + MCP `lint` tool + write-response warnings).+ */++import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { isAbsolute, join, relative, resolve } from 'node:path';+import {+ fixDocument,+ type LintDiagnostic,+ type LinterConfig,+ lintDocument,+ SUPPORTED_DOC_EXTENSIONS,+} from '@inkeep/open-knowledge-core';+import { SymlinkEscapeError } from '../apply-managed-rename.ts';+import { createContentFilter } from '../content-filter.ts';+import { isWithinContentDir } from '../persistence.ts';+import { resolveEffectiveLinterConfig } from './resolve-config.ts';++export interface FileLintResult {+ /** Path relative to `contentDir`. */+ file: string;+ diagnostics: LintDiagnostic[];+}++export interface AuditResult {+ files: FileLintResult[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ warnings: string[];+}++export interface AuditOptions {+ projectDir: string;+ contentDir: string;+ baseConfig: LinterConfig;+}++/** Lint a single document (read from disk) with its per-doc effective config. */+export async function lintDoc(+ opts: AuditOptions & { docRelPath: string; onConfigProblem?: (problem: string) => void },+): Promise<FileLintResult> {+ const { contentDir, baseConfig, docRelPath, onConfigProblem } = opts;+ // Symlinks inside the content dir are supported (realpath-based identity),+ // but an escape must be refused before the read: lint diagnostics echo+ // source text, so linting an escaped symlink is an arbitrary-file read.+ const canonical = resolveCanonicalDocPath(join(contentDir, docRelPath), contentDir);+ const text = readFileSync(canonical, 'utf-8');+ const cfg = resolveEffectiveLinterConfig(contentDir, baseConfig, {+ docName: docRelPath,+ onProblem: onConfigProblem,+ });+ return { file: docRelPath, diagnostics: await lintDocument(text, cfg, docRelPath) };+}++/**+ * Lint + auto-fix a single document's LIVE source text (frontmatter + body).+ * The `/api/lint/fix` handler passes the in-memory CRDT source (not disk) and+ * lands `fixed` through the agent-write spine, so this stays a pure string+ * compute that shares the engine + per-doc config resolution with `lintDoc`.+ * `fixDocument` delegates to upstream markdownlint's `applyFixes` — we author no+ * fix logic. Returns `cfg` so the caller can re-lint the post-write source for+ * the remaining set without re-resolving config.+ */+export async function lintAndFixSource(+ opts: AuditOptions & {+ docRelPath: string;+ source: string;+ onConfigProblem?: (problem: string) => void;+ },+): Promise<{ cfg: LinterConfig; before: LintDiagnostic[]; fixed: string }> {+ const { contentDir, baseConfig, docRelPath, source, onConfigProblem } = opts;+ const cfg = resolveEffectiveLinterConfig(contentDir, baseConfig, {+ docName: docRelPath,+ onProblem: onConfigProblem,+ });+ const before = await lintDocument(source, cfg, docRelPath);+ const fixed = fixDocument(source, cfg);+ return { cfg, before, fixed };+}++/** Lint every in-scope `.md`/`.mdx` document under `contentDir` (or a sub-path). */+export async function auditProject(+ opts: AuditOptions & { targetPath?: string },+): Promise<AuditResult> {+ const { projectDir, contentDir, baseConfig, targetPath } = opts;+ const warnings: string[] = [];+ const filter = createContentFilter({ projectDir, contentDir });++ const docFiles: string[] = [];+ const scope = resolveScope(targetPath, contentDir);+ // Defense-in-depth behind the HTTP boundary's relative-path validation: a+ // scope that resolves outside contentDir is refused, never walked — audit+ // output quotes document text, so an escaped walk is an arbitrary read.+ // The refusal must be realpath-based, not just lexical: a symlinked scope+ // directory would otherwise be readdir'd, and although every file read+ // inside is refused, the per-file refusal warnings would enumerate the+ // external filenames. Refuse once, before walking, naming no entries.+ const scopeRel = relative(contentDir, scope.path);+ if (scopeRel.startsWith('..') || isAbsolute(scopeRel)) {+ warnings.push(`refusing audit scope outside the content directory: ${targetPath ?? ''}`);+ return { files: [], fileCount: 0, errorCount: 0, warningCount: 0, warnings };+ }+ try {+ if (!isWithinContentDir(realpathSync(scope.path), realpathSync(contentDir))) {+ warnings.push(`symlink-escape: audit scope resolves outside the content directory`);+ return { files: [], fileCount: 0, errorCount: 0, warningCount: 0, warnings };+ }+ } catch {+ // Scope path missing or unreadable: fall through — the walk/read reports it.+ }+ if (scope.kind === 'file') {+ docFiles.push(relative(contentDir, scope.path));+ } else {+ walk(scope.path);+ }++ function walk(absDir: string): void {+ let entries: import('node:fs').Dirent[];+ try {+ entries = readdirSync(absDir, { withFileTypes: true });+ } catch (e) {+ warnings.push(`could not read ${relative(contentDir, absDir) || '.'}: ${errMsg(e)}`);+ return;+ }+ for (const entry of entries) {+ const full = join(absDir, entry.name);+ const rel = relative(contentDir, full);+ if (entry.isDirectory()) {+ if (filter.isDirExcluded(rel)) continue;+ walk(full);+ } else if (entry.isFile()) {+ if (!isDocFile(entry.name)) continue;+ if (filter.isExcluded(rel)) continue;+ docFiles.push(rel);+ }+ }+ }++ docFiles.sort();++ const files: FileLintResult[] = [];+ let errorCount = 0;+ let warningCount = 0;+ // Config problems repeat for every doc a governing file covers — dedupe.+ const seenConfigProblems = new Set<string>();+ const onConfigProblem = (problem: string) => {+ if (seenConfigProblems.has(problem)) return;+ seenConfigProblems.add(problem);+ warnings.push(problem);+ };+ for (const rel of docFiles) {+ let result: FileLintResult;+ try {+ result = await lintDoc({+ projectDir,+ contentDir,+ baseConfig,+ docRelPath: rel,+ onConfigProblem,+ });+ } catch (e) {+ warnings.push(`could not lint ${rel}: ${errMsg(e)}`);+ continue;+ }+ for (const d of result.diagnostics) {+ if (d.severity === 'error') errorCount++;+ else warningCount++;+ }+ // Only include files that actually have diagnostics in the audit payload.+ if (result.diagnostics.length > 0) files.push(result);+ }++ return { files, fileCount: docFiles.length, errorCount, warningCount, warnings };+}++/**+ * Realpath-resolve a doc path and refuse it when the canonical location falls+ * outside the canonical content dir (comparing realpaths on both sides keeps+ * platform aliases like macOS `/var` → `/private/var` from false-positives).+ */+function resolveCanonicalDocPath(abs: string, contentDir: string): string {+ const canonicalContentDir = realpathSync(contentDir);+ let canonical: string;+ try {+ canonical = realpathSync(abs);+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === 'ELOOP') {+ throw new SymlinkEscapeError('symlink cycle in path');+ }+ throw e;+ }+ if (!isWithinContentDir(canonical, canonicalContentDir)) {+ throw new SymlinkEscapeError('path resolves outside content directory');+ }+ return canonical;+}++type Scope = { kind: 'dir' | 'file'; path: string };++function resolveScope(targetPath: string | undefined, contentDir: string): Scope {+ if (targetPath === undefined || targetPath === '') return { kind: 'dir', path: contentDir };+ const abs = isAbsolute(targetPath) ? targetPath : resolve(contentDir, targetPath);+ try {+ if (statSync(abs).isFile()) return { kind: 'file', path: abs };+ } catch {+ // treat as a directory; the walk warns if unreadable.+ }+ return { kind: 'dir', path: abs };+}++function isDocFile(name: string): boolean {+ const lower = name.toLowerCase();+ return SUPPORTED_DOC_EXTENSIONS.some((ext) => lower.endsWith(ext));+}++function errMsg(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}diff --git a/packages/server/src/lint/markdownlint-discovery.test.ts b/packages/server/src/lint/markdownlint-discovery.test.tsnew file mode 100644index 000000000..7bd484939--- /dev/null+++ b/packages/server/src/lint/markdownlint-discovery.test.ts@@ -0,0 +1,290 @@+/**+ * Unit tests for native markdownlint config discovery against a real temp dir:+ * the `.markdownlint.*` precedence chain, per-format parsing (JSON / JSONC /+ * YAML), loud handling of malformed files, `extends` chain flattening with+ * its guards (package refs, escapes, cycles), and the per-dir cascade+ * (markdownlint-cli2 semantics: nearest file governs wholesale).+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ discoverMarkdownlintConfig,+ readOwnNativeRules,+ resolveNativeMarkdownlintConfig,+} from './markdownlint-discovery.ts';++let dir: string;++function write(name: string, content: string): void {+ const abs = join(dir, name);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, content, 'utf-8');+}++beforeEach(() => {+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-mdl-discovery-')));+});+afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+});++describe('discoverMarkdownlintConfig', () => {+ test('returns null when no native file exists', () => {+ expect(discoverMarkdownlintConfig(dir)).toBeNull();+ });++ test('reads a .markdownlint.json file', () => {+ write(+ '.markdownlint.json',+ JSON.stringify({ MD013: false, MD033: { allowed_elements: ['br'] } }),+ );+ expect(discoverMarkdownlintConfig(dir)).toEqual({+ rules: { MD013: false, MD033: { allowed_elements: ['br'] } },+ file: '.markdownlint.json',+ problems: [],+ });+ });++ test('reads a .markdownlint.yaml file', () => {+ write('.markdownlint.yaml', 'MD013: false\nMD007:\n indent: 4\n');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false, MD007: { indent: 4 } });+ });++ test('strips comments from a .markdownlint.jsonc file', () => {+ write('.markdownlint.jsonc', '{\n // line height\n "MD013": false /* off */\n}\n');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false });+ });++ test('strips the `$schema` meta key (never reaches the rules object)', () => {+ write(+ '.markdownlint.json',+ JSON.stringify({+ $schema:+ 'https://raw.githubusercontent.com/DavidAnson/markdownlint/main/schema/.markdownlint.jsonc',+ MD013: false,+ }),+ );+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([]);+ });++ test('jsonc wins over json when both exist (precedence)', () => {+ write('.markdownlint.json', JSON.stringify({ MD013: true }));+ write('.markdownlint.jsonc', '{ "MD013": false }');+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.file).toBe('.markdownlint.jsonc');+ expect(found?.rules).toEqual({ MD013: false });+ });++ test('a malformed file yields rules null + a loud problem, not silence', () => {+ write('.markdownlint.json', '{ not valid json');+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toBeNull();+ expect(found?.problems).toEqual([expect.stringContaining('malformed markdownlint config')]);+ });++ test('a malformed-file problem carries the parser detail, not just the verdict', () => {+ write('.markdownlint.json', '{ not valid json');+ const found = discoverMarkdownlintConfig(dir);+ // jsonc-parser's error code + offset, bounded to one line.+ expect(found?.problems[0]).toMatch(/malformed markdownlint config: .+ \(.+at offset \d+\)/);+ });++ test('tolerates trailing commas in .markdownlint.jsonc (full JSONC)', () => {+ write('.markdownlint.jsonc', '{\n "MD013": false,\n "MD041": false,\n}\n');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false, MD041: false });+ });++ test('tolerates a leading BOM (jsonc-parser flags it as an error but parses fine)', () => {+ write('.markdownlint.json', '\uFEFF{ "MD013": false }');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false });+ });++ test('rejects a half-parseable file rather than linting with a partial config', () => {+ // jsonc-parser error-recovers to `{ MD013: false }` here; the missing+ // colon must classify the file malformed, not silently drop MD041.+ write('.markdownlint.jsonc', '{ "MD013": false, "MD041" }');+ expect(discoverMarkdownlintConfig(dir)?.rules).toBeNull();+ });++ test('an executable config is detected, declined, and loudly reported', () => {+ write('.markdownlint.cjs', 'module.exports = { MD013: false };');+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toBeNull();+ expect(found?.problems).toEqual([+ expect.stringContaining('executable markdownlint config detected but not executed'),+ ]);+ });+});++describe('extends resolution', () => {+ test('flattens a relative-path extends chain, child keys winning', () => {+ write('base.json', JSON.stringify({ MD013: true, MD041: false }));+ write('.markdownlint.json', JSON.stringify({ extends: './base.json', MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false, MD041: false });+ expect(found?.problems).toEqual([]);+ });++ test('extends resolves relative to the extending FILE, transitively', () => {+ write('shared/root.json', JSON.stringify({ MD041: false }));+ write('shared/mid.json', JSON.stringify({ extends: './root.json', MD013: true }));+ write('.markdownlint.json', JSON.stringify({ extends: './shared/mid.json', MD010: false }));+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ MD041: false,+ MD013: true,+ MD010: false,+ });+ });++ test('declines a package-name extends with a loud problem, keeping own keys', () => {+ write(+ '.markdownlint.json',+ JSON.stringify({ extends: 'markdownlint/style/relaxed', MD013: false }),+ );+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([expect.stringContaining('package extends is not supported')]);+ });++ test('refuses an extends target that escapes the project root', () => {+ write('.markdownlint.json', JSON.stringify({ extends: '../outside.json', MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([+ expect.stringContaining('refusing extends target outside the project'),+ ]);+ });++ test('breaks an extends cycle with a problem instead of hanging', () => {+ write('a.json', JSON.stringify({ extends: './b.json', MD013: false }));+ write('b.json', JSON.stringify({ extends: './a.json', MD041: false }));+ write('.markdownlint.json', JSON.stringify({ extends: './a.json' }));+ const found = discoverMarkdownlintConfig(dir);+ // a + b both contribute their own keys; the cycle back to a is cut.+ expect(found?.rules).toEqual({ MD013: false, MD041: false });+ expect(found?.problems).toEqual([expect.stringContaining('extends cycle')]);+ });++ test('refuses an extends target whose SYMLINK realpath escapes the project', () => {+ // Lexically inside the boundary, physically outside: the realpath guard+ // (not the lexical one) must catch it.+ const outside = mkdtempSync(join(tmpdir(), 'ok-mdl-outside-'));+ try {+ writeFileSync(join(outside, 'evil.json'), JSON.stringify({ MD041: false }), 'utf-8');+ symlinkSync(join(outside, 'evil.json'), join(dir, 'linked.json'));+ write('.markdownlint.json', JSON.stringify({ extends: './linked.json', MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([+ expect.stringContaining('refusing extends target outside the project'),+ ]);+ } finally {+ rmSync(outside, { recursive: true, force: true });+ }+ });++ test('a missing extends target is a problem, own keys survive', () => {+ write('.markdownlint.json', JSON.stringify({ extends: './nope.json', MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([expect.stringContaining('cannot read')]);+ });++ test('a cannot-read problem carries the underlying errno detail', () => {+ write('.markdownlint.json', JSON.stringify({ extends: './nope.json', MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.problems[0]).toMatch(/cannot read .*nope\.json: .*ENOENT/);+ });++ test('extends: null means no inheritance (markdownlint semantics), not a problem', () => {+ write('.markdownlint.json', JSON.stringify({ extends: null, MD013: false }));+ const found = discoverMarkdownlintConfig(dir);+ expect(found?.rules).toEqual({ MD013: false });+ expect(found?.problems).toEqual([]);+ });+});++describe('resolveNativeMarkdownlintConfig (per-dir cascade, cli2 semantics)', () => {+ test('nearest file on the doc→root walk governs, WHOLESALE (no per-rule merge)', () => {+ write('.markdownlint.json', JSON.stringify({ MD013: false, MD041: false }));+ write('notes/.markdownlint.json', JSON.stringify({ MD010: false }));+ mkdirSync(join(dir, 'notes/deep'), { recursive: true });+ const near = resolveNativeMarkdownlintConfig(join(dir, 'notes/deep'), dir);+ // The folder file replaces the root file entirely — MD013/MD041 do NOT leak in.+ expect(near?.rules).toEqual({ MD010: false });+ expect(near?.file).toBe(join('notes', '.markdownlint.json'));+ });++ test('falls back to the root file when no nearer file exists', () => {+ write('.markdownlint.json', JSON.stringify({ MD013: false }));+ mkdirSync(join(dir, 'a/b'), { recursive: true });+ expect(resolveNativeMarkdownlintConfig(join(dir, 'a/b'), dir)?.rules).toEqual({ MD013: false });+ });++ test('returns null when nothing governs (no upward search above the root)', () => {+ mkdirSync(join(dir, 'a'), { recursive: true });+ expect(resolveNativeMarkdownlintConfig(join(dir, 'a'), dir)).toBeNull();+ });++ test('a subfolder inherits the root config the native way: explicit extends', () => {+ write('.markdownlint.json', JSON.stringify({ MD013: false, MD041: false }));+ write(+ 'notes/.markdownlint.json',+ JSON.stringify({ extends: '../.markdownlint.json', MD010: false }),+ );+ mkdirSync(join(dir, 'notes'), { recursive: true });+ expect(resolveNativeMarkdownlintConfig(join(dir, 'notes'), dir)?.rules).toEqual({+ MD013: false,+ MD041: false,+ MD010: false,+ });+ });++ test('a docDir outside the root clamps to the root', () => {+ write('.markdownlint.json', JSON.stringify({ MD013: false }));+ expect(resolveNativeMarkdownlintConfig(join(dir, '..'), dir)?.rules).toEqual({ MD013: false });+ });+});++describe('readOwnNativeRules', () => {+ test('returns null for a malformed file (write surface may rebuild it)', () => {+ write('.markdownlint.json', '{ not valid json');+ expect(readOwnNativeRules(dir)).toBeNull();+ });++ test('returns the raw bytes alongside the parsed keys', () => {+ const raw = '{\n // keep\n "MD013": false\n}\n';+ write('.markdownlint.jsonc', raw);+ const own = readOwnNativeRules(dir);+ expect(own?.rules).toEqual({ MD013: false });+ expect(own?.raw).toBe(raw);+ });++ // Root reads any file regardless of mode, so the permission probe only+ // proves the rethrow when the process isn't privileged.+ test.if(process.getuid?.() !== 0)(+ 'THROWS on a filesystem read failure — an unreadable file is not "no rules"',+ () => {+ write('.markdownlint.json', JSON.stringify({ MD013: false }));+ chmodSync(join(dir, '.markdownlint.json'), 0o000);+ try {+ expect(() => readOwnNativeRules(dir)).toThrow();+ } finally {+ chmodSync(join(dir, '.markdownlint.json'), 0o644);+ }+ },+ );+});diff --git a/packages/server/src/lint/markdownlint-discovery.ts b/packages/server/src/lint/markdownlint-discovery.tsnew file mode 100644index 000000000..a4ccc16eb--- /dev/null+++ b/packages/server/src/lint/markdownlint-discovery.ts@@ -0,0 +1,277 @@+/**+ * Native markdownlint config discovery. The project's markdownlint rules are the+ * SOURCE OF TRUTH in its own `.markdownlint.*` files — not in `.ok/config.yml`.+ * Resolution follows markdownlint-cli2: the nearest file on the doc→root walk+ * governs wholesale (no per-rule merge across depths), `extends` is the+ * inheritance mechanism, and a governing file is honored exactly as cli2+ * would — no OK underlay (OK's tuned defaults apply only when no file governs).+ *+ * Read-only and fs-bound, so it lives server/CLI-side; the browser never calls+ * it (the browser receives the already-resolved config).+ */++import { existsSync, readFileSync, realpathSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import type { MarkdownlintRuleSetting } from '@inkeep/open-knowledge-core';+import { type ParseError, parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';+import { parse as parseYaml } from 'yaml';++/** markdownlint's native config filenames, in precedence order (first found wins). */+const MARKDOWNLINT_CANDIDATE_FILES = [+ '.markdownlint.jsonc',+ '.markdownlint.json',+ '.markdownlint.yaml',+ '.markdownlint.yml',+ // Executable configs: detected so their presence is never silently ignored,+ // but declined at load time (see loadNativeConfigFile).+ '.markdownlint.cjs',+ '.markdownlint.mjs',+ '.markdownlintrc',+] as const;++/** Default native filename to create when a project has none yet. */+export const DEFAULT_MARKDOWNLINT_FILENAME = '.markdownlint.json';++/**+ * Find the project's existing native markdownlint file (first candidate that+ * exists, by precedence). Returns its name + absolute path, or null when none+ * exists. The write surface uses this to preserve a project's chosen file ++ * format instead of forcing a `.json`.+ */+export function findNativeMarkdownlintFile(dir: string): { name: string; path: string } | null {+ for (const name of MARKDOWNLINT_CANDIDATE_FILES) {+ const path = join(dir, name);+ if (existsSync(path)) return { name, path };+ }+ return null;+}++export interface DiscoveredMarkdownlintConfig {+ /**+ * The resolved native config (a markdownlint `Configuration`, `extends`+ * chain already flattened), or null when the governing file is unusable+ * (malformed / unreadable) — callers then keep OK defaults AND surface+ * `problems`, never silently.+ */+ rules: Record<string, MarkdownlintRuleSetting> | null;+ /** The governing file's path relative to the walk root, for diagnostics. */+ file: string;+ /** Human-readable resolution problems (malformed file, bad `extends`, …). */+ problems: string[];+}++/**+ * Discover the native markdownlint config at `dir` (root-level, no cascade).+ * Returns null when no native file exists.+ */+export function discoverMarkdownlintConfig(dir: string): DiscoveredMarkdownlintConfig | null {+ const found = findNativeMarkdownlintFile(dir);+ if (!found) return null;+ return loadNativeConfigFile(found.path, found.name, dir);+}++/**+ * Cascade discovery, markdownlint-cli2 semantics: the NEAREST directory on+ * the `docDir` → `rootDir` walk that holds a native file governs, wholesale —+ * no per-rule merge across depths (subfolders inherit shared config+ * explicitly via `extends`, the native inheritance mechanism). No search+ * above `rootDir`. Returns null when no file governs `docDir`.+ */+export function resolveNativeMarkdownlintConfig(+ docDir: string,+ rootDir: string,+): DiscoveredMarkdownlintConfig | null {+ const root = resolve(rootDir);+ let dir = resolve(docDir);+ // Clamp escapes (a docDir outside root walks nothing but the root itself).+ if (!isInside(dir, root)) dir = root;+ while (true) {+ const found = findNativeMarkdownlintFile(dir);+ if (found) {+ const loaded = loadNativeConfigFile(+ found.path,+ relative(root, found.path) || found.name,+ root,+ );+ return loaded;+ }+ if (dir === root) return null;+ const parent = dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/**+ * The root-level native file's OWN keys, verbatim — `extends` reference+ * included, chain NOT flattened. This is the write surface's read path: a+ * rule edit must merge into what the user actually wrote, never materialize+ * a resolved `extends` base into the file. Malformed/absent → null.+ *+ * A filesystem READ failure (EACCES, EMFILE, transient I/O) throws instead:+ * null is the write surface's license to rebuild the file from scratch, and+ * an unreadable-but-intact config must abort that write, not seed it with an+ * empty merge base (which would silently drop every hand-tuned rule).+ */+export function readOwnNativeRules(+ dir: string,+): { rules: Record<string, unknown>; name: string; path: string; raw: string } | null {+ const found = findNativeMarkdownlintFile(dir);+ if (!found) return null;+ if (/\.(cjs|mjs|js)$/.test(found.path)) return null;+ const raw = readFileSync(found.path, 'utf-8');+ const parsed = parseNativeConfig(raw, found.name);+ if ('error' in parsed) return null;+ const { value } = parsed;+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ return { rules: value as Record<string, unknown>, name: found.name, path: found.path, raw };+}++/** Max `extends` chain depth — cycles are caught separately; this bounds pathology. */+const MAX_EXTENDS_DEPTH = 10;++function isInside(path: string, root: string): boolean {+ const rel = relative(root, path);+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));+}++/**+ * Load one native config file and flatten its `extends` chain (child keys win+ * over the extended base, shallow — markdownlint's own merge). Guards:+ * package-name `extends` declined (no node_modules resolution semantics in a+ * KB project or the bundled server); realpath outside `boundaryDir` refused+ * (mirrors the symlink-escape policy); cycles + depth bounded. Every guard+ * records a problem — a config that half-resolves lints with what DID resolve+ * plus loud problems, and a malformed governing file yields `rules: null`.+ */+function loadNativeConfigFile(+ absPath: string,+ displayName: string,+ boundaryDir: string,+): DiscoveredMarkdownlintConfig {+ const problems: string[] = [];+ const visited = new Set<string>();++ const load = (path: string, depth: number): Record<string, MarkdownlintRuleSetting> | null => {+ // Lexical containment first, so an escaping target is refused as an+ // escape even when it doesn't exist (realpath would throw "cannot read").+ if (!isInside(resolve(path), resolve(boundaryDir))) {+ problems.push(+ `refusing extends target outside the project: ${relative(boundaryDir, path) || path}`,+ );+ return null;+ }+ let real: string;+ try {+ real = realpathSync(path);+ } catch (err) {+ problems.push(`cannot read ${relative(boundaryDir, path) || path}: ${errorDetail(err)}`);+ return null;+ }+ // Realpath containment second — catches symlinks that point outside.+ if (!isInside(real, realpathSync(boundaryDir))) {+ problems.push(+ `refusing extends target outside the project: ${relative(boundaryDir, path) || path}`,+ );+ return null;+ }+ if (visited.has(real)) {+ problems.push(`extends cycle at ${relative(boundaryDir, path) || path}`);+ return null;+ }+ visited.add(real);+ if (depth > MAX_EXTENDS_DEPTH) {+ problems.push(`extends chain deeper than ${MAX_EXTENDS_DEPTH} levels`);+ return null;+ }+ if (/\.(cjs|mjs|js)$/.test(path)) {+ problems.push(+ `executable markdownlint config detected but not executed: ${relative(boundaryDir, path) || path} — use a JSON/JSONC/YAML config`,+ );+ return null;+ }+ let raw: string;+ try {+ // Read via the already-resolved realpath so the bytes parsed come from+ // the same inode the containment check validated (a symlink swapped+ // between check and read would otherwise reopen the escape window).+ raw = readFileSync(real, 'utf-8');+ } catch (err) {+ problems.push(`cannot read ${relative(boundaryDir, path) || path}: ${errorDetail(err)}`);+ return null;+ }+ const parsed = parseNativeConfig(raw, path);+ if ('error' in parsed) {+ problems.push(+ `malformed markdownlint config: ${relative(boundaryDir, path) || path} (${parsed.error})`,+ );+ return null;+ }+ if (!parsed.value || typeof parsed.value !== 'object' || Array.isArray(parsed.value)) {+ problems.push(+ `malformed markdownlint config: ${relative(boundaryDir, path) || path} (not an object)`,+ );+ return null;+ }+ // `$schema` is editor-tooling metadata (officially recommended for+ // IntelliSense); markdownlint ignores it at runtime, and its URL-string+ // value must not reach the rules object (the wire schema's rule-setting+ // union would reject it and 500 the config fetch).+ const {+ extends: extendsRef,+ $schema: _schema,+ ...own+ } = parsed.value as Record<string, MarkdownlintRuleSetting> & {+ extends?: unknown;+ $schema?: unknown;+ };+ // Null is markdownlint's documented "no inheritance" value, same as absent.+ if (extendsRef === undefined || extendsRef === null) return own;+ if (typeof extendsRef !== 'string' || extendsRef === '') {+ problems.push(`invalid extends value in ${relative(boundaryDir, path) || path}`);+ return own;+ }+ // Bare specifiers are npm packages in native markdownlint — declined here.+ if (!extendsRef.startsWith('.') && !isAbsolute(extendsRef)) {+ problems.push(+ `package extends is not supported (${JSON.stringify(extendsRef)} in ${relative(boundaryDir, path) || path}) — use a relative file path`,+ );+ return own;+ }+ const target = resolve(dirname(path), extendsRef);+ const base = load(target, depth + 1);+ // Child keys override the extended base, per markdownlint's shallow merge.+ return base ? { ...base, ...own } : own;+ };++ const rules = load(absPath, 0);+ return { rules, file: displayName, problems };+}++/** First line of an error's message, so problems stay one-line but keep the cause. */+function errorDetail(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ return message.split('\n', 1)[0] ?? '';+}++function parseNativeConfig(raw: string, name: string): { value: unknown } | { error: string } {+ try {+ if (name.endsWith('.yaml') || name.endsWith('.yml')) return { value: parseYaml(raw) };+ // JSON + JSONC + `.markdownlintrc` all go through jsonc-parser: a+ // strict-JSON superset tolerating comments and trailing commas, matching+ // what markdownlint-cli2 accepts (regex-stripped JSONC has bitten this+ // repo before — parser-capability findings in the 2026-06-26 harness+ // config-write-safety work). BOM is stripped up front: jsonc-parser+ // reports it as InvalidSymbol@0 while still parsing fine, so leaving it+ // would misclassify a valid BOM'd config as malformed. jsonc-parser+ // recovers a value even for partially invalid input, so collect errors+ // and treat any as malformed rather than lint with a half-parsed config.+ const errors: ParseError[] = [];+ const value = parseJsonc(raw.replace(/^\uFEFF/, ''), errors, { allowTrailingComma: true });+ const first = errors[0];+ if (first) return { error: `${printParseErrorCode(first.error)} at offset ${first.offset}` };+ return { value };+ } catch (err) {+ return { error: errorDetail(err) };+ }+}diff --git a/packages/server/src/lint/markdownlint-write.test.ts b/packages/server/src/lint/markdownlint-write.test.tsnew file mode 100644index 000000000..b5849decf--- /dev/null+++ b/packages/server/src/lint/markdownlint-write.test.ts@@ -0,0 +1,297 @@+/**+ * Unit tests for the native markdownlint write surface against a real temp dir:+ * create-on-first-edit (seeded with OK's tuned defaults, materialized),+ * format preservation, merge, key removal, `extends` preservation, and+ * prune-to-empty file deletion. Round-trips are asserted via the discovery read.+ */++import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ chmodSync,+ existsSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DEFAULT_MARKDOWNLINT_CONFIG } from '@inkeep/open-knowledge-core';+import { parse as parseYaml } from 'yaml';+import { discoverMarkdownlintConfig, readOwnNativeRules } from './markdownlint-discovery.ts';+import { writeMarkdownlintRule } from './markdownlint-write.ts';++let dir: string;++beforeEach(() => {+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-mdl-write-')));+});+afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+});++describe('writeMarkdownlintRule', () => {+ test('creates .markdownlint.json on first edit, seeded with the tuned defaults', () => {+ const res = writeMarkdownlintRule(dir, 'MD010', false);+ expect(res).toEqual({ action: 'written', file: '.markdownlint.json' });+ expect(existsSync(join(dir, '.markdownlint.json'))).toBe(true);+ // The create materializes OK's defaults into the file — from now on the+ // file is the whole story for every native tool; OK layers nothing under.+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ ...DEFAULT_MARKDOWNLINT_CONFIG,+ MD010: false,+ });+ });++ test('merges a second rule, preserving the first', () => {+ writeMarkdownlintRule(dir, 'MD010', false);+ writeMarkdownlintRule(dir, 'MD013', true);+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ ...DEFAULT_MARKDOWNLINT_CONFIG,+ MD010: false,+ MD013: true,+ });+ });++ test('updates an existing rule value in place', () => {+ writeMarkdownlintRule(dir, 'MD010', false);+ writeMarkdownlintRule(dir, 'MD010', true);+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ ...DEFAULT_MARKDOWNLINT_CONFIG,+ MD010: true,+ });+ });++ test('writes a params object', () => {+ writeMarkdownlintRule(dir, 'MD007', { indent: 4 });+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ ...DEFAULT_MARKDOWNLINT_CONFIG,+ MD007: { indent: 4 },+ });+ });++ test('does NOT seed a hand-authored file (edits merge into what the user wrote)', () => {+ writeFileSync(join(dir, '.markdownlint.json'), JSON.stringify({ MD013: false }), 'utf-8');+ writeMarkdownlintRule(dir, 'MD010', false);+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false, MD010: false });+ });++ test('removing the last rule of a hand-authored file deletes it', () => {+ writeFileSync(join(dir, '.markdownlint.json'), JSON.stringify({ MD010: false }), 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD010', null);+ expect(res.action).toBe('deleted');+ expect(existsSync(join(dir, '.markdownlint.json'))).toBe(false);+ });++ test('removing one of several rules keeps the file', () => {+ writeFileSync(+ join(dir, '.markdownlint.json'),+ JSON.stringify({ MD010: false, MD013: false }),+ 'utf-8',+ );+ writeMarkdownlintRule(dir, 'MD010', null);+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false });+ });++ test('removing a rule when no file exists is a no-op (never creates a seeded file)', () => {+ const res = writeMarkdownlintRule(dir, 'MD010', null);+ expect(res.action).toBe('noop');+ expect(existsSync(join(dir, '.markdownlint.json'))).toBe(false);+ });++ test('preserves an existing .yaml file (writes YAML, not JSON)', () => {+ writeFileSync(join(dir, '.markdownlint.yaml'), 'MD013: false\n', 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD010', false);+ expect(res.file).toBe('.markdownlint.yaml');+ expect(existsSync(join(dir, '.markdownlint.json'))).toBe(false);+ // The on-disk file is still parseable as YAML and carries both rules.+ const raw = readFileSync(join(dir, '.markdownlint.yaml'), 'utf-8');+ expect(parseYaml(raw)).toEqual({ MD013: false, MD010: false });+ });++ test('declines to rewrite an executable .cjs config (would corrupt the module)', () => {+ const original = 'module.exports = { MD013: false };';+ writeFileSync(join(dir, '.markdownlint.cjs'), original, 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD010', false);+ expect(res).toEqual({ action: 'declined-executable', file: '.markdownlint.cjs' });+ // The module body is untouched, byte for byte.+ expect(readFileSync(join(dir, '.markdownlint.cjs'), 'utf-8')).toBe(original);+ expect(existsSync(join(dir, '.markdownlint.json'))).toBe(false);+ });++ // Root reads any file regardless of mode, so the permission probe only+ // proves the abort when the process isn't privileged.+ test.if(process.getuid?.() !== 0)(+ 'a transient read failure ABORTS the write — the hand-tuned file is untouched',+ () => {+ const original = JSON.stringify({ MD013: false, MD041: { level: 2 } });+ const file = join(dir, '.markdownlint.json');+ writeFileSync(file, original, 'utf-8');+ chmodSync(file, 0o000);+ try {+ // An unreadable file must never be mistaken for "no rules": merging+ // into an empty base would rewrite the file with only the new rule.+ expect(() => writeMarkdownlintRule(dir, 'MD010', false)).toThrow();+ } finally {+ chmodSync(file, 0o644);+ }+ expect(readFileSync(file, 'utf-8')).toBe(original);+ },+ );++ test('a MALFORMED file is still clobbered cleanly (documented behavior)', () => {+ writeFileSync(join(dir, '.markdownlint.json'), '{ not valid json', 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD010', false);+ expect(res.action).toBe('written');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD010: false });+ });++ test('preserves an extends reference verbatim — never materializes the base', () => {+ writeFileSync(join(dir, 'base.markdownlint.json'), JSON.stringify({ MD041: false }), 'utf-8');+ writeFileSync(+ join(dir, '.markdownlint.json'),+ JSON.stringify({ extends: './base.markdownlint.json', MD013: false }),+ 'utf-8',+ );+ writeMarkdownlintRule(dir, 'MD010', false);+ // Own keys only: the extends key survives, the base's MD041 is NOT copied in.+ expect(readOwnNativeRules(dir)?.rules).toEqual({+ extends: './base.markdownlint.json',+ MD013: false,+ MD010: false,+ });+ // The flattened resolution still sees the base through the chain.+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ MD041: false,+ MD013: false,+ MD010: false,+ });+ });+});++describe('JSONC comment preservation', () => {+ const COMMENTED = [+ '{',+ ' // tuned for prose, not code',+ ' "MD013": false, /* long lines OK */',+ ' "MD041": false',+ '}',+ '',+ ].join('\n');++ test('toggling an existing rule keeps every comment, changing only the value', () => {+ writeFileSync(join(dir, '.markdownlint.jsonc'), COMMENTED, 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD013', true);+ expect(res).toEqual({ action: 'written', file: '.markdownlint.jsonc' });+ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('// tuned for prose, not code');+ expect(raw).toContain('/* long lines OK */');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: true, MD041: false });+ });++ test('adding a new rule appends it without disturbing comments', () => {+ writeFileSync(join(dir, '.markdownlint.jsonc'), COMMENTED, 'utf-8');+ writeMarkdownlintRule(dir, 'MD007', { indent: 4 });+ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('// tuned for prose, not code');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({+ MD013: false,+ MD041: false,+ MD007: { indent: 4 },+ });+ });++ test('removing a rule keeps the remaining config and its comments', () => {+ writeFileSync(join(dir, '.markdownlint.jsonc'), COMMENTED, 'utf-8');+ writeMarkdownlintRule(dir, 'MD041', null);+ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('// tuned for prose, not code');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({ MD013: false });+ });++ test('removing the LAST rule keeps a file that still carries comments', () => {+ writeFileSync(+ join(dir, '.markdownlint.jsonc'),+ '// our lint philosophy, hand-tuned\n{\n "MD013": false\n}\n',+ 'utf-8',+ );+ const res = writeMarkdownlintRule(dir, 'MD013', null);+ // The emptied config keeps governing (native defaults, no OK underlay) —+ // deleting would destroy the user's comments.+ expect(res.action).toBe('written');+ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('// our lint philosophy, hand-tuned');+ expect(discoverMarkdownlintConfig(dir)?.rules).toEqual({});+ });++ test('a comment annotating ONLY the removed rule goes with it; an emptied file is deleted', () => {+ writeFileSync(+ join(dir, '.markdownlint.jsonc'),+ '{\n // about MD013 specifically\n "MD013": false\n}\n',+ 'utf-8',+ );+ // jsonc-parser removes the property together with the comment attached to+ // it — nothing meaningful remains, so the file goes too.+ const res = writeMarkdownlintRule(dir, 'MD013', null);+ expect(res.action).toBe('deleted');+ expect(existsSync(join(dir, '.markdownlint.jsonc'))).toBe(false);+ });++ test('removing the last rule of a comment-free .jsonc still deletes the file', () => {+ writeFileSync(join(dir, '.markdownlint.jsonc'), '{ "MD013": false }\n', 'utf-8');+ const res = writeMarkdownlintRule(dir, 'MD013', null);+ expect(res.action).toBe('deleted');+ expect(existsSync(join(dir, '.markdownlint.jsonc'))).toBe(false);+ });+});++describe('alias-keyed configs', () => {+ test('setting a rule writes through the existing alias key — no dual MD### key', () => {+ writeFileSync(+ join(dir, '.markdownlint.jsonc'),+ '{\n // prefer readable names\n "line-length": { "line_length": 100 }\n}\n',+ 'utf-8',+ );+ writeMarkdownlintRule(dir, 'MD013', false);+ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('"line-length": false');+ expect(raw).not.toContain('MD013');+ expect(raw).toContain('// prefer readable names');+ });++ test('with mixed keys, the governing (last) key is edited; the shadowed one is left alone', () => {+ writeFileSync(+ join(dir, '.markdownlint.json'),+ '{\n "MD013": false,\n "line-length": true\n}\n',+ 'utf-8',+ );+ writeMarkdownlintRule(dir, 'MD013', { line_length: 120 });+ const parsed = JSON.parse(readFileSync(join(dir, '.markdownlint.json'), 'utf-8'));+ // Last-key-wins in the engine: editing the shadowed MD013 would be a no-op.+ expect(parsed).toEqual({ MD013: false, 'line-length': { line_length: 120 } });+ });++ test('removing a rule deletes EVERY key addressing it (a shadowed alias would resurrect it)', () => {+ writeFileSync(+ join(dir, '.markdownlint.json'),+ JSON.stringify({ MD013: false, 'line-length': true, MD010: false }),+ 'utf-8',+ );+ writeMarkdownlintRule(dir, 'MD013', null);+ expect(readOwnNativeRules(dir)?.rules).toEqual({ MD010: false });+ });++ test('setting through an alias works on YAML too', () => {+ writeFileSync(join(dir, '.markdownlint.yaml'), 'line-length: false\n', 'utf-8');+ writeMarkdownlintRule(dir, 'MD013', true);+ const raw = readFileSync(join(dir, '.markdownlint.yaml'), 'utf-8');+ expect(parseYaml(raw)).toEqual({ 'line-length': true });+ });++ test('a rule id outside the catalog falls back to exact-key semantics', () => {+ writeFileSync(join(dir, '.markdownlint.json'), JSON.stringify({ MD999: true }), 'utf-8');+ writeMarkdownlintRule(dir, 'MD999', false);+ expect(readOwnNativeRules(dir)?.rules).toEqual({ MD999: false });+ });+});diff --git a/packages/server/src/lint/markdownlint-write.ts b/packages/server/src/lint/markdownlint-write.tsnew file mode 100644index 000000000..cd121c839--- /dev/null+++ b/packages/server/src/lint/markdownlint-write.ts@@ -0,0 +1,197 @@+/**+ * Native markdownlint config WRITE surface. The settings GUI edits the project's+ * own `.markdownlint.*` file (the source of truth — see `markdownlint-discovery`);+ * this merges a single rule change into it, format-preserving and atomic.+ *+ * Read-only discovery + this writer are the only `.markdownlint.*` I/O paths.+ * Writes target the ROOT file even though discovery cascades per-dir — a+ * settings edit is a project-level act; folder files are authored by hand.+ *+ * JSON-family files (`.json` / `.jsonc` / `.markdownlintrc`) are edited via+ * jsonc-parser's minimal text edits, so comments and formatting survive a rule+ * toggle. YAML files round-trip through the parser (whole-object rewrite).+ *+ * Rule identity is alias-aware: markdownlint accepts aliases (`line-length`)+ * as config keys, case-insensitively, last-key-wins. A set edits the key form+ * the user already wrote (the governing — last — one when several address the+ * same rule); a remove deletes EVERY key addressing the rule, since leaving a+ * shadowed alias behind would resurrect the value the user just removed.+ */++import { join } from 'node:path';+import {+ canonicalRuleId,+ DEFAULT_MARKDOWNLINT_CONFIG,+ findRuleConfigEntry,+ type MarkdownlintRuleSetting,+} from '@inkeep/open-knowledge-core';+import { applyEdits, modify, parse as parseJsonc, stripComments } from 'jsonc-parser';+import { stringify as stringifyYaml } from 'yaml';+import { tracedRenameSync, tracedUnlinkSync, tracedWriteFileSync } from '../fs-traced.ts';+import {+ DEFAULT_MARKDOWNLINT_FILENAME,+ findNativeMarkdownlintFile,+ readOwnNativeRules,+} from './markdownlint-discovery.ts';++export interface WriteMarkdownlintResult {+ /**+ * `written` = file created/updated; `deleted` = last rule removed; `noop` =+ * nothing to do; `declined-executable` = the project's native config is an+ * executable `.cjs`/`.mjs` module the write surface must not touch (a JSON+ * rewrite would corrupt it — discovery already surfaces the config as a+ * loud problem, so the edit is refused rather than destructive).+ */+ action: 'written' | 'deleted' | 'noop' | 'declined-executable';+ /** The native filename touched (e.g. `.markdownlint.json`), for diagnostics. */+ file: string;+}++/** YAML for `.yaml`/`.yml`; JSON (2-space) for everything else, including new files. */+function serialize(name: string, rules: Record<string, unknown>): string {+ if (name.endsWith('.yaml') || name.endsWith('.yml')) return stringifyYaml(rules);+ return `${JSON.stringify(rules, null, 2)}\n`;+}++/** The key a set should write through: the governing existing form, else canonical. */+function governingKey(rules: Readonly<Record<string, unknown>>, ruleId: string): string {+ return findRuleConfigEntry(rules, ruleId)?.key ?? canonicalRuleId(ruleId) ?? ruleId;+}++/** Every key in `rules` addressing `ruleId` (canonical + aliases, any case). */+function keysAddressing(rules: Readonly<Record<string, unknown>>, ruleId: string): string[] {+ const canonical = canonicalRuleId(ruleId);+ if (canonical === null) return ruleId in rules ? [ruleId] : [];+ return Object.keys(rules).filter((key) => canonicalRuleId(key) === canonical);+}++const JSONC_FORMATTING = { insertSpaces: true, tabSize: 2, eol: '\n' } as const;++/** Apply one rule change to raw JSON/JSONC text as minimal, comment-preserving edits. */+function applyJsoncRuleChange(+ raw: string,+ rules: Readonly<Record<string, unknown>>,+ ruleId: string,+ value: MarkdownlintRuleSetting | null,+): string {+ let text = raw;+ if (value === null) {+ for (const key of keysAddressing(rules, ruleId)) {+ text = applyEdits(+ text,+ modify(text, [key], undefined, { formattingOptions: JSONC_FORMATTING }),+ );+ }+ return text;+ }+ const key = governingKey(rules, ruleId);+ return applyEdits(text, modify(text, [key], value, { formattingOptions: JSONC_FORMATTING }));+}++/** Atomic write (tmp + rename), traced; never leaves the tmp file behind. */+function writeFileAtomic(file: string, content: string): void {+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;+ try {+ tracedWriteFileSync(tmp, content, 'utf-8');+ tracedRenameSync(tmp, file);+ } catch (err) {+ // The tmp file sits in user-visible content space — never leave an+ // orphan behind on a failed write/rename (same pattern as+ // config-persistence.ts).+ try {+ tracedUnlinkSync(tmp);+ } catch {+ // tmp may not exist if the write itself failed.+ }+ throw err;+ }+}++/**+ * Merge a single rule change into the project's native markdownlint file.+ * `value === null` deletes the rule (reverting it to OK's tuned default); a+ * boolean/params value sets it. Writes back to the existing file + format, or+ * creates `.markdownlint.json` when none exists. Removing the last rule deletes+ * the file — unless the file still carries comments, which are kept (the+ * emptied config keeps governing; deleting a user's commented file is data+ * loss). Atomic (tmp + rename) and traced.+ *+ * A filesystem READ failure on an existing file throws (via+ * `readOwnNativeRules`) — writing through it would rebuild the file from an+ * empty merge base and silently drop every other rule.+ */+export function writeMarkdownlintRule(+ contentDir: string,+ ruleId: string,+ value: MarkdownlintRuleSetting | null,+): WriteMarkdownlintResult {+ const existing = findNativeMarkdownlintFile(contentDir);+ const name = existing?.name ?? DEFAULT_MARKDOWNLINT_FILENAME;+ const file = existing?.path ?? join(contentDir, name);++ // An executable config (matched by the candidate list so its presence is+ // never silently ignored) must not be rewritten: readOwnNativeRules+ // declines it, so the merge base would be {} and serialize would overwrite+ // the module body with bare JSON under a .cjs/.mjs name — silent data loss.+ if (existing && /\.(cjs|mjs|js)$/.test(existing.path)) {+ return { action: 'declined-executable', file: existing.name };+ }++ // Removing a rule that has no file to live in must not create one (the+ // seeded create below would otherwise materialize defaults on a deletion).+ if (!existing && value === null) return { action: 'noop', file: name };++ // Read the file's OWN keys fresh from disk (extends reference preserved,+ // chain NOT flattened) so concurrent edits merge, not clobber, and a rule+ // edit never materializes a resolved extends base into the file. A+ // malformed file (`own === null`) is rewritten cleanly — the documented+ // clobber. When NO file exists yet, the create is seeded with OK's tuned+ // defaults materialized — from that moment the file is the whole story for+ // every native tool, and OK layers nothing under it.+ const own = existing ? readOwnNativeRules(contentDir) : null;+ const isYaml = name.endsWith('.yaml') || name.endsWith('.yml');++ if (existing && own && !isYaml) {+ const text = applyJsoncRuleChange(own.raw, own.rules, ruleId, value);+ const remaining = parseJsonc(text.replace(/^\uFEFF/, ''), [], { allowTrailingComma: true });+ const isEmpty =+ !remaining ||+ typeof remaining !== 'object' ||+ Object.keys(remaining as Record<string, unknown>).length === 0;+ if (isEmpty) {+ // Comments are the whole point of JSONC — keep the file when any+ // survive, even though its config is now empty (an empty governing+ // file keeps governing: native defaults, no OK underlay).+ const hasComments = stripComments(text) !== text;+ if (!hasComments) {+ tracedUnlinkSync(file);+ return { action: 'deleted', file: name };+ }+ }+ writeFileAtomic(file, text);+ return { action: 'written', file: name };+ }++ const rules: Record<string, unknown> = own+ ? { ...own.rules }+ : existing+ ? {}+ : { ...DEFAULT_MARKDOWNLINT_CONFIG };++ if (value === null) {+ for (const key of keysAddressing(rules, ruleId)) delete rules[key];+ } else {+ rules[governingKey(rules, ruleId)] = value;+ }++ if (Object.keys(rules).length === 0) {+ if (existing) {+ tracedUnlinkSync(file);+ return { action: 'deleted', file: name };+ }+ return { action: 'noop', file: name };+ }++ writeFileAtomic(file, serialize(name, rules));+ return { action: 'written', file: name };+}diff --git a/packages/server/src/lint/resolve-config.ts b/packages/server/src/lint/resolve-config.tsnew file mode 100644index 000000000..f203a6943--- /dev/null+++ b/packages/server/src/lint/resolve-config.ts@@ -0,0 +1,74 @@+/**+ * Effective lint-config resolution. OK config persists only the plugin+ * toggles; markdownlint `rules` come from the project's native+ * `.markdownlint.*` files, resolved per document with markdownlint-cli2+ * cascade semantics (nearest file on the doc→root walk governs wholesale,+ * `extends` flattened). When a native file governs, it is honored exactly as+ * cli2 would — no OK underlay; OK's tuned defaults (the base rules) apply+ * only when no file governs the doc. Resolution problems (malformed file,+ * bad `extends`) are surfaced through `onProblem`, never swallowed.+ */++import { dirname, join } from 'node:path';+import type { LinterConfig, MarkdownlintRuleSetting } from '@inkeep/open-knowledge-core';+import {+ type DiscoveredMarkdownlintConfig,+ resolveNativeMarkdownlintConfig,+} from './markdownlint-discovery.ts';++export interface ResolveLinterConfigOptions {+ /**+ * The document the config is being resolved FOR, as a content-relative+ * path (`folder/doc.md` — only its directory matters, so an extension-less+ * docName works too). Omitted → root-level resolution.+ */+ docName?: string;+ /** Receives each resolution problem, tagged with the governing file. */+ onProblem?: (problem: string) => void;+}++/**+ * The cascade resolution behind `resolveEffectiveLinterConfig`, exposed for+ * callers that need the governing file + problems themselves (lint-config API).+ */+export function resolveNativeConfigForDoc(+ contentDir: string,+ docName: string | undefined,+ onProblem?: (problem: string) => void,+): DiscoveredMarkdownlintConfig | null {+ const docDir = docName ? join(contentDir, dirname(docName)) : contentDir;+ const native = resolveNativeMarkdownlintConfig(docDir, contentDir);+ if (native && onProblem) for (const p of native.problems) onProblem(`[${native.file}] ${p}`);+ return native;+}++/**+ * Compose the effective config from a base + a (possibly absent) discovered+ * native config. A governing file wins wholesale; an unusable governing file+ * (rules null) or no file at all keeps the base rules (OK's tuned defaults).+ */+export function composeEffectiveLinterConfig(+ base: LinterConfig,+ native: DiscoveredMarkdownlintConfig | null,+): LinterConfig {+ const rules: Record<string, MarkdownlintRuleSetting> =+ native?.rules ?? base.plugins.markdownlint.rules;+ return {+ ...base,+ plugins: {+ ...base.plugins,+ markdownlint: { ...base.plugins.markdownlint, rules },+ },+ };+}++export function resolveEffectiveLinterConfig(+ contentDir: string,+ base: LinterConfig,+ opts: ResolveLinterConfigOptions = {},+): LinterConfig {+ return composeEffectiveLinterConfig(+ base,+ resolveNativeConfigForDoc(contentDir, opts.docName, opts.onProblem),+ );+}diff --git a/packages/server/src/mcp/tools/advisory-warnings.test.ts b/packages/server/src/mcp/tools/advisory-warnings.test.tsindex 3777bd589..98892f3ca 100644--- a/packages/server/src/mcp/tools/advisory-warnings.test.ts+++ b/packages/server/src/mcp/tools/advisory-warnings.test.ts@@ -5,7 +5,13 @@*/import { describe, expect, test } from 'bun:test';-import type { BrokenLink, RenderWarning, WriteWarning } from '@inkeep/open-knowledge-core';+import type {+ AdvisoryWarning,+ BrokenLink,+ LintViolationWarning,+ RenderWarning,+ WriteWarning,+} from '@inkeep/open-knowledge-core';import {formatAdvisoryBriefs,formatAdvisoryLines,@@ -222,3 +228,71 @@ describe('formatBrokenLinkBrief', () => {);});});++describe('content-rule (lint) violations', () => {+ const lint = (over: Partial<LintViolationWarning> = {}): LintViolationWarning => ({+ kind: 'lint-violation',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ severity: 'warning',+ line: 3,+ column: 1,+ ...over,+ });++ test('formatAdvisoryLines emits one line per violation, with rule + line + message', () => {+ const lines = formatAdvisoryLines([+ lint(),+ lint({+ code: 'MD043',+ message: 'Required heading structure',+ severity: 'error',+ line: 1,+ }),+ ]);+ expect(lines).toHaveLength(2);+ expect(lines[0]).toContain('markdownlint/MD010');+ expect(lines[0]).toContain('line 3');+ expect(lines[1]).toContain('markdownlint/MD043');+ expect(lines[1]).toContain('error');+ });++ test('formatAdvisoryBriefs emits a brief per violation', () => {+ const briefs = formatAdvisoryBriefs([lint()]);+ expect(briefs.some((b) => b.includes('MD010'))).toBe(true);+ });++ test('coexists with render + integrity entries', () => {+ const lines = formatAdvisoryLines([mermaidWarning(), lint()]);+ expect(lines.some((l) => l.toLowerCase().includes('mermaid'))).toBe(true);+ expect(lines.some((l) => l.includes('MD010'))).toBe(true);+ });+});++describe('unrecognized-kind fallback', () => {+ // A kind added to AdvisoryWarningSchema before this relay learns its+ // family — the closed union requires the cast.+ const future = { kind: 'future-advisory-kind', detail: 42 } as unknown as AdvisoryWarning;++ test('formatAdvisoryLines emits a generic line instead of dropping the entry', () => {+ const lines = formatAdvisoryLines([future]);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('⚠');+ expect(lines[0]).toContain('future-advisory-kind');+ });++ test('formatAdvisoryBriefs emits a generic brief instead of dropping the entry', () => {+ const briefs = formatAdvisoryBriefs([future]);+ expect(briefs).toHaveLength(1);+ expect(briefs[0]).toContain('future-advisory-kind');+ });++ test('recognized siblings keep their dedicated formats alongside the fallback', () => {+ const lines = formatAdvisoryLines([DIVERGENCE, future, mermaidWarning()]);+ expect(lines).toHaveLength(3);+ expect(lines.some((l) => l.includes('Content divergence'))).toBe(true);+ expect(lines.some((l) => l.toLowerCase().includes('mermaid'))).toBe(true);+ expect(lines.some((l) => l.includes('future-advisory-kind'))).toBe(true);+ });+});diff --git a/packages/server/src/mcp/tools/advisory-warnings.ts b/packages/server/src/mcp/tools/advisory-warnings.tsindex 98a60a6cc..9e5dc300c 100644--- a/packages/server/src/mcp/tools/advisory-warnings.ts+++ b/packages/server/src/mcp/tools/advisory-warnings.ts@@ -20,6 +20,7 @@ import {AdvisoryWarningSchema,type BrokenLink,BrokenLinkSchema,+ type LintViolationWarning,type RenderWarning,type WriteWarning,} from '@inkeep/open-knowledge-core';@@ -87,11 +88,55 @@ function renderEntries(warnings: AdvisoryWarning[]): RenderWarning[] {return warnings.filter((w): w is RenderWarning => w.kind === 'mermaid-parse-error');}+function lintEntries(warnings: AdvisoryWarning[]): LintViolationWarning[] {+ return warnings.filter((w): w is LintViolationWarning => w.kind === 'lint-violation');+}++/**+ * Kinds the family partitions above recognize. Entries outside this set — a+ * kind added to `AdvisoryWarningSchema` before this relay learns its family —+ * must still surface on the text channel (generic fallback line below), not+ * vanish for text-only consumers.+ */+const RELAYED_KINDS: ReadonlySet<string> = new Set([+ 'content-divergence',+ 'disk-edit-reconciled',+ 'mermaid-parse-error',+ 'lint-violation',+]);++function unrecognizedEntries(warnings: AdvisoryWarning[]): AdvisoryWarning[] {+ return warnings.filter((w) => !RELAYED_KINDS.has(w.kind));+}++/** Generic fallback `⚠` line for a kind this relay has no dedicated format for. */+function formatUnrecognizedLine(d: AdvisoryWarning): string {+ return `⚠ Advisory "${d.kind}" — see structuredContent.document.warnings for details.`;+}++/** Generic fallback `⚠` brief for a kind this relay has no dedicated format for. */+function formatUnrecognizedBrief(d: AdvisoryWarning): string {+ return `⚠ Advisory "${d.kind}" (see warnings).`;+}++/** `⚠` line for a single content-rule violation (flat `source/code` rule id). */+function formatLintLine(d: LintViolationWarning): string {+ const mark = d.severity === 'error' ? 'error' : 'warning';+ return `⚠ Content rule ${d.source}/${d.code} (${mark}, line ${d.line}): ${d.message}`;+}++/** Brief `⚠` suffix for a content-rule violation on a batch per-doc line. */+function formatLintBrief(d: LintViolationWarning): string {+ return `⚠ ${d.source}/${d.code} (line ${d.line}): ${d.message}`;+}+/** Full `⚠` lines (single-doc write + edit + restore): per integrity entry, plus one grouped render line. */export function formatAdvisoryLines(warnings: AdvisoryWarning[]): string[] {const lines = integrityEntries(warnings).map(formatIntegrityLine);const render = renderEntries(warnings);if (render.length > 0) lines.push(formatRenderWarningsLine(render));+ lines.push(...lintEntries(warnings).map(formatLintLine));+ lines.push(...unrecognizedEntries(warnings).map(formatUnrecognizedLine));return lines;}@@ -100,6 +145,8 @@ export function formatAdvisoryBriefs(warnings: AdvisoryWarning[]): string[] {const briefs = integrityEntries(warnings).map(formatIntegrityBrief);const render = renderEntries(warnings);if (render.length > 0) briefs.push(formatRenderWarningsBrief(render));+ briefs.push(...lintEntries(warnings).map(formatLintBrief));+ briefs.push(...unrecognizedEntries(warnings).map(formatUnrecognizedBrief));return briefs;}diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.tsindex fe95c4f2d..a057a8cb2 100644--- a/packages/server/src/mcp/tools/index.ts+++ b/packages/server/src/mcp/tools/index.ts@@ -48,6 +48,7 @@ import { register as registerPreviewUrl } from './get-preview-url.ts';import { register as registerHistory } from './history.ts';import { register as registerInstall } from './install.ts';import { register as registerLinks } from './links.ts';+import { register as registerLint } from './lint.ts';import { register as registerMove } from './move.ts';import { register as registerPalette } from './palette.ts';import { register as registerResolveConflict } from './resolve-conflict.ts';@@ -144,6 +145,15 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('links'),});+ // Markdown lint — surface rule violations (single doc or project-wide audit);+ // `fix: true` applies auto-fixes through the agent-write spine, so it takes+ // `identityRef` to attribute the write (mirrors write/edit).+ registerLint(registrationServer, {+ serverUrl: opts.serverUrl,+ config: opts.config,+ resolveCwd: named('lint'),+ identityRef: opts.identityRef,+ });// CRUD verbs — polymorphic over document / folder / template / asset// (Pattern B: per-target fields nested inside the address key). `write`,diff --git a/packages/server/src/mcp/tools/lint.test.ts b/packages/server/src/mcp/tools/lint.test.tsnew file mode 100644index 000000000..4450a108d--- /dev/null+++ b/packages/server/src/mcp/tools/lint.test.ts@@ -0,0 +1,413 @@+import {+ describe as _bunDescribe,+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ test,+} from 'bun:test';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { type Config, ConfigSchema } from '../../config/schema.ts';+import {+ AUDIT_FILE_CAP,+ AUDIT_FILE_DIAGNOSTIC_CAP,+ DESCRIPTION,+ type LintDeps,+ register,+} from './lint.ts';+import type { ServerInstance } from './shared.ts';+import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';++// Skip-on-CI gate (oven-sh/bun#11892): same git-child-reaping issue the sibling+// MCP tool tests guard against on ubuntu-latest GHA runners.+const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;++const BASE_CONFIG: Config = ConfigSchema.parse({});++interface ToolResult {+ content: Array<{ type: 'text'; text: string }>;+ structuredContent?: Record<string, unknown>;+ isError?: boolean;+}++interface LintHandlerArgs {+ document?: string;+ path?: string;+ fix?: boolean;+}++interface RegisteredTool {+ name: string;+ description: string;+ annotations?: Record<string, unknown>;+ handler: (args: LintHandlerArgs) => Promise<ToolResult>;+}++function createFakeServer() {+ let registered: RegisteredTool | undefined;+ const server = {+ registerTool(+ name: string,+ cfg: { description?: string; annotations?: Record<string, unknown> },+ handler: (args: LintHandlerArgs) => Promise<ToolResult>,+ ) {+ registered = {+ name,+ description: cfg.description ?? '',+ annotations: cfg.annotations,+ handler,+ };+ },+ } as unknown as ServerInstance;+ return {+ server,+ getTool(): RegisteredTool {+ if (!registered) throw new Error('Tool was not registered');+ return registered;+ },+ };+}++function makeDeps(serverUrl: string | undefined, cwdDir: string): LintDeps {+ return { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwdDir };+}++let testServer: ReturnType<typeof Bun.serve>;+let baseUrl: string;+let tmpDir: string;+const seenRequests: string[] = [];++function warningDiagnostic(line: number) {+ return {+ range: { start: { line, character: 0 }, end: { line, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ };+}++function auditPayloadOf(fileCount: number, diagnosticsPerFile: number) {+ const files = Array.from({ length: fileCount }, (_, i) => ({+ file: `doc-${String(i).padStart(2, '0')}.md`,+ diagnostics: Array.from({ length: diagnosticsPerFile }, (_, line) => warningDiagnostic(line)),+ }));+ return {+ ok: true,+ files,+ fileCount,+ errorCount: 0,+ warningCount: fileCount * diagnosticsPerFile,+ warnings: [],+ };+}++beforeAll(() => {+ testServer = Bun.serve({+ port: 0,+ hostname: '127.0.0.1',+ fetch(req) {+ const url = new URL(req.url);+ seenRequests.push(`${url.pathname}?${url.searchParams.toString()}`);+ if (url.pathname === '/api/lint/fix') {+ // The server's attributed auto-fix. Two fixed, one non-fixable remains.+ return Response.json({+ ok: true,+ file: 'notes.md',+ fixedCount: 2,+ diagnostics: [+ {+ range: { start: { line: 4, character: 0 }, end: { line: 4, character: 5 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD041',+ message: 'First line in file should be a top-level heading',+ },+ ],+ errorCount: 0,+ warningCount: 1,+ });+ }+ if (url.pathname === '/api/lint') {+ const doc = url.searchParams.get('doc');+ if (doc === 'clean') return Response.json({ ok: true, file: 'clean.md', diagnostics: [] });+ if (doc === 'fixable') {+ return Response.json({+ ok: true,+ file: 'fixable.md',+ diagnostics: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ fixes: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ newText: ' ',+ },+ ],+ },+ ],+ });+ }+ return Response.json({+ ok: true,+ file: `${doc}.md`,+ diagnostics: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ },+ ],+ });+ }+ if (url.pathname === '/api/lint/audit') {+ const path = url.searchParams.get('path');+ if (path === 'over-cap') {+ return Response.json(auditPayloadOf(AUDIT_FILE_CAP + 2, AUDIT_FILE_DIAGNOSTIC_CAP + 3));+ }+ if (path === 'at-cap') {+ return Response.json(auditPayloadOf(AUDIT_FILE_CAP, AUDIT_FILE_DIAGNOSTIC_CAP));+ }+ return Response.json({+ ok: true,+ files: [+ {+ file: 'dirty.md',+ diagnostics: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ },+ {+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } },+ severity: 'error',+ source: 'frontmatter',+ code: 'required',+ message: 'Missing required property: title',+ },+ ],+ },+ ],+ fileCount: 4,+ errorCount: 1,+ warningCount: 1,+ warnings: [],+ });+ }+ return Response.json({ ok: false, error: 'Not found' }, { status: 404 });+ },+ });+ baseUrl = `http://127.0.0.1:${testServer.port}`;+});++afterAll(() => {+ testServer.stop();+});++beforeEach(async () => {+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-lint-test-'));+ seenRequests.length = 0;+});++afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true });+});++describe('lint — registration + DESCRIPTION', () => {+ test('registers exactly one tool named "lint"', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ expect(getTool().name).toBe('lint');+ });++ test('declares mutating (fix-capable) tool annotations', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ // Not read-only: `fix: true` mutates the doc (recoverable content write).+ expect(getTool().annotations).toEqual({+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: true,+ });+ });++ test('DESCRIPTION documents both shapes and the fix mode', () => {+ expect(DESCRIPTION).toContain('`document`');+ expect(DESCRIPTION).toContain('audit');+ expect(DESCRIPTION).toContain('severity');+ expect(DESCRIPTION).toContain('`fix: true`');+ });++ test('returns Hocuspocus-unavailable error when no serverUrl is configured', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(undefined, tmpDir));+ const result = await getTool().handler({});+ expect(result.isError).toBe(true);+ expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);+ });+});++describe('lint — single document', () => {+ test('hits /api/lint with a normalized docName and returns its diagnostics', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ document: 'notes.md' });+ expect(seenRequests).toContain('/api/lint?doc=notes');+ const s = result.structuredContent as {+ files: Array<{ file: string; diagnostics: unknown[] }>;+ errorCount: number;+ warningCount: number;+ };+ expect(s.files).toHaveLength(1);+ expect(s.files[0]?.diagnostics).toHaveLength(1);+ expect(s.errorCount).toBe(0);+ expect(s.warningCount).toBe(1);+ expect(result.content[0]?.text).toContain('markdownlint/MD010');+ expect(result.content[0]?.text).toContain('line 3');+ });++ test('a clean doc reports no problems', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ document: 'clean' });+ const s = result.structuredContent as { warningCount: number; errorCount: number };+ expect(s.warningCount).toBe(0);+ expect(s.errorCount).toBe(0);+ expect(result.content[0]?.text).toContain('No problems');+ });+});++describe('lint — project audit', () => {+ test('omitting document hits /api/lint/audit and summarizes counts', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({});+ expect(seenRequests.some((r) => r.startsWith('/api/lint/audit'))).toBe(true);+ const s = result.structuredContent as {+ files: unknown[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ };+ expect(s.files).toHaveLength(1);+ expect(s.fileCount).toBe(4);+ expect(s.errorCount).toBe(1);+ expect(s.warningCount).toBe(1);+ expect(result.content[0]?.text).toContain('dirty.md');+ expect(result.content[0]?.text).toContain('1 error');+ });++ test('passes a sub-path scope through to the audit endpoint', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ await getTool().handler({ path: 'sub/dir' });+ expect(seenRequests).toContain('/api/lint/audit?path=sub%2Fdir');+ });+});++describe('lint — audit output cap', () => {+ interface AuditStructured {+ files: Array<{+ file: string;+ diagnostics: unknown[];+ omittedDiagnosticCount?: number;+ }>;+ fileCount: number;+ errorCount: number;+ warningCount: number;+ omittedFileCount?: number;+ }++ test('over-cap audits truncate both channels but keep totals accurate', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'over-cap' });++ const s = result.structuredContent as unknown as AuditStructured;+ expect(s.files).toHaveLength(AUDIT_FILE_CAP);+ expect(s.omittedFileCount).toBe(2);+ for (const file of s.files) {+ expect(file.diagnostics).toHaveLength(AUDIT_FILE_DIAGNOSTIC_CAP);+ expect(file.omittedDiagnosticCount).toBe(3);+ }+ // Totals mirror the server's full-scan counts, not the truncated view.+ expect(s.fileCount).toBe(AUDIT_FILE_CAP + 2);+ expect(s.warningCount).toBe((AUDIT_FILE_CAP + 2) * (AUDIT_FILE_DIAGNOSTIC_CAP + 3));++ const text = result.content[0]?.text ?? '';+ expect(text).toContain(`${AUDIT_FILE_CAP + 2} of ${AUDIT_FILE_CAP + 2} documents`);+ expect(text).toContain('… and 3 more problems');+ expect(text).toContain('… and 2 more files with problems');+ const shownFileHeaders = text.match(/^doc-\d+\.md:$/gm) ?? [];+ expect(shownFileHeaders).toHaveLength(AUDIT_FILE_CAP);+ });++ test('an audit exactly at the cap is complete, with no truncation indicators', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'at-cap' });++ const s = result.structuredContent as unknown as AuditStructured;+ expect(s.files).toHaveLength(AUDIT_FILE_CAP);+ expect(s.omittedFileCount).toBeUndefined();+ for (const file of s.files) {+ expect(file.diagnostics).toHaveLength(AUDIT_FILE_DIAGNOSTIC_CAP);+ expect(file.omittedDiagnosticCount).toBeUndefined();+ }++ const text = result.content[0]?.text ?? '';+ expect(text).not.toContain('… and');+ });+});++describe('lint — fix mode', () => {+ test('fix:true POSTs /api/lint/fix and reports fixed + remaining', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ document: 'notes.md', fix: true });+ expect(seenRequests.some((r) => r.startsWith('/api/lint/fix'))).toBe(true);+ const s = result.structuredContent as {+ fixedCount: number;+ files: Array<{ diagnostics: unknown[] }>;+ warningCount: number;+ };+ expect(s.fixedCount).toBe(2);+ expect(s.files[0]?.diagnostics).toHaveLength(1);+ const text = result.content[0]?.text ?? '';+ expect(text).toContain('Fixed 2 problems in notes.md');+ expect(text).toContain('1 problem remain');+ expect(text).toContain('`edit`/`write`');+ });++ test('fix:true without a document is an error and hits no endpoint', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ fix: true });+ expect(result.isError).toBe(true);+ expect(result.content[0]?.text).toContain('requires `document`');+ expect(seenRequests.some((r) => r.startsWith('/api/lint/fix'))).toBe(false);+ });+});++describe('lint — fixability hint', () => {+ test('a single-doc report quantifies how many violations `fix: true` would resolve', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ document: 'fixable' });+ const text = result.content[0]?.text ?? '';+ expect(text).toContain('auto-fixable');+ expect(text).toContain('`fix: true`');+ });+});diff --git a/packages/server/src/mcp/tools/lint.ts b/packages/server/src/mcp/tools/lint.tsnew file mode 100644index 000000000..0d81beb50--- /dev/null+++ b/packages/server/src/mcp/tools/lint.ts@@ -0,0 +1,354 @@+/**+ * `lint` MCP tool — surface markdown-lint violations to the agent, and+ * optionally auto-fix them.+ *+ * Three shapes:+ * - `document` given → lint that one doc, returning its diagnostics.+ * - `document` omitted → audit every in-scope doc (optionally scoped to a+ * sub-`path`), returning only the files that have violations plus totals.+ * - `document` + `fix: true` → apply markdownlint's auto-fixes to that doc+ * through the agent-write spine (attributed, live preview), then report+ * what remains. The one mutating shape; backed by `POST /api/lint/fix`.+ *+ * The read shapes lint the persisted disk content with the project's effective+ * config (native `.markdownlint.*` rules injected over the project base);+ * `fix: true` lints and rewrites the live CRDT source. Violations carry a+ * `severity` (`error` | `warning`); the text summary leads with the+ * error/warning counts so a text-only consumer can triage without parsing the+ * structured payload.+ */++import { z } from 'zod';+import type { AgentIdentity } from '../agent-identity.ts';+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';+import {+ agentIdentityFields,+ HOCUSPOCUS_NOT_RUNNING_ERROR,+ httpGet,+ httpPost,+ looseObjectArray,+ normalizeDocName,+ outputSchemaWithText,+ ROUTED_CWD_DESCRIPTION,+ resolveProjectServerContext,+ textPlusStructured,+ textResult,+} from './shared.ts';++export const DESCRIPTION = [+ '[Requires: Hocuspocus server] Lint markdown documents and report problems (rule violations); optionally auto-fix them.',+ '',+ '- `document` given → lint just that doc (extension-less path); `path` is ignored.',+ '- `document` omitted → audit every in-scope `.md`/`.mdx` doc; pass `path` to scope to a folder or single file.',+ '- `fix: true` (requires `document`) → apply auto-fixable rules to that doc IN PLACE and report what remains.',+ '',+ "Each violation carries a `source` (the plugin, e.g. markdownlint), a `code` (the engine's native rule id, e.g. MD010), `message`, a 0-based LSP `range`, and `severity` ('error' | 'warning' | 'info' | 'hint'). The audit lists only files that have at least one violation, plus `fileCount`/`errorCount`/`warningCount`. Audit output (text and structured) is capped at 10 files × 10 diagnostics per file, with explicit '… and N more' indicators; the counts always reflect the full scan — re-run with `path` scoped to a folder or file to see what was omitted. Lint rules are configured in Settings → Plugins (the toggle is committed to `config.yml`; the rules live in the project's native `.markdownlint.*` file).",+ '',+ 'To auto-fix, pass `fix: true` with `document`: the fix lands through the collaborative document — attributed to you and reflected in the live preview, same as the editor. It fixes auto-fixable rules (e.g. hard tabs, trailing spaces); violations that resist auto-fix need content edits via the `edit`/`write` tools. (`ok lint --fix` from a shell remains the headless/CI path, but it writes on disk unattributed — prefer `fix: true` when the server is running.)',+].join('\n');++/**+ * Audit output caps, mirroring the advisory channel's per-write violation cap:+ * a whole-project audit can carry thousands of diagnostics, which would flood+ * the calling agent's context. Totals stay uncapped; scoping via `path`+ * recovers omitted detail.+ */+export const AUDIT_FILE_CAP = 10;+export const AUDIT_FILE_DIAGNOSTIC_CAP = 10;++/**+ * Trailing hint for a single-doc lint, quantified by the fixability the wire+ * payload now carries (`fixes` present ⇒ auto-fixable): tells the agent exactly+ * how many `fix: true` would resolve and what's left for content edits.+ */+function singleDocFixHint(fixableCount: number, total: number): string {+ if (fixableCount === 0) {+ return 'None are auto-fixable — these need content edits via `edit`/`write`.';+ }+ const remaining = total - fixableCount;+ const remainder =+ remaining > 0 ? ` The other ${remaining} need content edits via \`edit\`/\`write\`.` : '';+ return `${fixableCount} of ${total} are auto-fixable — pass \`fix: true\` to apply in place (attributed, live preview).${remainder}`;+}++/** Audit-level hint: fix is per-document, so point at the single-doc call. */+const AUDIT_FIX_HINT =+ 'Auto-fix a single file with `lint({ document, fix: true })` (attributed, live preview). Violations that resist auto-fix need content edits.';++interface LintPositionPayload {+ line?: number;+ character?: number;+}++interface LintTextEditPayload {+ range?: { start?: LintPositionPayload; end?: LintPositionPayload };+ newText?: string;+}++interface LintDiagnosticPayload {+ source?: string;+ code?: string;+ message?: string;+ severity?: string;+ range?: { start?: LintPositionPayload; end?: LintPositionPayload };+ fixes?: LintTextEditPayload[];+}++interface LintDocPayload {+ file?: string;+ diagnostics?: LintDiagnosticPayload[];+}++interface LintFixPayload {+ file?: string;+ fixedCount?: number;+ diagnostics?: LintDiagnosticPayload[];+ warning?: string;+}++interface LintAuditPayload {+ files?: LintDocPayload[];+ fileCount?: number;+ errorCount?: number;+ warningCount?: number;+ warnings?: string[];+}++export interface LintDeps {+ serverUrl: ServerUrlOrResolver;+ config: ConfigOrResolver;+ resolveCwd: (explicit?: string) => Promise<string>;+ /** Present so `fix: true` attributes the write to the calling agent (mirrors write/edit). */+ identityRef?: { current: AgentIdentity };+}++interface LintArgs {+ document?: string;+ path?: string;+ fix?: boolean;+ cwd?: string;+}++export function register(server: ServerInstance, deps: LintDeps): void {+ server.registerTool(+ 'lint',+ {+ description: DESCRIPTION,+ inputSchema: {+ document: z+ .string()+ .optional()+ .describe('Doc to lint (path, extension-less). Omit to audit the whole project.'),+ path: z+ .string()+ .optional()+ .describe(+ 'Audit scope when `document` is omitted: a folder or single file (content-dir-relative). Default: the whole project.',+ ),+ fix: z+ .boolean()+ .optional()+ .describe(+ 'Auto-fix fixable rules in `document` IN PLACE (attributed, live preview), then report what remains. Requires `document`.',+ ),+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),+ },+ outputSchema: outputSchemaWithText({+ files: looseObjectArray+ .optional()+ .describe('Per-file diagnostics. For a single-doc lint, the one file (even if clean).'),+ fileCount: z.number().optional().describe('Audit only: total in-scope documents scanned.'),+ errorCount: z.number().describe('Total error-severity violations.'),+ warningCount: z.number().describe('Total warning-severity violations.'),+ warnings: z+ .array(z.string())+ .optional()+ .describe('Audit only: non-fatal issues (unreadable files/dirs).'),+ omittedFileCount: z+ .number()+ .optional()+ .describe('Audit only: files with problems omitted from `files` by the output cap.'),+ fixedCount: z+ .number()+ .optional()+ .describe('Fix mode only: problems resolved by the auto-fix.'),+ cwd: z.string().describe('Absolute directory the lint ran against.'),+ }),+ // Not read-only: `fix: true` mutates the document. The write is a+ // recoverable, shadow-versioned content edit (like `write`/`edit`), so the+ // tool stays auto-approved; `destructiveHint` is false and re-running+ // converges (`idempotentHint`).+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: true,+ },+ },+ async (args: LintArgs) => {+ const context = await resolveProjectServerContext(+ deps.resolveCwd,+ deps.config,+ deps.serverUrl,+ args.cwd,+ );+ if (!context.ok) return textResult(`Error: ${context.error}`, true);+ const { cwd, url } = context;+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);++ if (args.fix === true) {+ if (args.document === undefined) {+ return textResult(+ 'Error: `fix: true` requires `document` (fix one doc at a time). Omit `fix` to audit the whole project.',+ true,+ );+ }+ return fixLintDoc(args.document, url, cwd, deps.identityRef?.current);+ }++ return args.document !== undefined+ ? lintSingleDoc(args.document, url, cwd)+ : lintAudit(args.path, url, cwd);+ },+ );+}++async function fixLintDoc(+ document: string,+ url: string,+ cwd: string,+ identity: AgentIdentity | undefined,+) {+ const normalized = normalizeDocName(document);+ if (!normalized.ok) return textResult(normalized.error, true);+ const result = await httpPost(url, '/api/lint/fix', {+ docName: normalized.docName,+ ...agentIdentityFields(identity),+ });+ if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);+ const { ok: _ok, ...rest } = result;+ const data = rest as LintFixPayload;+ const file = data.file ?? normalized.docName;+ const diagnostics = data.diagnostics ?? [];+ const fixedCount = data.fixedCount ?? 0;+ const errorCount = diagnostics.filter((d) => d.severity === 'error').length;+ const warningCount = diagnostics.length - errorCount;+ const structured = { files: [{ file, diagnostics }], fixedCount, errorCount, warningCount, cwd };++ const header = data.warning+ ? // Fix wrote successfully but the post-write re-lint failed — the doc is+ // fixed; the diagnostics below fall back to the pre-fix set. Do NOT treat+ // this as a failed fix.+ `Applied auto-fixes to ${file}, but re-lint failed (${data.warning}); the fix landed — problems below are the pre-fix set, re-run \`lint\` to confirm.`+ : fixedCount > 0+ ? `Fixed ${fixedCount} problem${fixedCount === 1 ? '' : 's'} in ${file}.`+ : `No auto-fixable problems in ${file}.`;+ const lines = diagnostics.map(formatDiagnosticLine);+ const footer =+ diagnostics.length > 0 && !data.warning+ ? [+ `${diagnostics.length} problem${diagnostics.length === 1 ? '' : 's'} remain (${countSummary(errorCount, warningCount)}) — need content edits via \`edit\`/\`write\`.`,+ ]+ : [];+ return textPlusStructured([header, ...lines, ...footer].join('\n'), structured);+}++async function lintSingleDoc(document: string, url: string, cwd: string) {+ const normalized = normalizeDocName(document);+ if (!normalized.ok) return textResult(normalized.error, true);+ const result = await httpGet(url, `/api/lint?doc=${encodeURIComponent(normalized.docName)}`);+ if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);+ const { ok: _ok, ...rest } = result;+ const data = rest as LintDocPayload;+ const diagnostics = data.diagnostics ?? [];+ const errorCount = diagnostics.filter((d) => d.severity === 'error').length;+ const warningCount = diagnostics.length - errorCount;+ const file = { file: data.file ?? normalized.docName, diagnostics };+ const structured = { files: [file], errorCount, warningCount, cwd };++ const header =+ diagnostics.length === 0+ ? `No problems in ${file.file}.`+ : `${file.file}: ${countSummary(errorCount, warningCount)}`;+ const lines = diagnostics.map(formatDiagnosticLine);+ const fixableCount = diagnostics.filter((d) => (d.fixes?.length ?? 0) > 0).length;+ const footer = diagnostics.length > 0 ? [singleDocFixHint(fixableCount, diagnostics.length)] : [];+ return textPlusStructured([header, ...lines, ...footer].join('\n'), structured);+}++async function lintAudit(path: string | undefined, url: string, cwd: string) {+ const query = path ? `?path=${encodeURIComponent(path)}` : '';+ const result = await httpGet(url, `/api/lint/audit${query}`);+ if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);+ const { ok: _ok, ...rest } = result;+ const data = rest as LintAuditPayload;+ const files = data.files ?? [];+ const fileCount = data.fileCount ?? 0;+ const errorCount = data.errorCount ?? 0;+ const warningCount = data.warningCount ?? 0;++ // Both channels are agent-context-bound, so both get the cap; the HTTP+ // endpoint stays the uncapped surface for GUI consumers.+ const shownFiles = files.slice(0, AUDIT_FILE_CAP).map((file) => {+ const diagnostics = file.diagnostics ?? [];+ const shown = diagnostics.slice(0, AUDIT_FILE_DIAGNOSTIC_CAP);+ const omitted = diagnostics.length - shown.length;+ return {+ ...file,+ diagnostics: shown,+ ...(omitted > 0 ? { omittedDiagnosticCount: omitted } : {}),+ };+ });+ const omittedFileCount = files.length - shownFiles.length;++ const structured = {+ files: shownFiles,+ fileCount,+ errorCount,+ warningCount,+ ...(data.warnings && data.warnings.length > 0 ? { warnings: data.warnings } : {}),+ ...(omittedFileCount > 0 ? { omittedFileCount } : {}),+ cwd,+ };++ const scope = path ? ` in ${path}` : '';+ if (files.length === 0) {+ return textPlusStructured(+ `No problems across ${fileCount} document${fileCount === 1 ? '' : 's'}${scope}.`,+ structured,+ );+ }+ const header = `${files.length} of ${fileCount} document${fileCount === 1 ? '' : 's'}${scope} with problems — ${countSummary(errorCount, warningCount)}:`;+ const fileBlocks = shownFiles.map((file) => {+ const lines = file.diagnostics.map(formatDiagnosticLine);+ if (file.omittedDiagnosticCount !== undefined) {+ lines.push(+ ` … and ${file.omittedDiagnosticCount} more problem${file.omittedDiagnosticCount === 1 ? '' : 's'}`,+ );+ }+ return [`${file.file ?? '(unknown)'}:`, ...lines].join('\n');+ });+ const footer =+ omittedFileCount > 0+ ? [`… and ${omittedFileCount} more file${omittedFileCount === 1 ? '' : 's'} with problems`]+ : [];+ return textPlusStructured(+ [header, ...fileBlocks, ...footer, AUDIT_FIX_HINT].join('\n'),+ structured,+ );+}++function formatDiagnosticLine(d: LintDiagnosticPayload): string {+ const marker = d.severity === 'error' ? '✘' : '⚠';+ const startLine = d.range?.start?.line;+ // Text output is human-facing: display 1-based lines from the 0-based range.+ const where = startLine !== undefined ? `line ${startLine + 1}` : 'line ?';+ const flatId = d.source !== undefined && d.code !== undefined ? `${d.source}/${d.code}` : '?';+ return ` ${marker} ${where} ${flatId}: ${d.message ?? ''}`.trimEnd();+}++function countSummary(errorCount: number, warningCount: number): string {+ const parts: string[] = [];+ if (errorCount > 0) parts.push(`${errorCount} error${errorCount === 1 ? '' : 's'}`);+ if (warningCount > 0) parts.push(`${warningCount} warning${warningCount === 1 ? '' : 's'}`);+ return parts.length > 0 ? parts.join(', ') : 'no problems';+}diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.tsindex b25ffa170..564c70b47 100644--- a/packages/server/src/mcp/tools/registry.test.ts+++ b/packages/server/src/mcp/tools/registry.test.ts@@ -1,8 +1,8 @@/**- * Registry assertion — pins the 17-tool surface of `registerAllTools`.+ * Registry assertion — pins the tool surface of `registerAllTools`.*- * The OK MCP redesign collapsed the original surface to 17 native- * CRUD verbs + discriminated reads:+ * The OK MCP redesign collapsed the original surface to native+ * CRUD verbs + discriminated reads (`lint` was added later as a read):* - `write` / `edit` / `delete` / `move` are polymorphic over* document / folder / template / asset — absorbing write_document,* edit_document, edit_frontmatter, delete_document, rename(_document/_folder),@@ -16,7 +16,7 @@* - `history` / `config` / `preview_url` dropped the `get_` prefix.* - read_document / grep / list_documents were dropped (exec subsumes).*- * This test guards both ends: the 17 retained tools are present; none of the+ * This test guards both ends: the expected tools are present; none of the* names in RETIRED_TOOL_NAMES are.*/@@ -42,6 +42,7 @@ const EXPECTED_TOOLS = ['palette','preview_url','share_link',+ 'lint',// Writes — CRUD verbs + version'write','edit',@@ -123,13 +124,13 @@ function captureRegistered(): string[] {return names;}-describe('registerAllTools — 19-tool surface (SPEC.md §9.1 / AC8 + PRD-6935 install + skills read)', () => {- test('registers exactly 19 tools', () => {+describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install + skills + lint)', () => {+ test('registers exactly the expected number of tools', () => {const names = captureRegistered();- expect(names.length).toBe(19);+ expect(names.length).toBe(EXPECTED_TOOLS.length);});- test('the 19 expected tool names are all present', () => {+ test('the expected tool names are all present', () => {const names = new Set(captureRegistered());for (const expected of EXPECTED_TOOLS) {expect(names).toContain(expected);@@ -167,8 +168,9 @@ describe('registerAllTools — 19-tool surface (SPEC.md §9.1 / AC8 + PRD-6935 i** On the auto-approved side: `write` / `edit` / `checkpoint` / `restore_version`* / `resolve_conflict` all mutate KB content, but the shadow repo versions every- * write, so `history` + `restore_version` recover them. `exec` is a read-only- * allowlisted sandbox. `install` is NOT here — it projects executable skill+ * write, so `history` + `restore_version` recover them. `lint` joins them: its+ * `fix: true` mode is a recoverable, shadow-versioned content write (report-only+ * otherwise). `exec` is read-only (sandboxed allowlist). `install` is NOT here — it projects executable skill* scripts into the agent's own config dir, which no KB version history undoes.*/const OK_AUTO_APPROVED_TOOLS = [@@ -187,6 +189,7 @@ const OK_AUTO_APPROVED_TOOLS = ['conflicts','resolve_conflict','workflow',+ 'lint',] as const;describe('docked-terminal auto-approve classification', () => {diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 10ab117ee..e19c7a507 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -14,11 +14,15 @@ import {type ConfigIssue,createBasenameIndex,DEFAULT_ATTACHMENT_FOLDER_PATH,+ DEFAULT_LINTER_CONFIG,humanFormat,isKnownConfigError,+ type LinterConfig,type MarkdownManager,+ type PersistedLinterConfig,type Principal,parseGlobalSkillBundleDoc,+ toEffectiveBase,} from '@inkeep/open-knowledge-core';import {readConfigSafely,@@ -603,6 +607,21 @@ export function createServer(options: ServerOptions): ServerInstance {return project.value.autoSync?.default === true;}+ // Project-scope base linter config, read FRESH per request so a config edit+ // (project `.ok/config.yml` → contentRules.*) takes effect without a restart.+ function readLinterBaseConfig(): LinterConfig {+ const project = readConfigSafely({+ absPath: resolveConfigPath('project', projectDir),+ sideline: false,+ warn: (message) => log.warn({ message }, '[config] could not read project config for linter'),+ });+ // Persisted config omits markdownlint `rules` (native-file sourced); lift it+ // to an effective base (rules placeholder), which the resolver fills from the+ // native `.markdownlint.*` file.+ const persisted = project.value.contentRules as PersistedLinterConfig | undefined;+ return persisted ? toEffectiveBase(persisted) : DEFAULT_LINTER_CONFIG;+ }+// Project-local-only read (shared with `ok embeddings status` so they can't// disagree). Read fresh (not from the boot snapshot) so the config watcher's// re-evaluation picks up runtime edits.@@ -1587,6 +1606,7 @@ export function createServer(options: ServerOptions): ServerInstance {},semanticSearch,getSemanticSimilarityFloor: () => readSemanticSearchConfig().similarityFloor,+ getLinterBaseConfig: () => readLinterBaseConfig(),getLinkPreviewsEnabled: readLinkPreviewsEnabled,embeddingsSecretsFile: secretsFilePath(configHomedirOverride),ephemeral,