Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): unified validation surface (PRD-7375/7483) (#2884)
serafin-garcia3fb989cefd45
diff --git a/.changeset/content-rules-settings-create-link.md b/.changeset/content-rules-settings-create-link.mdnew file mode 100644index 000000000..0923d8c25--- /dev/null+++ b/.changeset/content-rules-settings-create-link.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Broken-link handling is now configurable, and dead links get a one-shot fix. A new **Content rules** tab under Settings → This project holds two project-shared knobs: how broken internal links are reported — hidden, warning (the new default, since a broken link is often a typo or a page-yet-to-be-written), or error — and whether the file explorer tints and badges files that have problems. Both persist as `validation.*` in config.yml; lint plugins keep their own tab. In the Problems panel, every dead-link row (doc and project scope) now offers a **Create page** action that creates the missing target — the same action as the Links panel's missing-page affordance, surfaced where the problem is listed. It is deliberately not part of Fix all: bulk-creating targets could silently mint duplicate files, so creation stays a per-row decision.diff --git a/.changeset/ok-audit-cli-command.md b/.changeset/ok-audit-cli-command.mdnew file mode 100644index 000000000..977288c55--- /dev/null+++ b/.changeset/ok-audit-cli-command.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++New `ok audit [path]` CLI command — the unified validation audit (markdownlint problems and broken internal links in one source-tagged, per-file report) is now available from the terminal, completing surface parity with the `audit` MCP tool and `GET /api/audit`. It delegates to the running project server (the links validator needs the live backlink index), scopes to a folder or single file via the optional path argument, and exits non-zero when problems are found for CI use. `--json` emits the full uncapped diagnostic plane; `--errors-only` restricts the failing exit to error-severity findings. `ok lint` is unchanged and remains the headless, lint-only alternative that needs no server.diff --git a/.changeset/unified-problems-panel-tree-indicators.md b/.changeset/unified-problems-panel-tree-indicators.mdnew file mode 100644index 000000000..fbbaa6fe7--- /dev/null+++ b/.changeset/unified-problems-panel-tree-indicators.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++The Problems panel is now the single validation space, and the file tree shows which files have problems without opening them. Project scope consumes the unified audit (`GET /api/audit`), so markdownlint violations and broken internal links render together, grouped by file with a per-row source tag (lint vs link); doc scope merges the open document's broken-link findings into the live lint list via the same canonical audit predicate, and link rows click-jump to their line in source mode. Fix all remains lint-only (links are not auto-fixable). In the file tree, files with problems tint their name red (errors) or yellow (warnings) and carry a problem-count badge; both severities light up, and clean files stay bare. Freshness comes from three cheap triggers — a project audit refreshes everything, the open document's entry tracks its live diagnostics, and a document whose bytes reach disk is re-validated alone (so an agent writing a broken link into an unopened file tints its row) — never a background whole-project scan. The Links panel is unchanged: it remains the navigation and graph aid.diff --git a/.changeset/unified-validation-audit.md b/.changeset/unified-validation-audit.mdnew file mode 100644index 000000000..4d21928c4--- /dev/null+++ b/.changeset/unified-validation-audit.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": minor+---++Open Knowledge now has a unified content audit that reports markdownlint problems and broken links together. A new `audit` MCP tool and a new read-only `GET /api/audit` endpoint run both validators in one call — over the whole project or scoped to a folder or single doc via `?path=` — and return one normalized per-file diagnostic plane in which every finding is tagged with its source (`markdownlint` or `links`). Broken-link findings are grouped under the doc that contains the link (the file you would edit to fix it), with the message naming the unresolved target; their severity follows the project's `validation.links` setting (warning by default, raisable to error, or hidden entirely).++Dead-link findings now also carry the source line of the offending link, giving them jump-to-line parity with lint diagnostics (line exact; column approximate). Existing surfaces are unchanged: the `lint` and `links` MCP tools and the `/api/lint`, `/api/lint/audit`, and `/api/dead-links` routes behave exactly as before, and backlink caches written by earlier versions load cleanly — entries gain positions as their docs are re-indexed.diff --git a/.changeset/write-advisories-unified-plane.md b/.changeset/write-advisories-unified-plane.mdnew file mode 100644index 000000000..1c8b95b6c--- /dev/null+++ b/.changeset/write-advisories-unified-plane.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Agent write/edit advisories now ride the unified validation plane: the up-to-10 findings on every `write`/`edit`/`agent-patch` response include broken internal links alongside lint violations, so an agent that writes a dead wiki-link hears about it on the write response itself — no separate `audit` round-trip. Dead-link entries carry the unresolved target verbatim (`linkTarget`), ready for a create-page fix, and honor the project's `validation.links` posture (hidden / warning / error). The write path refreshes the link index for the written doc before validating, so the very write that introduces a dead link is the one that reports it — the index's debounced update can't race the advisory. Still advisory-only: findings never block a write.diff --git a/docs/content/advanced/content-rules/overview.mdx b/docs/content/advanced/content-rules/overview.mdxindex 81eb40ca7..dd203d1d0 100644--- a/docs/content/advanced/content-rules/overview.mdx+++ b/docs/content/advanced/content-rules/overview.mdx@@ -37,12 +37,23 @@ ok lint --errors-only # exit non-zero only on error-severity problemsThe 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.+`ok audit` widens the same report to the full validation plane — markdownlint problems **and** broken internal links, each finding tagged with its source:++```bash+ok audit # audit the whole project (lint + links)+ok audit guides/ # scope to a folder or a single file+ok audit --json # the full structured diagnostic plane+ok audit --errors-only # exit non-zero only on error-severity problems+```++Unlike `ok lint`, `ok audit` needs the project's server running (`ok start` or OK Desktop) — the links validator reads the live backlink index. Same CI-friendly exit code; there's no `--fix` because the audit is read-only (lint fixes go through `ok lint --fix`, link repairs are content edits).+## AI agentsAgents 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.+- Every agent write response carries up to 10 validation findings for the document it touched — lint violations **and** broken internal links, following the same [Content rules](/docs/reference/configuration) posture as the audit — so an agent that writes a dead link hears about it immediately and can clean up after itself without being asked. Dead-link findings name the unresolved target, ready for a create-page fix. Advisory only — a finding never blocks the write.## See alsodiff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex c173818c1..65788d8e1 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -18,6 +18,7 @@ The surface is **19 tools**. The four write verbs — `write`, `edit`, `delete`,| `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` |+| `audit` | Unified read-only validation audit: every content problem — markdownlint violations **and** broken internal links — in one call, grouped by the file to fix (`path` scopes to a folder or doc). Each finding is tagged with its validator (`markdownlint` or `links`); broken links report under the source doc that contains them, at the offending line, as warnings by default (the project's `validation.links` setting can raise them to errors or hide them). Same 10 × 10 output cap as `lint`'s audit, with accurate totals. No fix shape — lint fixes go through `lint`, link repairs through `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/packages/app/package.json b/packages/app/package.jsonindex 87358e7c5..adad6ad46 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/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/lint-config-toggle.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/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-navigation.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/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/lint-config-toggle.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/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-navigation.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",diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsxindex 8a8ec3f41..b28d05559 100644--- a/packages/app/src/App.dom.test.tsx+++ b/packages/app/src/App.dom.test.tsx@@ -95,6 +95,9 @@ vi.doMock('@/lib/config-provider', () => ({ConfigProvider: ({ children }: { children: ReactNode }) => (<div data-testid="config-provider">{children}</div>),+ // ValidationFreshness (mounted in the App body) gates on the merged config;+ // null merged reads as every default (indicators on).+ useConfigContext: () => ({ merged: null }),}));// AppBody reads `merged.appearance.preview.autoOpen` to compose thediff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex 1a14d0174..5701f5c14 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -27,6 +27,7 @@ import { PageListProvider, usePageList } from '@/components/PageListContext';import { ReportBugMenuTrigger } from '@/components/ReportBugMenuTrigger';import { SystemDocSubscriber } from '@/components/SystemDocSubscriber';import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';+import { ValidationFreshness } from '@/components/ValidationFreshness';import {DocumentProvider,useDocumentContext,@@ -504,6 +505,7 @@ function AppBody() {<ConnectingBanner /><PageListProvider><SystemDocSubscriber />+ <ValidationFreshness /><NavigationHandler /><ActiveTargetBridgePush /><NewItemShortcutHandler />diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsxindex 30a0a8049..90961452b 100644--- a/packages/app/src/components/DocPanel.dom.test.tsx+++ b/packages/app/src/components/DocPanel.dom.test.tsx@@ -64,6 +64,10 @@ vi.doMock('@/editor/lint-config-client', () => ({vi.doMock('@/editor/useDocDiagnostics', () => ({useDocDiagnostics: () => diagnosticsValue,}));+vi.doMock('@/editor/validation-audit-client', () => ({+ runValidationAudit: async () => null,+ useDocLinkFindings: () => [],+}));// Terminal availability drives the Ask-AI gate — null mirrors the web host.let terminalLaunchValue: unknown = null;vi.doMock('@/components/handoff/TerminalLaunchContext', () => ({diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsxindex 0e57d437d..808c86461 100644--- a/packages/app/src/components/DocPanel.tsx+++ b/packages/app/src/components/DocPanel.tsx@@ -1,13 +1,13 @@import { t } from '@lingui/core/macro';import { Trans, useLingui } from '@lingui/react/macro';import { AlertTriangle, Clock, Link2, ListTree, Network } from 'lucide-react';-import { lazy, Suspense } from 'react';+import { lazy, Suspense, useEffect } from 'react';import { composeLintFixTerminalPaste } from '@/components/handoff/compose-lint-fix-prompt';import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';import { LinksPanel } from '@/components/LinksPanel';import { OutlinePanel } from '@/components/OutlinePanel';-import { ProblemsPanel } from '@/components/ProblemsPanel';+import { type DiagnosticLike, ProblemsPanel } from '@/components/ProblemsPanel';import { TimelineContent } from '@/components/TimelinePanel';import { Badge } from '@/components/ui/badge';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';@@ -16,7 +16,9 @@ import { applyLintFixes, collectFixes } from '@/editor/apply-lint-fix';import { useDocumentContext } from '@/editor/DocumentContext';import { useDocLintConfig } from '@/editor/lint-config-client';import { useDocDiagnostics } from '@/editor/useDocDiagnostics';+import { useDocLinkFindings } from '@/editor/validation-audit-client';import { useSingleFileMode } from '@/lib/single-file-mode';+import { type DocProblemCounts, patchDocValidationSource } from '@/lib/validation-store';export type PanelTab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems';@@ -28,6 +30,16 @@ export const TABS: { id: PanelTab; icon: typeof ListTree }[] = [{ id: 'problems', icon: AlertTriangle },];+function countsOf(diagnostics: readonly { severity: string }[]): DocProblemCounts {+ let errorCount = 0;+ let warningCount = 0;+ for (const diagnostic of diagnostics) {+ if (diagnostic.severity === 'error') errorCount += 1;+ else warningCount += 1;+ }+ return { errorCount, warningCount };+}+/** Localized display label for a doc-panel tab. */function tabLabel(id: PanelTab): string {if (id === 'outline') return t`Outline`;@@ -85,18 +97,39 @@ export function DocPanel({const { activeProvider, activeDocName } = useDocumentContext();const { data: lintConfig } = useDocLintConfig(docName);const lintProvider = activeDocName === docName ? activeProvider : null;- const diagnostics = useDocDiagnostics(lintProvider, lintConfig?.effective ?? null);+ const lintDiagnostics = useDocDiagnostics(lintProvider, lintConfig?.effective ?? null);+ // The doc's broken-link findings ride the SAME scoped audit predicate the+ // project audit runs (one canonical determination); lint stays on the live+ // CRDT read above, which is fresher than the audit's walk.+ const linkFindings = useDocLinkFindings(docName);+ const diagnostics = [...lintDiagnostics, ...linkFindings];+ // Freshness trigger 2: the open doc's shared-store entry tracks its own live+ // counts (lint off the CRDT debounce, links off the scoped audit fetch) so+ // the file tree's tint follows edits without waiting for a project audit.+ // The store no-ops on unchanged counts, so the identity-fresh arrays are+ // cheap dependencies. Skipped while nav is settling (`lintProvider` null) —+ // an empty transient list must not wipe the previous doc's real counts.+ useEffect(() => {+ if (lintProvider === null) return;+ patchDocValidationSource(docName, 'lint', countsOf(lintDiagnostics));+ }, [docName, lintProvider, lintDiagnostics]);+ useEffect(() => {+ if (lintProvider === null) return;+ patchDocValidationSource(docName, 'links', countsOf(linkFindings));+ }, [docName, lintProvider, linkFindings]);// 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]) => {+ const handleFix = (diagnostic: DiagnosticLike) => {if (lintProvider !== null && diagnostic.fixes && diagnostic.fixes.length > 0) {applyLintFixes(lintProvider, diagnostic.fixes);}};+ // Fix-all stays lint-only by construction: only the live lint diagnostics+ // carry deterministic fixes (broken links need content edits).const handleFixAll = () => {if (lintProvider !== null) {- applyLintFixes(lintProvider, collectFixes(diagnostics));+ applyLintFixes(lintProvider, collectFixes(lintDiagnostics));}};// Hand one diagnostic to the docked terminal's agent as a grounded prompt@@ -104,7 +137,7 @@ export function DocPanel({// on web nothing subscribes to the terminal-input event, so the button is// withheld entirely by not passing `onAskAi`.const terminalLaunch = useTerminalLaunch();- const handleAskAi = (diagnostic: (typeof diagnostics)[number]) => {+ const handleAskAi = (diagnostic: DiagnosticLike) => {if (lintProvider === null) return;const source = lintProvider.document.getText('source').toString();const lineText = source.split('\n')[diagnostic.range.start.line];diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex e7b6efef5..653b430df 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -130,6 +130,10 @@ import {resolveKeyboardDeleteTargets,selectedTreePathsToDeleteTargets,} from '@/components/file-tree-path-helpers';+import {+ applyProblemIndicators,+ FILE_TREE_PROBLEM_CSS,+} from '@/components/file-tree-problem-indicators';import {applyRenameInputAffordance,FILE_TREE_RENAME_INPUT_CSS,@@ -227,6 +231,7 @@ import {} from '@/lib/show-all-stream';import { OK_SIDEBAR_DRAG_MIME, serializeSidebarDragPayload } from '@/lib/sidebar-drag';import { cn } from '@/lib/utils';+import { getValidationSnapshot, subscribeToValidationStore } from '@/lib/validation-store';import { joinWorkspacePath } from '@/lib/workspace-paths';import { mergeRootEntriesAdditive, spliceLazyFolderChildren } from './file-tree-merge';import { OpenInAgentContextSubmenu } from './handoff/OpenInAgentContextSubmenu';@@ -393,7 +398,7 @@ const FILE_TREE_CREATION_CLEARED_CSS = `// markdown icon stays gray when its row is selected. The full styling block lives// alongside the badge-injection processor in file-tree-extension-badge.ts so the// CSS + DOM-mutation contract stays in one place.-const FILE_TREE_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_RENAME_INPUT_CSS}\n${FILE_TREE_ROOT_DROP_CSS}\n${FILE_TREE_EXTERNAL_FILE_DROP_CSS}\n${FILE_TREE_CREATION_CLEARED_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;+const FILE_TREE_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_PROBLEM_CSS}\n${FILE_TREE_RENAME_INPUT_CSS}\n${FILE_TREE_ROOT_DROP_CSS}\n${FILE_TREE_EXTERNAL_FILE_DROP_CSS}\n${FILE_TREE_CREATION_CLEARED_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;interface PendingCreate {kind: 'file' | 'folder';@@ -3407,6 +3412,39 @@ export function FileTree({return () => observer.disconnect();}, [loading, documents.length]);+ // Tint + badge rows whose docs have validation problems, from the shared+ // validation store. Same shadow-root + MutationObserver pattern as the+ // extension badge above, plus a store subscription so tint updates arrive+ // without a DOM mutation (e.g. a project audit landing while the tree is+ // idle). Our own attribute writes are outside the `data-item-path` filter+ // and the badge write is value-gated, so the observer stays quiescent.+ const problemIndicatorsEnabled = merged?.validation?.fileTreeIndicators !== false;+ useEffect(() => {+ if (loading || documents.length === 0) return;+ const shadow = fileTreeHostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;+ if (!shadow) return;+ if (!problemIndicatorsEnabled) {+ // One clearing pass strips any tint/badges left from before the toggle+ // flipped off; no observer or store subscription while disabled.+ applyProblemIndicators(shadow, new Map());+ return;+ }+ const apply = () => applyProblemIndicators(shadow, getValidationSnapshot());+ apply();+ const observer = new MutationObserver(apply);+ observer.observe(shadow, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['data-item-path'],+ });+ const unsubscribe = subscribeToValidationStore(apply);+ return () => {+ observer.disconnect();+ unsubscribe();+ };+ }, [loading, documents.length, problemIndicatorsEnabled]);+// Select Pierre's rename-input stem while keeping the extension visible and// editable. Kept separate from the badge observer because the watched event// (childList: the rename input mounting) is structurally different from thediff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsxindex 6681bb088..bcc780537 100644--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx@@ -7,7 +7,7 @@* affordance, and click-navigates to the offending doc by hash.*/-import type { LintAuditResponse, LintDiagnostic } from '@inkeep/open-knowledge-core';+import type { LintDiagnostic, ValidationAuditResponse } from '@inkeep/open-knowledge-core';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';@@ -32,20 +32,17 @@ vi.doMock('@lingui/core/macro', () => linguiMacroMock);vi.doMock('@lingui/react/macro', () => linguiMacroMock);let auditCalls = 0;-let runLintAuditImpl: () => Promise<LintAuditResponse | null> = async () => null;+let runLintAuditImpl: () => Promise<ValidationAuditResponse | null> = async () => null;let fixLintDocCalls: string[] = [];let fixLintDocImpl: (docName: string) => Promise<{ ok: boolean; errorDetail?: string | null }> =async () => ({ ok: true });const toastError = vi.fn((_message: string) => {});-vi.doMock('sonner', () => ({ toast: { error: toastError } }));+const toastSuccess = vi.fn((_message: string) => {});+vi.doMock('sonner', () => ({ toast: { error: toastError, success: toastSuccess } }));vi.doMock('@/editor/lint-config-client', () => ({emitLintConfigChanged: () => {},subscribeToLintConfigChanged: () => () => {},- runLintAudit: () => {- auditCalls += 1;- return runLintAuditImpl();- },fixLintDoc: (docName: string) => {fixLintDocCalls.push(docName);return fixLintDocImpl(docName);@@ -55,6 +52,35 @@ vi.doMock('@/editor/lint-config-client', () => ({fetchEffectiveLintConfig: async () => null,writeMarkdownlintRule: async () => ({ ok: false, errorDetail: null }),}));+// The panel's project scope now consumes the unified audit plane.+vi.doMock('@/editor/validation-audit-client', () => ({+ runValidationAudit: () => {+ auditCalls += 1;+ return runLintAuditImpl();+ },+ useDocLinkFindings: () => [],+}));+// Page-list context for the dead-link "Create page" one-shot. `addPage` is the+// only member the panel touches.+const addPageCalls: string[] = [];+vi.doMock('@/components/PageListContext', () => ({+ useOptionalPageList: () => ({ addPage: (docName: string) => addPageCalls.push(docName) }),+}));+let createPageCalls: { initialDir: string; suggestedName: string }[] = [];+let createPageImpl: (seed: { initialDir: string; suggestedName: string }) => Promise<{+ docName: string;+}> = async (seed) => ({ docName: seed.suggestedName });+vi.doMock('@/lib/create-page', () => ({+ createPageFromSeedAndUpdate: async (+ seed: { initialDir: string; suggestedName: string },+ options: { addPage: (docName: string) => void },+ ) => {+ createPageCalls.push(seed);+ const created = await createPageImpl(seed);+ options.addPage(created.docName);+ return created;+ },+}));const { ProblemsPanel, LINT_NAV_EVENT } = await import('./ProblemsPanel');// The real registry, deliberately unmocked: the tests assert the banked intent@@ -79,16 +105,38 @@ function diag(over: Partial<LintDiagnostic> & { line?: number; column?: number }};}-function auditResult(over: Partial<LintAuditResponse> = {}): LintAuditResponse {+function auditResult(over: Partial<ValidationAuditResponse> = {}): ValidationAuditResponse {return { files: [], fileCount: 3, errorCount: 0, warningCount: 0, warnings: [], ...over };}+/** A dead-link diagnostic as the links validator reports it on the wire. */+function linkDiag(+ over: Partial<LintDiagnostic> & { line?: number } = {},+): LintDiagnostic & { linkTarget: string } {+ return {+ ...diag({+ severity: 'warning',+ code: 'dead-link',+ message: 'Link target "ghost" does not resolve to an existing document.',+ ...over,+ // The wire's `source` is any validator id; the in-process type is narrower,+ // so route around it for the fixture.+ source: 'links' as LintDiagnostic['source'],+ }),+ linkTarget: 'ghost',+ };+}+beforeEach(() => {auditCalls = 0;runLintAuditImpl = async () => null;fixLintDocCalls = [];fixLintDocImpl = async () => ({ ok: true });+ createPageCalls = [];+ createPageImpl = async (seed) => ({ docName: seed.suggestedName });+ addPageCalls.length = 0;toastError.mockClear();+ toastSuccess.mockClear();});afterEach(() => {@@ -243,6 +291,55 @@ describe('ProblemsPanel', () => {}});+ test('every row carries a source tag: lint for validators, link for dead links', () => {+ render(+ <ProblemsPanel docName="notes" diagnostics={[diag({ line: 2 }), linkDiag({ line: 5 })]} />,+ );+ const tags = screen.getAllByTestId('problems-source-tag');+ expect(tags).toHaveLength(2);+ expect(tags[0]?.textContent).toBe('lint');+ expect(tags[1]?.textContent).toBe('link');+ });++ test('a dead-link row offers the one-shot Create page action; lint rows do not', async () => {+ render(<ProblemsPanel docName="notes" diagnostics={[linkDiag({ line: 5 }), diag({})]} />);+ // Exactly one Create button — the lint row gets none.+ const createButtons = screen.getAllByTestId('problems-create-page');+ expect(createButtons).toHaveLength(1);++ fireEvent.click(createButtons[0] as HTMLElement);+ await waitFor(() =>+ expect(createPageCalls).toEqual([{ initialDir: '', suggestedName: 'ghost' }]),+ );+ // The created page lands in the page list (same flow as the Links panel).+ expect(addPageCalls).toEqual(['ghost']);+ });++ test('the create action is never counted by Fix all', () => {+ render(+ <ProblemsPanel docName="notes" diagnostics={[linkDiag({})]} onFixAll={vi.fn(() => {})} />,+ );+ // A dead link is not deterministically fixable — the Fix all label counts 0.+ const button = screen.getByTestId('problems-fix-all') as HTMLButtonElement;+ expect(button.disabled).toBe(true);+ expect(button.textContent).toContain('(0)');+ });++ test('a dead-link row click-jumps to its 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={[linkDiag({ line: 5 })]} />);+ fireEvent.click(screen.getByRole('button', { name: /does not resolve/ }));+ expect(received).toEqual({ line: 5, column: 1 });+ } 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'));@@ -294,6 +391,50 @@ describe('ProblemsPanel — project scope', () => {expect(screen.getByTestId('problems-audit-summary').textContent).toContain('3 warnings');});+ test('project groups mix lint and link findings for one file, source-tagged', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ files: [+ {+ file: 'guides/setup.md',+ diagnostics: [diag({ line: 4 }), linkDiag({ line: 9 })],+ },+ ],+ fileCount: 4,+ errorCount: 1,+ warningCount: 1,+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());++ const tags = screen.getAllByTestId('problems-source-tag');+ expect(tags.map((tag) => tag.textContent)).toEqual(['lint', 'link']);+ // The rollup summary carries the merged plane's counts.+ expect(screen.getByTestId('problems-audit-summary').textContent).toContain('1 error');+ expect(screen.getByTestId('problems-audit-summary').textContent).toContain('1 warning');+ });++ test('a project-scope dead-link row creates its target and re-audits the plane', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ files: [{ file: 'guides/setup.md', diagnostics: [linkDiag({ line: 3 })] }],+ fileCount: 2,+ warningCount: 1,+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);+ fireEvent.click(screen.getByTestId('panel-scope-project'));+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());+ expect(auditCalls).toBe(1);++ fireEvent.click(screen.getByTestId('problems-create-page'));+ await waitFor(() =>+ expect(createPageCalls).toEqual([{ initialDir: '', suggestedName: 'ghost' }]),+ );+ // A loaded snapshot is stale truth after the create — the panel re-audits.+ await waitFor(() => expect(auditCalls).toBe(2));+ });+test('the cached result is reused when toggling scopes; refresh re-fetches', async () => {runLintAuditImpl = async () =>auditResult({ files: [{ file: 'first.md', diagnostics: [diag({})] }] });@@ -318,7 +459,7 @@ describe('ProblemsPanel — project scope', () => {});test('a pending audit shows the loading skeleton with the refresh disabled', async () => {- let resolveAudit: (value: LintAuditResponse | null) => void = () => {};+ let resolveAudit: (value: ValidationAuditResponse | null) => void = () => {};runLintAuditImpl = () =>new Promise((resolve) => {resolveAudit = resolve;diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsxindex 1ccc76477..d67b324c5 100644--- a/packages/app/src/components/ProblemsPanel.tsx+++ b/packages/app/src/components/ProblemsPanel.tsx@@ -1,16 +1,19 @@// 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 type { ValidationAuditResponse, ValidationDocResult } from '@inkeep/open-knowledge-core';import { Plural, Trans, useLingui } from '@lingui/react/macro';import {AlertCircle,AlertTriangle,ChevronRight,+ FilePlus2,+ Link2,RefreshCw,Sparkles,Wrench,} from 'lucide-react';import { type ReactNode, useEffect, useRef, useState } from 'react';import { toast } from 'sonner';+import { useOptionalPageList } from '@/components/PageListContext';import { type PanelScope, PanelScopeHeader } from '@/components/PanelScopeHeader';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -25,10 +28,13 @@ import {PanelTitle,} from '@/components/ui/panel';import { Skeleton } from '@/components/ui/skeleton';-import { fixLintDoc, runLintAudit } from '@/editor/lint-config-client';+import { fixLintDoc } from '@/editor/lint-config-client';import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';+import { runValidationAudit } from '@/editor/validation-audit-client';+import { createPageFromSeedAndUpdate } from '@/lib/create-page';import { filePathToDocName, hashFromDocName } from '@/lib/doc-hash';import { cn } from '@/lib/utils';+import { replaceValidationFromAudit } from '@/lib/validation-store';/** Jump-to-line intent dispatched when a problem row is clicked in source mode. */export interface LintNavDetail {@@ -41,12 +47,12 @@ export interface LintNavDetail {export const LINT_NAV_EVENT = 'open-knowledge:lint-nav';/**- * Wire-loose diagnostic shape from the audit response. The engine's+ * Wire-loose diagnostic shape from the unified 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];+export type DiagnosticLike = ValidationDocResult['diagnostics'][number];/** Stable sort key: line, then column. */function compareDiagnostics(a: DiagnosticLike, b: DiagnosticLike): number {@@ -66,15 +72,16 @@ function lintNavDetailOf(diagnostic: DiagnosticLike): LintNavDetail {type ProjectAuditState =| { status: 'idle' }| { status: 'loading' }- | { status: 'loaded'; result: LintAuditResponse }+ | { status: 'loaded'; result: ValidationAuditResponse }| { status: 'failed' };-/** Message line + `source/code · line` subline shared by doc- and project-scope rows. */+/** Message line + source chip + `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;+ const isLink = diagnostic.source === 'links';return (<><span className="flex items-start gap-1.5 text-sm">@@ -87,8 +94,30 @@ function DiagnosticRowBody({ diagnostic }: { diagnostic: DiagnosticLike }) {/><span className="text-foreground">{diagnostic.message}</span></span>- <span className="ps-5 font-mono text-xs text-muted-foreground">- {flatId} · {t`line ${displayLine}`}+ <span className="flex items-center gap-1.5 ps-5 font-mono text-xs text-muted-foreground">+ {/* Source tag: the unified plane mixes validators per file, so every+ row names its category at a glance (the flatId spells the full+ validator id for the detail-oriented). */}+ <Badge+ variant="gray"+ data-testid="problems-source-tag"+ className={cn(+ 'h-4 shrink-0 px-1 font-sans text-[10px] uppercase leading-none',+ isLink && 'gap-0.5',+ )}+ >+ {isLink ? (+ <>+ <Link2 aria-hidden="true" className="size-2.5" />+ <Trans>link</Trans>+ </>+ ) : (+ <Trans>lint</Trans>+ )}+ </Badge>+ <span className="min-w-0 truncate">+ {flatId} · {t`line ${displayLine}`}+ </span></span></>);@@ -103,6 +132,40 @@ function countFixable(diagnostics: readonly DiagnosticLike[]): number {return diagnostics.reduce((n, d) => n + ((d.fixes?.length ?? 0) > 0 ? 1 : 0), 0);}+/**+ * One-shot "create the missing page" action for a dead-link row — the same+ * action as the Links panel's amber missing-page affordance, surfaced where+ * the problem is listed. Deliberately outside Fix all (a broken link may be a+ * typo; bulk-creating targets would mint duplicate files).+ */+function CreatePageButton({+ target,+ creating,+ disabled,+ onCreate,+}: {+ target: string;+ creating: boolean;+ disabled: boolean;+ onCreate: () => void;+}) {+ const { t } = useLingui();+ return (+ <Button+ size="sm"+ variant="ghost"+ className="h-6 shrink-0 px-2 text-xs"+ disabled={disabled}+ onClick={onCreate}+ aria-label={t`Create missing page ${target}`}+ data-testid="problems-create-page"+ >+ <FilePlus2 aria-hidden="true" className="size-3" />+ {creating ? <Trans>Creating</Trans> : <Trans>Create page</Trans>}+ </Button>+ );+}+/** "Fix all" action shared by both scopes — same look, same position in the* actions row; only the click handler's blast radius differs. The label* carries the deterministically-fixable problem count so the click's effect@@ -157,10 +220,12 @@ export function ProblemsPanel({onAskAi,}: {docName: string;- diagnostics: LintDiagnostic[];+ /** Live lint diagnostics for the open doc PLUS its broken-link findings —+ * wire-loose so both the in-process lint shape and the audit plane fit. */+ diagnostics: DiagnosticLike[];/** 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;+ onFix?: (diagnostic: DiagnosticLike) => void;/** Apply every fixable diagnostic's auto-fix in this doc. When absent, the* doc-scope Fix all button is not rendered. */onFixAll?: () => void;@@ -168,12 +233,17 @@ export function ProblemsPanel({* prompt. Desktop-only — absent on web, where rows render no Ask AI button.* Offered on every row, fixable or not: AI is most useful exactly where no* deterministic fix exists. */- onAskAi?: (diagnostic: LintDiagnostic) => void;+ onAskAi?: (diagnostic: DiagnosticLike) => void;}) {const { t } = useLingui();const [scope, setScope] = useState<PanelScope>('doc');const [audit, setAudit] = useState<ProjectAuditState>({ status: 'idle' });const [projectFixing, setProjectFixing] = useState<{ done: number; total: number } | null>(null);+ // The dead-link "Create page" one-shot (target being created, else null).+ // Optional context: the panel is always under PageListProvider in the app;+ // the null branch only serves bare unit harnesses (create renders disabled).+ const pageList = useOptionalPageList();+ const [creatingTarget, setCreatingTarget] = useState<string | null>(null);// Tracks whether the panel is still mounted so the async project sweep can// stop early instead of posting fixes and setState-ing into an unmounted tree.const mountedRef = useRef(true);@@ -186,9 +256,44 @@ export function ProblemsPanel({const sorted = [...diagnostics].sort(compareDiagnostics);+ /**+ * One-shot fix for a dead link: create the missing target page (the same+ * action as the Links panel's amber "missing page" affordance). Deliberately+ * NOT part of Fix all — a broken link may be a typo, and bulk-creating+ * targets would silently mint duplicate files.+ */+ async function createLinkTarget(diagnostic: DiagnosticLike) {+ const target = diagnostic.linkTarget;+ if (target === undefined || creatingTarget !== null || pageList === null) return;+ setCreatingTarget(target);+ // No try/finally: the React Compiler cannot lower a finalizer clause, so+ // both exits clear the creating flag explicitly.+ try {+ await createPageFromSeedAndUpdate(+ { initialDir: '', suggestedName: target },+ { addPage: pageList.addPage },+ );+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t`Failed to create page`);+ if (mountedRef.current) setCreatingTarget(null);+ return;+ }+ toast.success(t`Created ${target}`);+ if (mountedRef.current) setCreatingTarget(null);+ // The doc scope heals itself (the create emits the backlinks relay the+ // link-findings hook listens to); a loaded project snapshot is stale+ // truth, so refresh it in place.+ if (mountedRef.current && audit.status === 'loaded') await loadAudit();+ }+async function loadAudit() {setAudit({ status: 'loading' });- const result = await runLintAudit();+ const result = await runValidationAudit();+ // A successful whole-project audit is full-plane truth — refresh the+ // shared validation store (freshness trigger 1) so the file tree's tints+ // update in the same pass. Deliberately BEFORE the mounted guard: the+ // store outlives this panel, and the fetch already completed.+ if (result !== null) replaceValidationFromAudit(result.files);// Match the sweep's mounted guard: don't setState into an unmounted tree// (loadAudit is awaited from the sweep, the refresh button, and scope// activation).@@ -306,6 +411,7 @@ export function ProblemsPanel({{sorted.map((diagnostic) => {const displayLine = diagnostic.range.start.line + 1;const fixable = onFix !== undefined && (diagnostic.fixes?.length ?? 0) > 0;+ const canCreate = diagnostic.linkTarget !== undefined && pageList !== null;const flatId = `${diagnostic.source}/${diagnostic.code}`;return (<li@@ -324,12 +430,20 @@ export function ProblemsPanel({><DiagnosticRowBody diagnostic={diagnostic} /></button>- {fixable || onAskAi !== undefined ? (+ {fixable || onAskAi !== undefined || canCreate ? (// Bottom-right, revealed on hover/focus. `bg-muted`// matches the row's own hover background so it cleanly// occludes the `source/code · line` subline underneath// if a long id would otherwise run beneath it.<div className="absolute bottom-1 right-1 flex items-center gap-1 rounded bg-muted opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 motion-reduce:transition-none">+ {canCreate ? (+ <CreatePageButton+ target={diagnostic.linkTarget ?? ''}+ creating={creatingTarget === diagnostic.linkTarget}+ disabled={creatingTarget !== null}+ onCreate={() => void createLinkTarget(diagnostic)}+ />+ ) : null}{fixable ? (<Buttonsize="sm"@@ -373,6 +487,8 @@ export function ProblemsPanel({fixableCount={projectFixableFiles.reduce((n, f) => n + countFixable(f.diagnostics), 0)}fixing={projectFixing}onFixAll={() => void fixAllProjectFiles()}+ onCreateTarget={pageList !== null ? (d) => void createLinkTarget(d) : undefined}+ creatingTarget={creatingTarget}/>)}</Panel>@@ -386,6 +502,8 @@ function ProjectAuditBody({fixableCount,fixing,onFixAll,+ onCreateTarget,+ creatingTarget,}: {audit: ProjectAuditState;onRefresh: () => void;@@ -396,6 +514,9 @@ function ProjectAuditBody({/** Sweep progress while a project Fix all is running, else null. */fixing: { done: number; total: number } | null;onFixAll: () => void;+ /** Create a dead-link row's missing target page; absent in bare harnesses. */+ onCreateTarget?: (diagnostic: DiagnosticLike) => void;+ creatingTarget: string | null;}) {const { t } = useLingui();const loading = audit.status === 'loading' || audit.status === 'idle';@@ -472,7 +593,12 @@ function ProjectAuditBody({)}{audit.status === 'loaded' && (- <ProjectAuditResults result={audit.result} onNavigate={onNavigate} />+ <ProjectAuditResults+ result={audit.result}+ onNavigate={onNavigate}+ onCreateTarget={onCreateTarget}+ creatingTarget={creatingTarget}+ />)}</PanelBody>);@@ -481,9 +607,13 @@ function ProjectAuditBody({function ProjectAuditResults({result,onNavigate,+ onCreateTarget,+ creatingTarget,}: {- result: LintAuditResponse;+ result: ValidationAuditResponse;onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;+ onCreateTarget?: (diagnostic: DiagnosticLike) => void;+ creatingTarget: string | null;}) {const { t } = useLingui();return (@@ -512,7 +642,13 @@ function ProjectAuditResults({</PanelEmpty>) : (result.files.map((file) => (- <ProjectFileGroup key={file.file} file={file} onNavigate={onNavigate} />+ <ProjectFileGroup+ key={file.file}+ file={file}+ onNavigate={onNavigate}+ onCreateTarget={onCreateTarget}+ creatingTarget={creatingTarget}+ />)))}</div>@@ -522,9 +658,13 @@ function ProjectAuditResults({function ProjectFileGroup({file,onNavigate,+ onCreateTarget,+ creatingTarget,}: {- file: LintDocResult;+ file: ValidationDocResult;onNavigate: (filePath: string, diagnostic: DiagnosticLike) => void;+ onCreateTarget?: (diagnostic: DiagnosticLike) => void;+ creatingTarget: string | null;}) {const { t } = useLingui();const sorted = [...file.diagnostics].sort(compareDiagnostics);@@ -549,16 +689,32 @@ function ProjectFileGroup({<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;+ const canCreate = diagnostic.linkTarget !== undefined && onCreateTarget !== undefined;return (- <li key={diagnosticKey(diagnostic)}>+ <li+ key={diagnosticKey(diagnostic)}+ className="group relative rounded transition-colors hover:bg-muted"+ ><buttontype="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"+ className="flex w-full cursor-pointer flex-col gap-0.5 rounded px-2 py-1.5 text-left"title={t`Go to line ${displayLine} in ${file.file}`}><DiagnosticRowBody diagnostic={diagnostic} /></button>+ {canCreate ? (+ // Same hover-revealed overlay contract as the doc scope's+ // Fix / Ask AI actions.+ <div className="absolute bottom-1 right-1 flex items-center gap-1 rounded bg-muted opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 motion-reduce:transition-none">+ <CreatePageButton+ target={diagnostic.linkTarget ?? ''}+ creating={creatingTarget === diagnostic.linkTarget}+ disabled={creatingTarget !== null}+ onCreate={() => onCreateTarget?.(diagnostic)}+ />+ </div>+ ) : null}</li>);})}diff --git a/packages/app/src/components/SystemDocSubscriber.tsx b/packages/app/src/components/SystemDocSubscriber.tsxindex dcf6bde96..2b01d02e1 100644--- a/packages/app/src/components/SystemDocSubscriber.tsx+++ b/packages/app/src/components/SystemDocSubscriber.tsx@@ -6,7 +6,11 @@ import { useDocumentContext } from '@/editor/DocumentContext';import { dispatchCC1Stateless, SYSTEM_DOC_NAME } from '@/lib/cc1';import { emitConfigIgnoreNestedError } from '@/lib/config-ignore-nested-error-events';import { emitConfigValidationRejected } from '@/lib/config-validation-events';-import { emitDocumentsChanged, subscribeToDocumentsChanged } from '@/lib/documents-events';+import {+ emitDocPersisted,+ emitDocumentsChanged,+ subscribeToDocumentsChanged,+} from '@/lib/documents-events';import { createSyncedReconnectGate } from '@/lib/server-info-refresh';export function SystemDocSubscriber() {@@ -66,6 +70,10 @@ export function SystemDocSubscriber() {},onDiskAck: (p) => {handlersRef.current.observeDiskAck(p.docName, p.sv);+ // Relay the docName for validation freshness: disk-ack is the one+ // per-doc CC1 channel, so it is the "this doc changed" signal the+ // per-doc re-validate keys off.+ emitDocPersisted(p.docName);},onDerivedView: (p) => {emitDocumentsChanged([p.ch]);diff --git a/packages/app/src/components/ValidationFreshness.dom.test.tsx b/packages/app/src/components/ValidationFreshness.dom.test.tsxnew file mode 100644index 000000000..4afe99aba--- /dev/null+++ b/packages/app/src/components/ValidationFreshness.dom.test.tsx@@ -0,0 +1,147 @@+/**+ * Behavioral tests for freshness trigger 3: a doc-persisted relay (CC1+ * `disk-ack` docName) re-validates JUST that doc via the scoped audit and+ * patches its shared-store entry — reserved/mermaid docNames are skipped, and+ * bursts debounce to one trailing fetch per doc.+ */++import type { ValidationAuditResponse } from '@inkeep/open-knowledge-core';+import { cleanup, render, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { emitDocPersisted } from '@/lib/documents-events';+import { getValidationSnapshot, resetValidationStoreForTest } from '@/lib/validation-store';++// Config context gates the whole subscriber (`validation.fileTreeIndicators`).+let mergedConfigValue: { validation?: { fileTreeIndicators?: boolean } } | null = null;+vi.doMock('@/lib/config-provider', () => ({+ useConfigContext: () => ({ merged: mergedConfigValue }),+}));++const { ValidationFreshness } = await import('./ValidationFreshness');++const origFetch = globalThis.fetch;+let fetchUrls: string[] = [];+let fetchBody: ValidationAuditResponse = {+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [],+};++beforeEach(() => {+ resetValidationStoreForTest();+ mergedConfigValue = null;+ fetchUrls = [];+ globalThis.fetch = (async (url: RequestInfo | URL) => {+ fetchUrls.push(String(url));+ return new Response(JSON.stringify(fetchBody), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+});++afterEach(() => {+ globalThis.fetch = origFetch;+ cleanup();+});++describe('ValidationFreshness', () => {+ test('a persisted doc is re-validated alone and its store entry patched', async () => {+ fetchBody = {+ files: [+ {+ file: 'guides/setup.md',+ diagnostics: [+ {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 0 } },+ severity: 'error',+ source: 'links',+ code: 'dead-link',+ message: 'Link target "ghost" does not resolve to an existing document.',+ },+ ],+ },+ ],+ fileCount: 1,+ errorCount: 1,+ warningCount: 0,+ warnings: [],+ };+ render(<ValidationFreshness />);+ emitDocPersisted('guides/setup');++ await waitFor(+ () =>+ expect(getValidationSnapshot().get('guides/setup')).toEqual({+ errorCount: 1,+ warningCount: 0,+ }),+ { timeout: 3000 },+ );+ expect(fetchUrls).toEqual(['/api/audit?doc=guides%2Fsetup']);+ });++ test('a burst of acks for one doc coalesces to one trailing fetch', async () => {+ render(<ValidationFreshness />);+ emitDocPersisted('notes');+ emitDocPersisted('notes');+ emitDocPersisted('notes');++ await waitFor(() => expect(fetchUrls).toHaveLength(1), { timeout: 3000 });+ // Trailing-edge only — give the window a beat to prove no extra fetches land.+ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(fetchUrls).toEqual(['/api/audit?doc=notes']);+ });++ test('reserved and mermaid docNames are skipped', async () => {+ render(<ValidationFreshness />);+ emitDocPersisted('__config__/project');+ emitDocPersisted('__system__');+ emitDocPersisted('assets/flow.mmd');+ emitDocPersisted('diagrams/arch.mermaid');++ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(fetchUrls).toEqual([]);+ });++ test('the subscriber is inert when the project turns file-tree indicators off', async () => {+ mergedConfigValue = { validation: { fileTreeIndicators: false } };+ render(<ValidationFreshness />);+ emitDocPersisted('notes');++ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(fetchUrls).toEqual([]);+ });++ test('a healed doc is dropped from the snapshot on its next re-validate', async () => {+ render(<ValidationFreshness />);+ fetchBody = {+ files: [+ {+ file: 'a.md',+ diagnostics: [+ {+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ },+ ],+ },+ ],+ fileCount: 1,+ errorCount: 0,+ warningCount: 1,+ warnings: [],+ };+ emitDocPersisted('a');+ await waitFor(() => expect(getValidationSnapshot().has('a')).toBe(true), { timeout: 3000 });++ fetchBody = { files: [], fileCount: 1, errorCount: 0, warningCount: 0, warnings: [] };+ emitDocPersisted('a');+ await waitFor(() => expect(getValidationSnapshot().has('a')).toBe(false), { timeout: 3000 });+ });+});diff --git a/packages/app/src/components/ValidationFreshness.tsx b/packages/app/src/components/ValidationFreshness.tsxnew file mode 100644index 000000000..65f4078c1--- /dev/null+++ b/packages/app/src/components/ValidationFreshness.tsx@@ -0,0 +1,78 @@+/**+ * Freshness trigger 3 of the shared validation store: when a doc's bytes reach+ * disk (CC1 `disk-ack`, relayed as the doc-persisted event), re-validate JUST+ * that doc via the scoped audit and patch its store entry. This heals the+ * silent false-negative where an agent writes a broken link (or a lint+ * problem) into a document nobody has open — its tree tint updates without a+ * whole-project walk.+ *+ * Debounced per doc: persistence flushes ack in bursts during active writing;+ * one trailing re-validate per doc per burst is enough for a tree tint.+ */++import { useEffect } from 'react';+import { runValidationAudit } from '@/editor/validation-audit-client';+import { useConfigContext } from '@/lib/config-provider';+import { filePathToDocName } from '@/lib/doc-hash';+import { subscribeToDocPersisted } from '@/lib/documents-events';+import { patchDocValidationFromAudit } from '@/lib/validation-store';++const REVALIDATE_DEBOUNCE_MS = 500;++/**+ * DocNames the per-doc re-validate skips: reserved trees (`__system__`,+ * `__config__/…`, `__skill__/…`, `__template__/…`, `__local__/…`, `__user__/…`)+ * are not content docs, and extension-retaining Mermaid docs (`.mmd` /+ * `.mermaid`) have no markdown plane to audit.+ */+function isAuditableDocName(docName: string): boolean {+ return !docName.startsWith('__') && !/\.(mmd|mermaid)$/i.test(docName);+}++export function ValidationFreshness() {+ // The per-doc re-validate exists to keep the file tree's indicators fresh;+ // when the project turns those off (`validation.fileTreeIndicators`), skip+ // the background work entirely instead of writing to a store nothing reads.+ const { merged } = useConfigContext();+ const indicatorsEnabled = merged?.validation?.fileTreeIndicators !== false;++ useEffect(() => {+ if (!indicatorsEnabled) return;+ const timers = new Map<string, ReturnType<typeof setTimeout>>();+ let disposed = false;++ const revalidate = (docName: string) => {+ void runValidationAudit({ kind: 'doc', docName }).then((result) => {+ // A failed scoped audit (server hiccup) keeps the previous entry —+ // stale beats wrongly-clean.+ if (disposed || result === null) return;+ const diagnostics = result.files+ .filter((file) => filePathToDocName(file.file) === docName)+ .flatMap((file) => file.diagnostics);+ patchDocValidationFromAudit(docName, diagnostics);+ });+ };++ const unsubscribe = subscribeToDocPersisted((docName) => {+ if (!isAuditableDocName(docName)) return;+ const existing = timers.get(docName);+ if (existing !== undefined) clearTimeout(existing);+ timers.set(+ docName,+ setTimeout(() => {+ timers.delete(docName);+ revalidate(docName);+ }, REVALIDATE_DEBOUNCE_MS),+ );+ });++ return () => {+ disposed = true;+ unsubscribe();+ for (const timer of timers.values()) clearTimeout(timer);+ timers.clear();+ };+ }, [indicatorsEnabled]);++ return null;+}diff --git a/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx b/packages/app/src/components/file-tree-problem-indicators.dom.test.tsxnew file mode 100644index 000000000..6cd9e5cd6--- /dev/null+++ b/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx@@ -0,0 +1,109 @@+/**+ * DOM test for the problem-indicator processor. Mirrors the extension-badge+ * test's approach: build Pierre-shaped rows by hand and exercise+ * `applyProblemIndicators` directly against a counts snapshot. Covers the+ * decision layer — tint attribute + count on problem rows, nothing on clean+ * rows, healing removal, idempotence — while the real shadow-root color is+ * the e2e's job (jsdom doesn't paint unsafeCSS).+ */++import { cleanup } from '@testing-library/react';+import { afterEach, describe, expect, test } from 'vitest';+import {+ applyProblemIndicators,+ OK_PROBLEM_BADGE_ATTR,+ OK_PROBLEM_ROW_ATTR,+} from './file-tree-problem-indicators';++afterEach(() => {+ cleanup();+});++function buildRow(path: string): HTMLElement {+ const row = document.createElement('div');+ row.setAttribute('data-type', 'item');+ row.setAttribute('data-item-path', path);+ const contentSection = document.createElement('div');+ contentSection.setAttribute('data-item-section', 'content');+ contentSection.textContent = path;+ row.appendChild(contentSection);+ const actionSection = document.createElement('div');+ actionSection.setAttribute('data-item-section', 'action');+ row.appendChild(actionSection);+ return row;+}++function buildTree(paths: string[]): { root: HTMLElement; rows: Map<string, HTMLElement> } {+ const root = document.createElement('div');+ const rows = new Map<string, HTMLElement>();+ for (const path of paths) {+ const row = buildRow(path);+ root.appendChild(row);+ rows.set(path, row);+ }+ return { root, rows };+}++describe('applyProblemIndicators', () => {+ test('tints error red-severity, warning yellow-severity, with total counts', () => {+ const { root, rows } = buildTree(['a.md', 'guides/b.md', 'clean.md']);+ applyProblemIndicators(+ root,+ new Map([+ ['a', { errorCount: 2, warningCount: 1 }],+ ['guides/b', { errorCount: 0, warningCount: 4 }],+ ]),+ );++ const errorRow = rows.get('a.md');+ expect(errorRow?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('error');+ expect(errorRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('3');++ const warningRow = rows.get('guides/b.md');+ expect(warningRow?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('warning');+ expect(warningRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('4');++ const cleanRow = rows.get('clean.md');+ expect(cleanRow?.hasAttribute(OK_PROBLEM_ROW_ATTR)).toBe(false);+ expect(cleanRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)).toBeNull();+ });++ test('healed rows lose tint and badge on the next apply', () => {+ const { root, rows } = buildTree(['a.md']);+ applyProblemIndicators(root, new Map([['a', { errorCount: 1, warningCount: 0 }]]));+ expect(rows.get('a.md')?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('error');++ applyProblemIndicators(root, new Map());+ expect(rows.get('a.md')?.hasAttribute(OK_PROBLEM_ROW_ATTR)).toBe(false);+ expect(rows.get('a.md')?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)).toBeNull();+ });++ test('folder rows are never tinted even when a same-named doc has problems', () => {+ const { root, rows } = buildTree(['guides/']);+ applyProblemIndicators(root, new Map([['guides', { errorCount: 1, warningCount: 0 }]]));+ expect(rows.get('guides/')?.hasAttribute(OK_PROBLEM_ROW_ATTR)).toBe(false);+ });++ test('severity downgrades in place when errors heal but warnings remain', () => {+ const { root, rows } = buildTree(['a.md']);+ applyProblemIndicators(root, new Map([['a', { errorCount: 1, warningCount: 2 }]]));+ applyProblemIndicators(root, new Map([['a', { errorCount: 0, warningCount: 2 }]]));+ const row = rows.get('a.md');+ expect(row?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('warning');+ expect(row?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('2');+ });++ test('repeated applies are idempotent (one badge, same attrs)', () => {+ const { root, rows } = buildTree(['a.md']);+ const counts = new Map([['a', { errorCount: 0, warningCount: 1 }]]);+ applyProblemIndicators(root, counts);+ applyProblemIndicators(root, counts);+ expect(rows.get('a.md')?.querySelectorAll(`[${OK_PROBLEM_BADGE_ATTR}]`)).toHaveLength(1);+ });++ test('counts above 99 clamp the badge label', () => {+ const { root, rows } = buildTree(['a.md']);+ applyProblemIndicators(root, new Map([['a', { errorCount: 100, warningCount: 50 }]]));+ expect(rows.get('a.md')?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('99+');+ });+});diff --git a/packages/app/src/components/file-tree-problem-indicators.ts b/packages/app/src/components/file-tree-problem-indicators.tsnew file mode 100644index 000000000..fa387fcbe--- /dev/null+++ b/packages/app/src/components/file-tree-problem-indicators.ts@@ -0,0 +1,112 @@+/**+ * Pure DOM-mutation pass that tints file-tree rows whose docs carry+ * validation problems (red for errors, yellow for warnings) and injects a+ * problem-count badge. Reads the shared validation store's snapshot; same+ * shadow-root + MutationObserver contract as `file-tree-extension-badge.ts`+ * (every write value-gated so the host observer stays self-quiescent).+ *+ * The count badge is a sibling of the extension badge (both can coexist on a+ * `.mdx` row) because the tree's single decoration lane is already taken by+ * the symlink / agent icons.+ *+ * Color plumbing: the editor's `--lint-error-color` / `--lint-warning-color`+ * tokens are NOT `:root`-defined (they live under `.dark .cm-editor` etc.), so+ * they never reach this shadow root. The tree uses its own inheritable+ * `--ok-tree-problem-*` tokens: light mode rides the `var()` fallback+ * literals below (the editor's own light-mode fallbacks), dark mode overrides+ * at `.dark` scope in `globals.css` — custom properties inherit through+ * shadow boundaries, so the override reaches these rules.+ */++import { filePathToDocName } from '@/lib/doc-hash';+import type { DocProblemCounts } from '@/lib/validation-store';++export const OK_PROBLEM_ROW_ATTR = 'data-ok-problem';+export const OK_PROBLEM_BADGE_ATTR = 'data-ok-problem-badge';++/** CSS rules that apply inside Pierre's shadow root (joined into `FILE_TREE_UNSAFE_CSS`). */+export const FILE_TREE_PROBLEM_CSS = `+ [data-type='item'][${OK_PROBLEM_ROW_ATTR}='warning'] [data-item-section='content'] {+ color: var(--ok-tree-problem-warning, oklch(70% 0.15 75));+ }+ [data-type='item'][${OK_PROBLEM_ROW_ATTR}='error'] [data-item-section='content'] {+ color: var(--ok-tree-problem-error, oklch(55% 0.15 25));+ }+ [${OK_PROBLEM_BADGE_ATTR}] {+ display: inline-block;+ margin-left: 0.375rem;+ margin-right: 0.25rem;+ align-self: center;+ font-size: 0.6875rem;+ line-height: 1rem;+ min-width: 1rem;+ text-align: center;+ border-radius: 0.5rem;+ padding: 0 0.25rem;+ flex-shrink: 0;+ pointer-events: none;+ user-select: none;+ color: var(--ok-tree-problem-warning, oklch(70% 0.15 75));+ background: color-mix(in oklab, currentColor 14%, transparent);+ }+ [data-type='item'][${OK_PROBLEM_ROW_ATTR}='error'] [${OK_PROBLEM_BADGE_ATTR}] {+ color: var(--ok-tree-problem-error, oklch(55% 0.15 25));+ }+`;++/**+ * Tint + badge every file row whose doc has problems in `counts`; strip+ * indicators from rows that healed. Idempotent — repeated calls with no+ * change are no-ops. Folder rows are untouched (FR: files tint).+ */+export function applyProblemIndicators(+ root: ParentNode,+ counts: ReadonlyMap<string, DocProblemCounts>,+): void {+ const rows = root.querySelectorAll<HTMLElement>('[data-type="item"][data-item-path]');+ for (const row of rows) {+ const treePath = row.dataset.itemPath;+ if (!treePath || treePath.endsWith('/')) {+ clearProblemIndicators(row);+ continue;+ }+ const entry = counts.get(filePathToDocName(treePath));+ if (entry === undefined || (entry.errorCount === 0 && entry.warningCount === 0)) {+ clearProblemIndicators(row);+ continue;+ }+ const severity = entry.errorCount > 0 ? 'error' : 'warning';+ if (row.getAttribute(OK_PROBLEM_ROW_ATTR) !== severity) {+ row.setAttribute(OK_PROBLEM_ROW_ATTR, severity);+ }+ upsertProblemBadge(row, entry.errorCount + entry.warningCount);+ }+}++function clearProblemIndicators(row: HTMLElement): void {+ if (row.hasAttribute(OK_PROBLEM_ROW_ATTR)) row.removeAttribute(OK_PROBLEM_ROW_ATTR);+ row.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.remove();+}++/**+ * Inject (or update) the count badge right before the action lane — the same+ * slot contract as the extension badge's `upsertBadge`, landing AFTER any+ * extension badge already in that position so the order reads+ * `[label] [decoration?] [EXT?] [count] [action ···]`.+ */+function upsertProblemBadge(row: HTMLElement, total: number): void {+ const label = total > 99 ? '99+' : String(total);+ let badge = row.querySelector<HTMLSpanElement>(`[${OK_PROBLEM_BADGE_ATTR}]`);+ if (!badge) {+ badge = row.ownerDocument.createElement('span');+ badge.setAttribute(OK_PROBLEM_BADGE_ATTR, '');+ badge.setAttribute('aria-hidden', 'true');+ const actionSection = row.querySelector('[data-item-section="action"]');+ if (actionSection) {+ actionSection.before(badge);+ } else {+ row.appendChild(badge);+ }+ }+ if (badge.textContent !== label) badge.textContent = label;+}diff --git a/packages/app/src/components/handoff/compose-lint-fix-prompt.ts b/packages/app/src/components/handoff/compose-lint-fix-prompt.tsindex 19d32d9d8..3a5e71555 100644--- a/packages/app/src/components/handoff/compose-lint-fix-prompt.ts+++ b/packages/app/src/components/handoff/compose-lint-fix-prompt.ts@@ -19,7 +19,10 @@ const ALIAS_BY_CODE = new Map(MARKDOWNLINT_RULE_CATALOG.map((rule) => [rule.id,*/export function composeLintFixTerminalPaste(docName: string,- diagnostic: LintDiagnostic,+ // Structural over the fields actually read: the unified Problems panel+ // hands wire-shape diagnostics whose `source` is any validator id, not the+ // in-process lint-plugin literal union. `LintDiagnostic` remains assignable.+ diagnostic: Pick<LintDiagnostic, 'code' | 'message' | 'range'> & { source: string },lineText: string | undefined,): string {return composeLintFixPrompt({diff --git a/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx b/packages/app/src/components/settings/ContentRulesSection.dom.test.tsxnew file mode 100644index 000000000..5286d50bd--- /dev/null+++ b/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx@@ -0,0 +1,100 @@+/**+ * Behavioral tests for the Content rules settings section (This project →+ * Content rules): the broken-link posture select and the file-tree indicator+ * toggle write `validation.*` patches through the project binding, defaults+ * read as warning/on, and the lint-plugins pointer is present.+ */++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++const linguiMacroMock = {+ t: renderLinguiTemplate,+ Trans: ({ children }: { children: ReactNode }) => children,+ useLingui: () => ({ t: renderLinguiTemplate }),+};+vi.doMock('@lingui/core/macro', () => linguiMacroMock);+vi.doMock('@lingui/react/macro', () => linguiMacroMock);++let patches: unknown[] = [];+let patchResult: { ok: boolean; error?: unknown } = { ok: true };+let projectConfigValue: Record<string, unknown> = {};+let projectSyncedValue = true;+vi.doMock('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ projectConfig: projectConfigValue,+ projectSynced: projectSyncedValue,+ projectBinding: {+ patch: (patch: unknown) => {+ patches.push(patch);+ return patchResult;+ },+ },+ }),+}));++const toastError = vi.fn((_message: string) => {});+vi.doMock('sonner', () => ({ toast: { error: toastError } }));++const { ContentRulesSection } = await import('./ContentRulesSection');++beforeEach(() => {+ patches = [];+ patchResult = { ok: true };+ projectConfigValue = {};+ projectSyncedValue = true;+ toastError.mockClear();+});++afterEach(() => {+ cleanup();+});++describe('ContentRulesSection', () => {+ test('defaults read as links=warning and indicators on, with the plugins pointer', () => {+ render(<ContentRulesSection />);+ expect(screen.getByTestId('settings-content-rules-links').textContent).toContain('Warning');+ const toggle = screen.getByTestId('settings-content-rules-indicators');+ expect(toggle.getAttribute('data-state')).toBe('checked');+ expect(screen.getByTestId('settings-content-rules-plugins-note').textContent).toContain(+ 'their own tab',+ );+ });++ test('persisted values render: links=error, indicators off', () => {+ projectConfigValue = { validation: { links: 'error', fileTreeIndicators: false } };+ render(<ContentRulesSection />);+ expect(screen.getByTestId('settings-content-rules-links').textContent).toContain('Error');+ expect(screen.getByTestId('settings-content-rules-indicators').getAttribute('data-state')).toBe(+ 'unchecked',+ );+ });++ test('toggling indicators writes a validation patch', () => {+ render(<ContentRulesSection />);+ fireEvent.click(screen.getByTestId('settings-content-rules-indicators'));+ expect(patches).toEqual([{ validation: { fileTreeIndicators: false } }]);+ });++ test('changing the links posture writes a validation patch', async () => {+ render(<ContentRulesSection />);+ // Radix Select in jsdom: open the trigger, then choose an option.+ fireEvent.click(screen.getByTestId('settings-content-rules-links'));+ fireEvent.click(screen.getByRole('option', { name: 'Error' }));+ expect(patches).toEqual([{ validation: { links: 'error' } }]);+ // Let the popup fully close before the test ends: Radix's focus-scope+ // dispatches from a timer, and a dispatch landing after this file's jsdom+ // window is torn down surfaces as a cross-file unhandled error.+ await waitFor(() => expect(screen.queryByRole('option')).toBeNull());+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ test('a failed patch surfaces an error toast', () => {+ patchResult = { ok: false, error: 'nope' };+ render(<ContentRulesSection />);+ fireEvent.click(screen.getByTestId('settings-content-rules-indicators'));+ expect(toastError).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/app/src/components/settings/ContentRulesSection.tsx b/packages/app/src/components/settings/ContentRulesSection.tsxnew file mode 100644index 000000000..fa764aae9--- /dev/null+++ b/packages/app/src/components/settings/ContentRulesSection.tsx@@ -0,0 +1,135 @@+/**+ * Settings → This project → Content rules — the validation-surface knobs that+ * are NOT lint plugins: how broken internal links are classified (hidden /+ * warning / error) and whether the file tree tints problem files. Both are+ * project-scope (`validation.*` in config.yml, committed and shared via git);+ * the lint plugins themselves are managed on their own tab.+ */+import {+ DEFAULT_LINKS_VALIDATION,+ humanFormat,+ type LinksValidationSetting,+} from '@inkeep/open-knowledge-core';+import { Trans, useLingui } from '@lingui/react/macro';+import { toast } from 'sonner';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Switch } from '@/components/ui/switch';+import { useConfigContext } from '@/lib/config-provider';++export function ContentRulesSection() {+ const { t } = useLingui();+ const { projectConfig, projectSynced, projectBinding } = useConfigContext();+ const bindingReady = projectSynced && projectBinding !== null;+ const linksSetting: LinksValidationSetting =+ projectConfig?.validation?.links ?? DEFAULT_LINKS_VALIDATION;+ const indicatorsOn = projectConfig?.validation?.fileTreeIndicators !== false;++ function write(patch: { links?: LinksValidationSetting; fileTreeIndicators?: boolean }): void {+ if (projectBinding === null) {+ toast.error(t`Content rules not yet loaded — try again in a moment`);+ return;+ }+ const result = projectBinding.patch({ validation: patch });+ if (!result.ok) {+ toast.error(t`Failed to save content rules — ${humanFormat(result.error)}`);+ }+ }++ return (+ <section+ aria-labelledby="settings-content-rules-title"+ className="space-y-4"+ data-testid="settings-content-rules"+ >+ <div className="space-y-1">+ <h3 id="settings-content-rules-title" className="text-base font-semibold">+ <Trans>Content rules</Trans>+ </h3>+ <p className="text-sm text-muted-foreground">+ <Trans>+ How validation findings surface across the project. These choices are committed to+ config.yml and shared with every collaborator via git.+ </Trans>+ </p>+ </div>++ <div className="divide-y rounded-md border">+ <div className="flex items-center justify-between gap-3 px-3 py-2">+ <div className="min-w-0">+ <Label htmlFor="settings-content-rules-links" className="text-sm font-medium">+ <Trans>Broken internal links</Trans>+ </Label>+ <p className="text-sm text-muted-foreground">+ <Trans>+ How unresolved wiki-links are reported in the Problems panel, audits, and agent+ tools.+ </Trans>+ </p>+ </div>+ <Select+ value={linksSetting}+ onValueChange={(next) => write({ links: next as LinksValidationSetting })}+ disabled={!bindingReady}+ >+ <SelectTrigger+ id="settings-content-rules-links"+ className="w-36 shrink-0"+ data-testid="settings-content-rules-links"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="off">+ <Trans>Don't show</Trans>+ </SelectItem>+ <SelectItem value="warning">+ <Trans>Warning</Trans>+ </SelectItem>+ <SelectItem value="error">+ <Trans>Error</Trans>+ </SelectItem>+ </SelectContent>+ </Select>+ </div>++ <div className="flex items-center justify-between gap-3 px-3 py-2">+ <div className="min-w-0">+ <Label htmlFor="settings-content-rules-indicators" className="text-sm font-medium">+ <Trans>Problem indicators in the file explorer</Trans>+ </Label>+ <p className="text-sm text-muted-foreground">+ <Trans>+ Tint and badge files that have lint or link problems, without opening them.+ </Trans>+ </p>+ </div>+ <Switch+ id="settings-content-rules-indicators"+ checked={indicatorsOn}+ disabled={!bindingReady}+ onCheckedChange={(next) => write({ fileTreeIndicators: next })}+ aria-label={indicatorsOn ? t`Hide problem indicators` : t`Show problem indicators`}+ data-testid="settings-content-rules-indicators"+ />+ </div>+ </div>++ <p+ className="text-sm text-muted-foreground"+ data-testid="settings-content-rules-plugins-note"+ >+ <Trans>+ Lint plugins — which rule families run and their per-rule settings — are configured on+ their own tab under This project → Plugins.+ </Trans>+ </p>+ </section>+ );+}diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsxindex 4dbbe424c..332232af2 100644--- a/packages/app/src/components/settings/SettingsDialogBody.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx@@ -27,6 +27,7 @@ import { AccountSection } from './AccountSection';import { AiToolsSection } from './AiToolsSection';import { AttachmentsSection } from './AttachmentsSection';import { ConfigureAgentsSection } from './ConfigureAgentsSection';+import { ContentRulesSection } from './ContentRulesSection';import { EmbeddingsKeySection } from './EmbeddingsKeySection';import { SectionSkeleton } from './field-controls';import { HotkeysSection } from './HotkeysSection';@@ -126,6 +127,11 @@ export function SettingsDialogBody({// project's content-rule plugins + the audit pointer.return <ProjectPluginsManageSection />;}+ if (activeId === 'content-rules') {+ // Validation-surface knobs that are not lint plugins (This project →+ // Content rules): broken-link posture + file-tree problem indicators.+ return <ContentRulesSection />;+ }if (activeId === 'user-plugins-manage') {// User-scope plugins management (User → Plugins): toggle personal plugins// (Themes) via the user-scope binding.diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsxindex 1adddd2c0..0ff5b0dbe 100644--- a/packages/app/src/components/settings/SettingsDialogShell.tsx+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx@@ -222,6 +222,7 @@ export function SettingsDialogShell({{ id: 'sync', label: t`Sync` },{ id: 'search', label: t`Search` },{ id: 'plugins-manage', label: t`Plugins` },+ { id: 'content-rules', label: t`Content rules` },...(isFileProtocolRenderer ? [] : [{ id: 'link-previews', label: t`Link previews` }]),...(terminalSettingsAvailable ? [{ id: 'terminal', label: t`Terminal` }] : []),// Per-project MCP wiring + runtime skill — desktop-only because thediff --git a/packages/app/src/editor/lint-config-client.ts b/packages/app/src/editor/lint-config-client.tsindex 164ba010a..f296ea409 100644--- a/packages/app/src/editor/lint-config-client.ts+++ b/packages/app/src/editor/lint-config-client.ts@@ -6,8 +6,6 @@*/import {- type LintAuditResponse,- LintAuditResponseSchema,type LintConfigResponse,LintConfigResponseSchema,type LinterConfig,@@ -60,29 +58,6 @@ export async function fetchEffectiveLintConfig(docName: string): Promise<LinterCreturn 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 a whole-doc auto-fix. The body carries no agent identity on purpose:* a UI-initiated deterministic fix is the principal's write (the humandiff --git a/packages/app/src/editor/validation-audit-client.dom.test.tsx b/packages/app/src/editor/validation-audit-client.dom.test.tsxnew file mode 100644index 000000000..38be676fc--- /dev/null+++ b/packages/app/src/editor/validation-audit-client.dom.test.tsx@@ -0,0 +1,148 @@+/**+ * Behavioral tests for the unified-audit client: `runValidationAudit` hits+ * `GET /api/audit` with the right scoping query, and `useDocLinkFindings`+ * serves the doc's links-plane findings via the SAME endpoint (canonical+ * predicate — no divergent doc-scope determination), refreshing on the CC1+ * `backlinks` push relay.+ */++import type { ValidationAuditResponse } from '@inkeep/open-knowledge-core';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { emitDocumentsChanged } from '@/lib/documents-events';+import { runValidationAudit, useDocLinkFindings } from './validation-audit-client';++const origFetch = globalThis.fetch;+let fetchUrls: string[] = [];+let fetchBody: ValidationAuditResponse = {+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [],+};++beforeEach(() => {+ fetchUrls = [];+ globalThis.fetch = (async (url: RequestInfo | URL) => {+ fetchUrls.push(String(url));+ return new Response(JSON.stringify(fetchBody), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+});++afterEach(() => {+ globalThis.fetch = origFetch;+ cleanup();+});++const deadLink = {+ range: { start: { line: 4, character: 2 }, end: { line: 4, character: 2 } },+ severity: 'error' as const,+ source: 'links',+ code: 'dead-link',+ message: 'Link target "ghost" does not resolve to an existing document.',+};++const lintFinding = {+ range: { start: { line: 1, character: 0 }, end: { line: 1, character: 1 } },+ severity: 'warning' as const,+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+};++describe('runValidationAudit', () => {+ test('project scope hits the bare endpoint; doc scope uses the doc param', async () => {+ await runValidationAudit();+ await runValidationAudit({ kind: 'doc', docName: 'guides/intro' });+ await runValidationAudit({ kind: 'path', path: 'guides/' });+ expect(fetchUrls).toEqual([+ '/api/audit',+ '/api/audit?doc=guides%2Fintro',+ '/api/audit?path=guides%2F',+ ]);+ });++ test('returns null on a malformed response body', async () => {+ globalThis.fetch = (async () =>+ new Response(JSON.stringify({ nonsense: true }), { status: 200 })) as typeof fetch;+ expect(await runValidationAudit()).toBeNull();+ });+});++describe('useDocLinkFindings', () => {+ test('serves only links-source findings for the doc, keyed off the scoped audit', async () => {+ fetchBody = {+ files: [{ file: 'notes.md', diagnostics: [lintFinding, deadLink] }],+ fileCount: 1,+ errorCount: 1,+ warningCount: 1,+ warnings: [],+ };+ const { result } = renderHook(() => useDocLinkFindings('notes'));+ await waitFor(() => expect(result.current).toHaveLength(1));+ expect(result.current[0]?.code).toBe('dead-link');+ expect(fetchUrls).toEqual(['/api/audit?doc=notes']);+ });++ test('refreshes on the CC1 backlinks relay and clears healed findings', async () => {+ fetchBody = {+ files: [{ file: 'notes.md', diagnostics: [deadLink] }],+ fileCount: 1,+ errorCount: 1,+ warningCount: 0,+ warnings: [],+ };+ const { result } = renderHook(() => useDocLinkFindings('notes'));+ await waitFor(() => expect(result.current).toHaveLength(1));++ // The link target gets created elsewhere — the index push heals this doc.+ fetchBody = { files: [], fileCount: 1, errorCount: 0, warningCount: 0, warnings: [] };+ act(() => emitDocumentsChanged(['backlinks']));+ await waitFor(() => expect(result.current).toHaveLength(0));+ expect(fetchUrls).toEqual(['/api/audit?doc=notes', '/api/audit?doc=notes']);++ // Unrelated channels do not refetch.+ act(() => emitDocumentsChanged(['files']));+ expect(fetchUrls).toHaveLength(2);+ });++ test('null docName serves no findings and never fetches', () => {+ const { result } = renderHook(() => useDocLinkFindings(null));+ expect(result.current).toEqual([]);+ expect(fetchUrls).toEqual([]);+ });++ test('switching docs resets findings before the new fetch resolves (no stale carryover)', async () => {+ fetchBody = {+ files: [{ file: 'a.md', diagnostics: [deadLink] }],+ fileCount: 1,+ errorCount: 1,+ warningCount: 0,+ warnings: [],+ };+ const { result, rerender } = renderHook(({ doc }: { doc: string }) => useDocLinkFindings(doc), {+ initialProps: { doc: 'a' },+ });+ await waitFor(() => expect(result.current).toHaveLength(1));++ // Park the next fetch unresolved: doc B's findings must read EMPTY during+ // the in-flight window, never doc A's stale list (which would render A's+ // dead links — and store counts — under B's name).+ let resolveNext: (r: Response) => void = () => {};+ globalThis.fetch = (() => new Promise<Response>((r) => (resolveNext = r))) as typeof fetch;+ rerender({ doc: 'b' });+ expect(result.current).toEqual([]);++ resolveNext(+ new Response(+ JSON.stringify({ files: [], fileCount: 1, errorCount: 0, warningCount: 0, warnings: [] }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ ),+ );+ await waitFor(() => expect(result.current).toEqual([]));+ });+});diff --git a/packages/app/src/editor/validation-audit-client.ts b/packages/app/src/editor/validation-audit-client.tsnew file mode 100644index 000000000..2b673d18a--- /dev/null+++ b/packages/app/src/editor/validation-audit-client.ts@@ -0,0 +1,108 @@+/**+ * Client for the unified validation audit surface (`GET /api/audit`) — the+ * one engine spanning every registered content validator (markdownlint AND+ * internal-link resolution), returning a single source-tagged per-file+ * diagnostic plane. Sibling of `lint-config-client.ts`, which stays on the+ * lint-only `/api/lint*` routes.+ */++import {+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+ type ValidationDocResult,+} from '@inkeep/open-knowledge-core';+import { useEffect, useState } from 'react';+import { subscribeToDocumentsChanged } from '@/lib/documents-events';++/** Wire-loose diagnostic (schema `source` is any string, by design). */+type WireDiagnostic = ValidationDocResult['diagnostics'][number];++export type AuditScope =+ | { kind: 'project' }+ | { kind: 'path'; path: string }+ /** Extension-less docName — the server resolves the on-disk extension. */+ | { kind: 'doc'; docName: string };++/**+ * GET the unified audit plane for a scope. Returns every in-scope doc that has+ * at least one diagnostic from any validator, plus rollup counts and engine+ * degradation warnings. null on any failure.+ */+export async function runValidationAudit(+ scope: AuditScope = { kind: 'project' },+): Promise<ValidationAuditResponse | null> {+ try {+ const query =+ scope.kind === 'path'+ ? `?path=${encodeURIComponent(scope.path)}`+ : scope.kind === 'doc'+ ? `?doc=${encodeURIComponent(scope.docName)}`+ : '';+ const res = await fetch(`/api/audit${query}`);+ if (!res.ok) {+ // Log like the schema-drift path below: a non-OK response (server down,+ // port conflict) otherwise silently leaves the panel + tree on stale data.+ console.warn('[audit] request failed', res.status, res.statusText);+ return null;+ }+ const body = await res.json().catch(() => null);+ const parsed = ValidationAuditResponseSchema.safeParse(body);+ if (!parsed.success) {+ // Mirror the sibling lint-config-client logging so a client/server+ // schema drift window leaves a diagnostic trail instead of a silent null.+ console.warn('[audit] response failed schema validation', parsed.error.issues);+ return null;+ }+ return parsed.data;+ } catch (err) {+ console.warn('[audit] fetch threw', err);+ return null;+ }+}++/**+ * Live broken-link findings for one doc, via the SAME scoped audit predicate+ * the project audit runs — doc scope is a provable restriction of the+ * project-wide plane, never a second determination. Lint findings are+ * excluded here (the doc scope's lint plane is the live `useDocDiagnostics`+ * CRDT read, which is fresher than the audit walk).+ *+ * Refreshes when the doc changes and on every CC1 `backlinks` push — the+ * signal the server debounces whenever the link index changes, which covers+ * both this doc's own edits and cross-doc ripples (a deleted target turning+ * this doc's link dead).+ */+export function useDocLinkFindings(docName: string | null): WireDiagnostic[] {+ const [findings, setFindings] = useState<WireDiagnostic[]>([]);+ useEffect(() => {+ // Reset on every doc change, not just null: the previous doc's findings+ // must never survive into the new doc's render window — a stale carryover+ // would show doc A's dead links under doc B (panel rows AND store counts)+ // until the scoped fetch resolves.+ setFindings((prev) => (prev.length === 0 ? prev : []));+ if (docName === null) {+ return;+ }+ let cancelled = false;+ const load = () => {+ void runValidationAudit({ kind: 'doc', docName }).then((result) => {+ if (cancelled || result === null) return;+ const linkFindings = result.files+ .flatMap((f) => f.diagnostics)+ .filter((d) => d.source === 'links');+ setFindings((prev) =>+ prev.length === 0 && linkFindings.length === 0 ? prev : linkFindings,+ );+ });+ };+ load();+ const unsub = subscribeToDocumentsChanged((channels) => {+ if (channels.includes('backlinks')) load();+ });+ return () => {+ cancelled = true;+ unsub();+ };+ }, [docName]);+ return findings;+}diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 640b7deab..7a0fd4919 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -5193,6 +5193,17 @@ html.electron-mode [data-slot="sidebar-inner"] {.dark .cm-editor .cm-lintRange-error {--lint-error-color: oklch(72% 0.18 25);}+/* File-tree problem-indicator tokens (file-tree-problem-indicators.ts). The+ editor's --lint-*-color tokens are scoped under .dark .cm-editor / .dark+ .ProseMirror and never reach the tree's shadow root, so the tree gets its+ own inheritable pair: light mode rides the var() fallback literals inside+ the shadow CSS (same values as the editor's light fallbacks); this .dark+ block carries the dark overrides across the shadow boundary via custom-+ property inheritance. Values mirror the editor's dark lint palette. */+.dark {+ --ok-tree-problem-warning: oklch(80% 0.13 80);+ --ok-tree-problem-error: oklch(72% 0.18 25);+}/* Diagnostic tooltip + lint panel onto OK popover tokens. */.cm-tooltip.cm-tooltip-lint,.cm-panel.cm-panel-lint {diff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.tsindex 5774ad7bf..7e48a2b87 100644--- a/packages/app/src/lib/documents-events.ts+++ b/packages/app/src/lib/documents-events.ts@@ -41,6 +41,33 @@ export function subscribeToDocumentsChanged(return () => window.removeEventListener(DOCUMENTS_CHANGED_EVENT, listener);}+// Doc-persisted relays the CC1 `disk-ack` frame's docName — the one per-doc+// push channel — for consumers that react to "this document's bytes just+// reached disk" (the validation-freshness per-doc re-audit). Kept separate+// from documents-changed: derived-view channels are doc-anonymous signals,+// while this event's whole value is the docName it names.+const DOC_PERSISTED_EVENT = 'open-knowledge:doc-persisted';++interface DocPersistedDetail {+ docName: string;+}++export function emitDocPersisted(docName: string): void {+ window.dispatchEvent(+ new CustomEvent<DocPersistedDetail>(DOC_PERSISTED_EVENT, { detail: { docName } }),+ );+}++export function subscribeToDocPersisted(onPersisted: (docName: string) => void): () => void {+ const listener = (event: Event) => {+ if (!(event instanceof CustomEvent)) return;+ const docName = (event as CustomEvent<DocPersistedDetail>).detail?.docName;+ if (typeof docName === 'string' && docName.length > 0) onPersisted(docName);+ };+ window.addEventListener(DOC_PERSISTED_EVENT, listener);+ return () => window.removeEventListener(DOC_PERSISTED_EVENT, listener);+}+// Branch-changed is a side-channel event for surfaces that display the// current git branch (sidebar footer, editor footer). Emitted by the// DocumentContext branch dispatchers (`observeBranch`, `onBranchSwitched`),diff --git a/packages/app/src/lib/validation-store.test.ts b/packages/app/src/lib/validation-store.test.tsnew file mode 100644index 000000000..35b0f9735--- /dev/null+++ b/packages/app/src/lib/validation-store.test.ts@@ -0,0 +1,87 @@+/**+ * Unit tests for the shared validation store: full-plane replace (project+ * audit), per-doc patch (scoped re-validate), per-source live patch (open+ * doc), zero-count pruning, and subscriber notification semantics.+ */++import { beforeEach, describe, expect, test } from 'vitest';+import {+ getValidationSnapshot,+ patchDocValidationFromAudit,+ patchDocValidationSource,+ replaceValidationFromAudit,+ resetValidationStoreForTest,+ subscribeToValidationStore,+} from './validation-store';++const lintWarning = { severity: 'warning', source: 'markdownlint' };+const lintError = { severity: 'error', source: 'markdownlint' };+const deadLink = { severity: 'error', source: 'links' };++beforeEach(() => {+ resetValidationStoreForTest();+});++describe('validation store', () => {+ test('replaceValidationFromAudit keys totals by extension-less docName', () => {+ replaceValidationFromAudit([+ { file: 'guides/setup.md', diagnostics: [lintWarning, deadLink] },+ { file: 'notes.mdx', diagnostics: [lintError] },+ ]);+ const snapshot = getValidationSnapshot();+ expect(snapshot.get('guides/setup')).toEqual({ errorCount: 1, warningCount: 1 });+ expect(snapshot.get('notes')).toEqual({ errorCount: 1, warningCount: 0 });+ });++ test('a later replace drops healed docs from the snapshot', () => {+ replaceValidationFromAudit([{ file: 'a.md', diagnostics: [lintWarning] }]);+ replaceValidationFromAudit([{ file: 'b.md', diagnostics: [deadLink] }]);+ const snapshot = getValidationSnapshot();+ expect(snapshot.has('a')).toBe(false);+ expect(snapshot.get('b')).toEqual({ errorCount: 1, warningCount: 0 });+ });++ test('patchDocValidationFromAudit refreshes one doc; empty plane heals it', () => {+ replaceValidationFromAudit([+ { file: 'a.md', diagnostics: [lintWarning] },+ { file: 'b.md', diagnostics: [deadLink] },+ ]);+ patchDocValidationFromAudit('a', [lintError, lintWarning]);+ expect(getValidationSnapshot().get('a')).toEqual({ errorCount: 1, warningCount: 1 });+ // Other docs untouched.+ expect(getValidationSnapshot().get('b')).toEqual({ errorCount: 1, warningCount: 0 });++ patchDocValidationFromAudit('a', []);+ expect(getValidationSnapshot().has('a')).toBe(false);+ });++ test('patchDocValidationSource updates one source, preserving the other', () => {+ patchDocValidationFromAudit('a', [lintWarning, deadLink]);+ patchDocValidationSource('a', 'lint', { errorCount: 0, warningCount: 3 });+ // links error preserved; lint replaced.+ expect(getValidationSnapshot().get('a')).toEqual({ errorCount: 1, warningCount: 3 });++ patchDocValidationSource('a', 'links', { errorCount: 0, warningCount: 0 });+ expect(getValidationSnapshot().get('a')).toEqual({ errorCount: 0, warningCount: 3 });+ });++ test('subscribers fire on change and unchanged per-source patches no-op', () => {+ let notifications = 0;+ const unsubscribe = subscribeToValidationStore(() => {+ notifications += 1;+ });+ patchDocValidationSource('a', 'lint', { errorCount: 0, warningCount: 2 });+ expect(notifications).toBe(1);+ // Identical counts are a structural no-op — the tree must not re-render.+ patchDocValidationSource('a', 'lint', { errorCount: 0, warningCount: 2 });+ expect(notifications).toBe(1);+ unsubscribe();+ patchDocValidationSource('a', 'lint', { errorCount: 1, warningCount: 0 });+ expect(notifications).toBe(1);+ });++ test('all-zero docs never appear in the snapshot', () => {+ patchDocValidationSource('clean', 'lint', { errorCount: 0, warningCount: 0 });+ expect(getValidationSnapshot().has('clean')).toBe(false);+ });+});diff --git a/packages/app/src/lib/validation-store.ts b/packages/app/src/lib/validation-store.tsnew file mode 100644index 000000000..3e05111f2--- /dev/null+++ b/packages/app/src/lib/validation-store.ts@@ -0,0 +1,135 @@+/**+ * Shared validation-results store: per-doc problem counts read by BOTH the+ * Problems panel and the file tree (the tree tints/badges rows from it).+ * Module store + subscribe (the codebase's module-event idiom;+ * `useSyncExternalStore`-compatible) rather than React context — the file+ * tree consumes it from a MutationObserver callback outside React.+ *+ * Counts are tracked per validator source so the three freshness triggers can+ * write independently without clobbering each other:+ * 1. a project audit replaces the WHOLE store (both sources, every doc);+ * 2. the open doc's lint entry is written live off the `useDocDiagnostics`+ * debounce, and its links entry off the doc-scoped audit fetch;+ * 3. a persisted doc (CC1 `disk-ack`, the one per-doc channel) is re-validated+ * alone and patched (both sources).+ * Never a background whole-project walk.+ */++import { filePathToDocName } from '@/lib/doc-hash';++export interface DocProblemCounts {+ errorCount: number;+ warningCount: number;+}++export type ValidationSourceKey = 'lint' | 'links';++interface DiagnosticShape {+ severity: string;+ source: string;+}++interface SourceCounts {+ lint: DocProblemCounts;+ links: DocProblemCounts;+}++const ZERO: DocProblemCounts = { errorCount: 0, warningCount: 0 };++/** Keyed by extension-less docName. */+const entries = new Map<string, SourceCounts>();+const listeners = new Set<() => void>();+/**+ * Immutable totals snapshot handed to `useSyncExternalStore` consumers and+ * the tree's apply pass. Rebuilt on every mutation; docs whose merged counts+ * are all zero are dropped so `snapshot.has(docName)` means "has problems".+ */+let snapshot: ReadonlyMap<string, DocProblemCounts> = new Map();++function rebuildSnapshotAndNotify(): void {+ const next = new Map<string, DocProblemCounts>();+ for (const [docName, counts] of entries) {+ const errorCount = counts.lint.errorCount + counts.links.errorCount;+ const warningCount = counts.lint.warningCount + counts.links.warningCount;+ if (errorCount === 0 && warningCount === 0) continue;+ next.set(docName, { errorCount, warningCount });+ }+ snapshot = next;+ for (const listener of listeners) listener();+}++/** Split one doc's diagnostics into per-source counts ('links' vs everything else). */+function countBySource(diagnostics: readonly DiagnosticShape[]): SourceCounts {+ const counts: SourceCounts = {+ lint: { errorCount: 0, warningCount: 0 },+ links: { errorCount: 0, warningCount: 0 },+ };+ for (const diagnostic of diagnostics) {+ const bucket = diagnostic.source === 'links' ? counts.links : counts.lint;+ if (diagnostic.severity === 'error') bucket.errorCount += 1;+ else bucket.warningCount += 1;+ }+ return counts;+}++export function subscribeToValidationStore(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** Merged per-doc totals; only docs with at least one problem are present. */+export function getValidationSnapshot(): ReadonlyMap<string, DocProblemCounts> {+ return snapshot;+}++/**+ * Trigger 1 — a whole-project audit is a full-plane truth: replace every+ * entry (docs healed since the last audit drop out).+ */+export function replaceValidationFromAudit(+ files: readonly { file: string; diagnostics: readonly DiagnosticShape[] }[],+): void {+ entries.clear();+ for (const file of files) {+ entries.set(filePathToDocName(file.file), countBySource(file.diagnostics));+ }+ rebuildSnapshotAndNotify();+}++/**+ * Trigger 3 — one doc re-validated (scoped audit): both sources for that doc+ * are fresh truth; an empty plane means the doc healed.+ */+export function patchDocValidationFromAudit(+ docName: string,+ diagnostics: readonly DiagnosticShape[],+): void {+ entries.set(docName, countBySource(diagnostics));+ rebuildSnapshotAndNotify();+}++/**+ * Trigger 2 — one source's live counts for the open doc (lint off the CRDT+ * debounce, links off the doc-scoped fetch), preserving the other source.+ */+export function patchDocValidationSource(+ docName: string,+ source: ValidationSourceKey,+ counts: DocProblemCounts,+): void {+ const current = entries.get(docName) ?? { lint: ZERO, links: ZERO };+ const existing = current[source];+ if (existing.errorCount === counts.errorCount && existing.warningCount === counts.warningCount) {+ return;+ }+ entries.set(docName, { ...current, [source]: counts });+ rebuildSnapshotAndNotify();+}++export function resetValidationStoreForTest(): void {+ entries.clear();+ snapshot = new Map();+ listeners.clear();+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex c2ba6cb34..3a4cc9592 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -458,6 +458,7 @@"8lwQlE": [["0"], " added, ", ["1"], " removed"],"8m8diM": ["No location selected. Use Browse to choose a folder."],"8nWu1k": ["Empty diagram"],+ "8ruqQi": ["Broken internal links"],"8t9CRE": ["Starting ", ["agentName"], "…"],"8tjQCz": ["Explore"],"8uAWix": [@@ -719,6 +720,7 @@"EOjU5V": ["Inline Math Properties"],"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens used"],"ETyvvg": ["No language match."],+ "EWCJFu": ["Created ", ["target"]],"EWPtMO": ["Code"],"EWX92Z": ["Collapse Ask AI"],"EZVxVz": ["Replace the active match from the replace field."],@@ -791,6 +793,9 @@"FOGD7m": ["Create something great."],"FRYB1Q": ["/api/config returned a malformed body"],"FRqZ9v": ["Couldn't update skill: ", ["0"]],+ "FTBN5g": [+ "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."+ ],"FTUGgh": ["Enter a repository URL or owner/repo"],"FUMerq": ["Could not enable sync: ", ["detail"]],"FWQuPE": [@@ -1065,6 +1070,7 @@"Lcehxn": ["Save resolution"],"LdABLa": ["Could not open ", ["target"], ". Try opening it manually."],"LdKIHS": ["Draft a spec"],+ "LdyooL": ["link"],"LeGeTf": ["OpenKnowledge on GitHub"],"LhQlGR": ["This project is running an older version of OpenKnowledge (v",@@ -1150,6 +1156,9 @@" — your previous version is in history if you need to restore it."],"MysZUL": ["Connecting to ", ["agentName"], "…"],+ "N-IonL": [+ "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."+ ],"N1KkEO": ["Jump to last tab"],"N1YYa7": ["Loading image"],"N1mdmS": ["This file can't be opened in the text editor."],@@ -1196,6 +1205,7 @@"NuH1jp": ["Public repository"],"Nv3mUj": ["Show advanced"],"NvOvTi": ["Create in <0>", ["dirDisplay"], "</0>"],+ "Nwbs0q": ["Don't show"],"Nx7BWE": ["Git auto-sync"],"NxW-md": ["Resize ", ["handleKey"]],"NzFvyK": ["Session ended — undo unavailable"],@@ -1223,6 +1233,7 @@"ONPvOb": ["Loading agent activity"],"ONgEZF": ["Loading headings for ", ["pageTarget"]],"OOIVJo": ["Uninstalled \"", ["0"], "\" from ", ["1"]],+ "OPOiKn": ["Content rules"],"OTF92M": ["Label <0>(optional display text)</0>"],"OVjNeX": ["Terminal ", ["0"]],"OX2Neh": ["Inline code"],@@ -1396,6 +1407,7 @@"SItQRc": ["How do you like OpenKnowledge?"],"SOPwPh": ["Restore to this edit"],"SQWJ-i": ["Restore sessions"],+ "STOrpI": ["lint"],"STTOnz": [["keyName"], " type: complex value (nested; read-only)"],"SUOoXn": ["Failed to open project."],"SVLPt5": [["formatted"], " GitHub stars"],@@ -1414,6 +1426,7 @@"SiUUCS": ["Next match"],"SkMZlS": ["Couldn't remove <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],"Skr_7L": ["Search worktrees"],+ "SlfejT": ["Error"],"Sq8lf2": ["Editors to install skills into"],"SrOuyg": ["Document panels"],"SvBFYA": ["No recent projects"],@@ -1454,6 +1467,7 @@"U5Spo9": ["Content directory must be inside the project"],"U7HJ4y": ["Managed by OpenKnowledge (read-only)"],"U8CD-l": ["Copy full path, No workspace"],+ "U9tm58": ["Hide problem indicators"],"UBv8UK": ["Delete Permanently"],"UDFrWm": ["Checking GitHub connection..."],"UL8A9w": ["Tag"],@@ -1655,6 +1669,9 @@"Y8ViJx": ["A newer version may have been deployed since this tab opened."],"YBt9YP": ["Beta"],"YC6_wP": ["Edit ", ["keyName"]],+ "YDL7N6": [+ "Lint plugins — which rule families run and their per-rule settings — are configured on their own tab under This project → Plugins."+ ],"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"],@@ -2283,6 +2300,7 @@"knjOzA": ["Tag value"],"kolRU1": ["Do you want to permanently delete instead?"],"kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],+ "ktspdq": ["Tint and badge files that have lint or link problems, without opening them."],"ku0yLQ": ["Pages are embedded the first time a search needs them."],"ky9Tuc": ["Edit ", ["0"], " source"],"l-4nnw": ["Search rules"],@@ -2494,6 +2512,7 @@"oKBnk5": ["More requests were blocked."],"oQA-cA": ["Full path"],"oS1YpJ": ["Open the Project Navigator."],+ "oWsZk8": ["Create missing page ", ["target"]],"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."@@ -2600,6 +2619,7 @@"r4R7AZ": ["Network error during cleanup"],"r51jLC": ["File saved & Claude Desktop App opened"],"r6ncaO": ["Close tab"],+ "r6y-jM": ["Warning"],"r871ed": ["Your knowledge base is now on GitHub at <0>",["ownerLogin"],@@ -2759,6 +2779,7 @@"uQewpR": ["Couldn't restart the server — it's running under a different account. Restart your computer to clear it, then reopen this project."],+ "uR2YT3": ["Show problem indicators"],"uVbUP8": ["Settings…"],"uWtdQR": ["No templates yet. Add one in this folder's Templates section, or in Settings → Templates."@@ -2870,6 +2891,7 @@["projectEntries", "plural", { "one": ["#", " entry"], "other": ["#", " entries"] }],")"],+ "x3kWeu": ["Problem indicators in the file explorer"],"x57cJf": ["Open link"],"xCJdfg": ["Clear"],"xCdTnb": ["Close new tab"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 0a0e39880..e5d30caac 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1403,6 +1403,10 @@ msgstr "breadcrumb"msgid "Bring a remote repository onto this machine."msgstr "Bring a remote repository onto this machine."+#: src/components/settings/ContentRulesSection.tsx+msgid "Broken internal links"+msgstr "Broken internal links"+#: src/components/GraphPanel.tsxmsgid "Broken link"msgstr "Broken link"@@ -2054,6 +2058,12 @@ msgstr "Content directory must be inside the project"msgid "Content root"msgstr "Content root"+#: src/components/settings/ContentRulesSection.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Content rules"+msgstr "Content rules"++#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/LintingSection.tsxmsgid "Content rules not yet loaded — try again in a moment"msgstr "Content rules not yet loaded — try again in a moment"@@ -2639,6 +2649,10 @@ msgstr "Create a worktree from this branch"msgid "Create in <0>{dirDisplay}</0>"msgstr "Create in <0>{dirDisplay}</0>"+#: src/components/ProblemsPanel.tsx+msgid "Create missing page {target}"+msgstr "Create missing page {target}"+#: src/components/CreateProjectDialog.tsx#: src/components/NavigatorApp.tsxmsgid "Create new project"@@ -2649,6 +2663,7 @@ msgid "Create new tag #{tagValue}"msgstr "Create new tag #{tagValue}"#: src/components/GraphPanel.tsx+#: src/components/ProblemsPanel.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsxmsgid "Create page"@@ -2702,6 +2717,10 @@ msgstr "Create your first file"msgid "Create your first project"msgstr "Create your first project"+#: src/components/ProblemsPanel.tsx+msgid "Created {target}"+msgstr "Created {target}"+#: src/components/FolderTimelineCard.tsxmsgid "created folder"msgstr "created folder"@@ -2714,6 +2733,7 @@ msgstr "created template"#: src/components/NewItemDialog.tsx#: src/components/NewSkillDialog.tsx#: src/components/NewTemplateDialog.tsx+#: src/components/ProblemsPanel.tsxmsgid "Creating"msgstr "Creating"@@ -3098,6 +3118,10 @@ msgstr "Documents tagged <0>#{tagName}</0>"msgid "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."msgstr "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."+#: src/components/settings/ContentRulesSection.tsx+msgid "Don't show"+msgstr "Don't show"+#: src/components/acp/ThreadView.tsxmsgid "done"msgstr "done"@@ -3448,6 +3472,10 @@ msgstr "Enter a valid URL (for example https://api.openai.com/v1)."msgid "Entry"msgstr "Entry"+#: src/components/settings/ContentRulesSection.tsx+msgid "Error"+msgstr "Error"+#: src/components/ShareReceiveDialog.tsxmsgid "Error:"msgstr "Error:"@@ -3553,6 +3581,7 @@ msgid "Failed to create folder"msgstr "Failed to create folder"#: src/components/LinksPanel.tsx+#: src/components/ProblemsPanel.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsxmsgid "Failed to create page"@@ -3756,6 +3785,7 @@ msgid "Failed to reorder"msgstr "Failed to reorder"#. placeholder {0}: humanFormat(result.error)+#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/LintingSection.tsxmsgid "Failed to save content rules — {0}"msgstr "Failed to save content rules — {0}"@@ -4314,6 +4344,10 @@ msgstr "Hide panel ({panelShortcut})"msgid "Hide panel ({panelShortcutLabel})"msgstr "Hide panel ({panelShortcutLabel})"+#: src/components/settings/ContentRulesSection.tsx+msgid "Hide problem indicators"+msgstr "Hide problem indicators"+#: src/editor/find-replace/FindReplaceBar.tsxmsgid "Hide replace"msgstr "Hide replace"@@ -4397,6 +4431,14 @@ msgstr "How to set up"msgid "How to set up {0} (opens in browser)"msgstr "How to set up {0} (opens in browser)"+#: src/components/settings/ContentRulesSection.tsx+msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."+msgstr "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."++#: src/components/settings/ContentRulesSection.tsx+msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."+msgstr "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."+#: src/editor/slash-command/embed-starter-items.tsxmsgid "HTML"msgstr "HTML"@@ -4797,6 +4839,10 @@ msgstr "Light, dark, or follow the OS."msgid "line {displayLine}"msgstr "line {displayLine}"+#: src/components/ProblemsPanel.tsx+msgid "link"+msgstr "link"+#: src/editor/bubble-menu/LinkEditPopover.tsx#: src/editor/slash-command/component-items.tsxmsgid "Link"@@ -4843,6 +4889,14 @@ msgstr "Links"msgid "Links & images"msgstr "Links & images"+#: src/components/ProblemsPanel.tsx+msgid "lint"+msgstr "lint"++#: src/components/settings/ContentRulesSection.tsx+msgid "Lint plugins — which rule families run and their per-rule settings — are configured on their own tab under This project → Plugins."+msgstr "Lint plugins — which rule families run and their per-rule settings — are configured on their own tab under This project → Plugins."+#: src/components/PropertyWidgets.tsxmsgid "List"msgstr "List"@@ -6589,6 +6643,10 @@ msgstr "Private repository"msgid "probe failed"msgstr "probe failed"+#: src/components/settings/ContentRulesSection.tsx+msgid "Problem indicators in the file explorer"+msgstr "Problem indicators in the file explorer"+#: src/components/DocPanel.tsx#: src/components/ProblemsPanel.tsxmsgid "Problems"@@ -7933,6 +7991,10 @@ msgstr "Show panel ({panelShortcut})"msgid "Show panel ({panelShortcutLabel})"msgstr "Show panel ({panelShortcutLabel})"+#: src/components/settings/ContentRulesSection.tsx+msgid "Show problem indicators"+msgstr "Show problem indicators"+#: src/editor/find-replace/FindReplaceBar.tsxmsgid "Show replace"msgstr "Show replace"@@ -8986,6 +9048,10 @@ msgstr "This window can't store a token — open Settings from the main app windmsgid "Timeline"msgstr "Timeline"+#: src/components/settings/ContentRulesSection.tsx+msgid "Tint and badge files that have lint or link problems, without opening them."+msgstr "Tint and badge files that have lint or link problems, without opening them."+#: src/components/TemplateProperties.tsxmsgid "title"msgstr "title"@@ -9481,6 +9547,10 @@ msgstr "Waiting for authorization"msgid "Waiting for your approval"msgstr "Waiting for your approval"+#: src/components/settings/ContentRulesSection.tsx+msgid "Warning"+msgstr "Warning"+#: src/components/settings/AccountSection.tsxmsgid "We couldn't check your GitHub connection."msgstr "We couldn't check your GitHub connection."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex d744f21cb..f2db6ccc4 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -458,6 +458,7 @@"8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],+ "8ruqQi": ["ßŕōķēń ĩńţēŕńàĺ ĺĩńķś"],"8t9CRE": ["Śţàŕţĩńĝ ", ["agentName"], "…"],"8tjQCz": ["Ēxƥĺōŕē"],"8uAWix": [@@ -719,6 +720,7 @@"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " ţōķēńś ũśēď"],"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],+ "EWCJFu": ["Ćŕēàţēď ", ["target"]],"EWPtMO": ["Ćōďē"],"EWX92Z": ["Ćōĺĺàƥśē Àśķ ÀĨ"],"EZVxVz": ["Ŕēƥĺàćē ţĥē àćţĩvē ḿàţćĥ ƒŕōḿ ţĥē ŕēƥĺàćē ƒĩēĺď."],@@ -791,6 +793,9 @@"FOGD7m": ["Ćŕēàţē śōḿēţĥĩńĝ ĝŕēàţ."],"FRYB1Q": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď à ḿàĺƒōŕḿēď ƀōďŷ"],"FRqZ9v": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ: ", ["0"]],+ "FTBN5g": [+ "Ĥōŵ vàĺĩďàţĩōń ƒĩńďĩńĝś śũŕƒàćē àćŕōśś ţĥē ƥŕōĴēćţ. Ţĥēśē ćĥōĩćēś àŕē ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ àńď śĥàŕēď ŵĩţĥ ēvēŕŷ ćōĺĺàƀōŕàţōŕ vĩà ĝĩţ."+ ],"FTUGgh": ["Ēńţēŕ à ŕēƥōśĩţōŕŷ ŨŔĹ ōŕ ōŵńēŕ/ŕēƥō"],"FUMerq": ["Ćōũĺď ńōţ ēńàƀĺē śŷńć: ", ["detail"]],"FWQuPE": [@@ -1065,6 +1070,7 @@"Lcehxn": ["Śàvē ŕēśōĺũţĩōń"],"LdABLa": ["Ćōũĺď ńōţ ōƥēń ", ["target"], ". Ţŕŷ ōƥēńĩńĝ ĩţ ḿàńũàĺĺŷ."],"LdKIHS": ["Ďŕàƒţ à śƥēć"],+ "LdyooL": ["ĺĩńķ"],"LeGeTf": ["ŌƥēńĶńōŵĺēďĝē ōń ĜĩţĤũƀ"],"LhQlGR": ["Ţĥĩś ƥŕōĴēćţ ĩś ŕũńńĩńĝ àń ōĺďēŕ vēŕśĩōń ōƒ ŌƥēńĶńōŵĺēďĝē (v",@@ -1150,6 +1156,9 @@" — ŷōũŕ ƥŕēvĩōũś vēŕśĩōń ĩś ĩń ĥĩśţōŕŷ ĩƒ ŷōũ ńēēď ţō ŕēśţōŕē ĩţ."],"MysZUL": ["Ćōńńēćţĩńĝ ţō ", ["agentName"], "…"],+ "N-IonL": [+ "Ĥōŵ ũńŕēśōĺvēď ŵĩķĩ-ĺĩńķś àŕē ŕēƥōŕţēď ĩń ţĥē Ƥŕōƀĺēḿś ƥàńēĺ, àũďĩţś, àńď àĝēńţ ţōōĺś."+ ],"N1KkEO": ["ĵũḿƥ ţō ĺàśţ ţàƀ"],"N1YYa7": ["Ĺōàďĩńĝ ĩḿàĝē"],"N1mdmS": ["Ţĥĩś ƒĩĺē ćàń'ţ ƀē ōƥēńēď ĩń ţĥē ţēxţ ēďĩţōŕ."],@@ -1196,6 +1205,7 @@"NuH1jp": ["Ƥũƀĺĩć ŕēƥōśĩţōŕŷ"],"Nv3mUj": ["Śĥōŵ àďvàńćēď"],"NvOvTi": ["Ćŕēàţē ĩń <0>", ["dirDisplay"], "</0>"],+ "Nwbs0q": ["Ďōń'ţ śĥōŵ"],"Nx7BWE": ["Ĝĩţ àũţō-śŷńć"],"NxW-md": ["Ŕēśĩźē ", ["handleKey"]],"NzFvyK": ["Śēśśĩōń ēńďēď — ũńďō ũńàvàĩĺàƀĺē"],@@ -1223,6 +1233,7 @@"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],"OOIVJo": ["Ũńĩńśţàĺĺēď \"", ["0"], "\" ƒŕōḿ ", ["1"]],+ "OPOiKn": ["Ćōńţēńţ ŕũĺēś"],"OTF92M": ["Ĺàƀēĺ <0>(ōƥţĩōńàĺ ďĩśƥĺàŷ ţēxţ)</0>"],"OVjNeX": ["Ţēŕḿĩńàĺ ", ["0"]],"OX2Neh": ["Ĩńĺĩńē ćōďē"],@@ -1396,6 +1407,7 @@"SItQRc": ["Ĥōŵ ďō ŷōũ ĺĩķē ŌƥēńĶńōŵĺēďĝē?"],"SOPwPh": ["Ŕēśţōŕē ţō ţĥĩś ēďĩţ"],"SQWJ-i": ["Ŕēśţōŕē śēśśĩōńś"],+ "STOrpI": ["ĺĩńţ"],"STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],"SVLPt5": [["formatted"], " ĜĩţĤũƀ śţàŕś"],@@ -1414,6 +1426,7 @@"SiUUCS": ["Ńēxţ ḿàţćĥ"],"SkMZlS": ["Ćōũĺďń'ţ ŕēḿōvē <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],"Skr_7L": ["Śēàŕćĥ ŵōŕķţŕēēś"],+ "SlfejT": ["Ēŕŕōŕ"],"Sq8lf2": ["Ēďĩţōŕś ţō ĩńśţàĺĺ śķĩĺĺś ĩńţō"],"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],"SvBFYA": ["Ńō ŕēćēńţ ƥŕōĴēćţś"],@@ -1454,6 +1467,7 @@"U5Spo9": ["Ćōńţēńţ ďĩŕēćţōŕŷ ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],"U7HJ4y": ["Ḿàńàĝēď ƀŷ ŌƥēńĶńōŵĺēďĝē (ŕēàď-ōńĺŷ)"],"U8CD-l": ["Ćōƥŷ ƒũĺĺ ƥàţĥ, Ńō ŵōŕķśƥàćē"],+ "U9tm58": ["Ĥĩďē ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],"UL8A9w": ["Ţàĝ"],@@ -1655,6 +1669,9 @@"Y8ViJx": ["À ńēŵēŕ vēŕśĩōń ḿàŷ ĥàvē ƀēēń ďēƥĺōŷēď śĩńćē ţĥĩś ţàƀ ōƥēńēď."],"YBt9YP": ["ßēţà"],"YC6_wP": ["Ēďĩţ ", ["keyName"]],+ "YDL7N6": [+ "Ĺĩńţ ƥĺũĝĩńś — ŵĥĩćĥ ŕũĺē ƒàḿĩĺĩēś ŕũń àńď ţĥēĩŕ ƥēŕ-ŕũĺē śēţţĩńĝś — àŕē ćōńƒĩĝũŕēď ōń ţĥēĩŕ ōŵń ţàƀ ũńďēŕ Ţĥĩś ƥŕōĴēćţ → Ƥĺũĝĩńś."+ ],"YEIS9T": ["Ēďĩţś àƥƥĺŷ ĺĩvē. Ĺĩĝĥţ ōŕ ďàŕķ ĩś ćĥōśēń ƒŕōḿ ţĥē ƀàćķĝŕōũńď."],"YEP3X2": ["Ďēĺēţē à ţàƀĺē ŵĥēń ţĥē àćţĩvē ţàƀĺē ćēĺĺ śēĺēćţĩōń ćōvēŕś ţĥē ƒũĺĺ ţàƀĺē."],"YGIi_c": ["Ŕēĩńśţàĺĺ"],@@ -2283,6 +2300,7 @@"knjOzA": ["Ţàĝ vàĺũē"],"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],"kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],+ "ktspdq": ["Ţĩńţ àńď ƀàďĝē ƒĩĺēś ţĥàţ ĥàvē ĺĩńţ ōŕ ĺĩńķ ƥŕōƀĺēḿś, ŵĩţĥōũţ ōƥēńĩńĝ ţĥēḿ."],"ku0yLQ": ["Ƥàĝēś àŕē ēḿƀēďďēď ţĥē ƒĩŕśţ ţĩḿē à śēàŕćĥ ńēēďś ţĥēḿ."],"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],"l-4nnw": ["Śēàŕćĥ ŕũĺēś"],@@ -2494,6 +2512,7 @@"oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],"oQA-cA": ["Ƒũĺĺ ƥàţĥ"],"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],+ "oWsZk8": ["Ćŕēàţē ḿĩśśĩńĝ ƥàĝē ", ["target"]],"oXKEsy": ["Ďēĺēţē àń àďĴàćēńţ ŵĩķĩ-ĺĩńķ ōŕ ţàĝ ćĥĩƥ."],"oXlLi4": ["ƤŕōĴēćţ ƥĺũĝĩńś àŕē ŷōũŕ ƥŕōĴēćţ'ś àũţĥōŕĩńĝ śţàńďàŕď — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĩś ćōḿḿĩţţēď ţō ćōńƒĩĝ.ŷḿĺ àńď śĥàŕēď ŵĩţĥ ēvēŕŷ ćōĺĺàƀōŕàţōŕ vĩà ĝĩţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."@@ -2600,6 +2619,7 @@"r4R7AZ": ["Ńēţŵōŕķ ēŕŕōŕ ďũŕĩńĝ ćĺēàńũƥ"],"r51jLC": ["Ƒĩĺē śàvēď & Ćĺàũďē Ďēśķţōƥ Àƥƥ ōƥēńēď"],"r6ncaO": ["Ćĺōśē ţàƀ"],+ "r6y-jM": ["Ŵàŕńĩńĝ"],"r871ed": ["Ŷōũŕ ķńōŵĺēďĝē ƀàśē ĩś ńōŵ ōń ĜĩţĤũƀ àţ <0>",["ownerLogin"],@@ -2759,6 +2779,7 @@"uQewpR": ["Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — ĩţ'ś ŕũńńĩńĝ ũńďēŕ à ďĩƒƒēŕēńţ àććōũńţ. Ŕēśţàŕţ ŷōũŕ ćōḿƥũţēŕ ţō ćĺēàŕ ĩţ, ţĥēń ŕēōƥēń ţĥĩś ƥŕōĴēćţ."],+ "uR2YT3": ["Śĥōŵ ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],"uVbUP8": ["Śēţţĩńĝś…"],"uWtdQR": ["Ńō ţēḿƥĺàţēś ŷēţ. Àďď ōńē ĩń ţĥĩś ƒōĺďēŕ'ś Ţēḿƥĺàţēś śēćţĩōń, ōŕ ĩń Śēţţĩńĝś → Ţēḿƥĺàţēś."@@ -2870,6 +2891,7 @@["projectEntries", "plural", { "one": ["#", " ēńţŕŷ"], "other": ["#", " ēńţŕĩēś"] }],")"],+ "x3kWeu": ["Ƥŕōƀĺēḿ ĩńďĩćàţōŕś ĩń ţĥē ƒĩĺē ēxƥĺōŕēŕ"],"x57cJf": ["Ōƥēń ĺĩńķ"],"xCJdfg": ["Ćĺēàŕ"],"xCdTnb": ["Ćĺōśē ńēŵ ţàƀ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 7144c5c22..f109720ff 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1399,6 +1399,10 @@ msgstr ""msgid "Bring a remote repository onto this machine."msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Broken internal links"+msgstr ""+#: src/components/GraphPanel.tsxmsgid "Broken link"msgstr ""@@ -2050,6 +2054,12 @@ msgstr ""msgid "Content root"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+#: src/components/settings/SettingsDialogShell.tsx+msgid "Content rules"+msgstr ""++#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/LintingSection.tsxmsgid "Content rules not yet loaded — try again in a moment"msgstr ""@@ -2635,6 +2645,10 @@ msgstr ""msgid "Create in <0>{dirDisplay}</0>"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Create missing page {target}"+msgstr ""+#: src/components/CreateProjectDialog.tsx#: src/components/NavigatorApp.tsxmsgid "Create new project"@@ -2645,6 +2659,7 @@ msgid "Create new tag #{tagValue}"msgstr ""#: src/components/GraphPanel.tsx+#: src/components/ProblemsPanel.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsxmsgid "Create page"@@ -2698,6 +2713,10 @@ msgstr ""msgid "Create your first project"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "Created {target}"+msgstr ""+#: src/components/FolderTimelineCard.tsxmsgid "created folder"msgstr ""@@ -2710,6 +2729,7 @@ msgstr ""#: src/components/NewItemDialog.tsx#: src/components/NewSkillDialog.tsx#: src/components/NewTemplateDialog.tsx+#: src/components/ProblemsPanel.tsxmsgid "Creating"msgstr ""@@ -3094,6 +3114,10 @@ msgstr ""msgid "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Don't show"+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "done"msgstr ""@@ -3444,6 +3468,10 @@ msgstr ""msgid "Entry"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Error"+msgstr ""+#: src/components/ShareReceiveDialog.tsxmsgid "Error:"msgstr ""@@ -3549,6 +3577,7 @@ msgid "Failed to create folder"msgstr ""#: src/components/LinksPanel.tsx+#: src/components/ProblemsPanel.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsxmsgid "Failed to create page"@@ -3752,6 +3781,7 @@ msgid "Failed to reorder"msgstr ""#. placeholder {0}: humanFormat(result.error)+#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/LintingSection.tsxmsgid "Failed to save content rules — {0}"msgstr ""@@ -4310,6 +4340,10 @@ msgstr ""msgid "Hide panel ({panelShortcutLabel})"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Hide problem indicators"+msgstr ""+#: src/editor/find-replace/FindReplaceBar.tsxmsgid "Hide replace"msgstr ""@@ -4393,6 +4427,14 @@ msgstr ""msgid "How to set up {0} (opens in browser)"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."+msgstr ""++#: src/components/settings/ContentRulesSection.tsx+msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."+msgstr ""+#: src/editor/slash-command/embed-starter-items.tsxmsgid "HTML"msgstr ""@@ -4793,6 +4835,10 @@ msgstr ""msgid "line {displayLine}"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "link"+msgstr ""+#: src/editor/bubble-menu/LinkEditPopover.tsx#: src/editor/slash-command/component-items.tsxmsgid "Link"@@ -4839,6 +4885,14 @@ msgstr ""msgid "Links & images"msgstr ""+#: src/components/ProblemsPanel.tsx+msgid "lint"+msgstr ""++#: src/components/settings/ContentRulesSection.tsx+msgid "Lint plugins — which rule families run and their per-rule settings — are configured on their own tab under This project → Plugins."+msgstr ""+#: src/components/PropertyWidgets.tsxmsgid "List"msgstr ""@@ -6585,6 +6639,10 @@ msgstr ""msgid "probe failed"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Problem indicators in the file explorer"+msgstr ""+#: src/components/DocPanel.tsx#: src/components/ProblemsPanel.tsxmsgid "Problems"@@ -7929,6 +7987,10 @@ msgstr ""msgid "Show panel ({panelShortcutLabel})"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Show problem indicators"+msgstr ""+#: src/editor/find-replace/FindReplaceBar.tsxmsgid "Show replace"msgstr ""@@ -8982,6 +9044,10 @@ msgstr ""msgid "Timeline"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Tint and badge files that have lint or link problems, without opening them."+msgstr ""+#: src/components/TemplateProperties.tsxmsgid "title"msgstr ""@@ -9477,6 +9543,10 @@ msgstr ""msgid "Waiting for your approval"msgstr ""+#: src/components/settings/ContentRulesSection.tsx+msgid "Warning"+msgstr ""+#: src/components/settings/AccountSection.tsxmsgid "We couldn't check your GitHub connection."msgstr ""diff --git a/packages/app/tests/integration/advisory-warnings.test.ts b/packages/app/tests/integration/advisory-warnings.test.tsindex 186ffeb35..ebed254ef 100644--- a/packages/app/tests/integration/advisory-warnings.test.ts+++ b/packages/app/tests/integration/advisory-warnings.test.ts@@ -242,4 +242,60 @@ describe('content-rule (lint) violations on the agent write path', () => {writeFileSync(cfgPath, '', 'utf-8');}});++ test('a dead link written by THIS write rides warnings[] immediately (no index-debounce race)', async () => {+ const docName = uniqueDoc('rw-dead-link');+ // The live-derived index updates 100 ms AFTER a change; the advisory is+ // computed synchronously in the handler. This asserts the write path+ // refreshes the index for the written doc before validating, so the very+ // write that introduces the dead link is the one that reports it.+ const target = `rw-ghost-${crypto.randomUUID().slice(0, 8)}`;+ const { status, body } = await writeMd(`# Doc\n\nSee [[${target}]].\n`, docName);+ expect(status).toBe(200);+ const dead = (body.warnings ?? []).find(+ (w) => w.kind === 'lint-violation' && w.code === 'dead-link',+ );+ expect(dead).toBeDefined();+ if (dead?.kind !== 'lint-violation') throw new Error('narrowed above');+ expect(dead.source).toBe('links');+ // Default posture: warnings (validation.links).+ expect(dead.severity).toBe('warning');+ expect(dead.message).toContain(target);+ // The unresolved target rides verbatim so the agent can create the page.+ expect(dead.linkTarget).toBe(target);+ // Line is exact (0-based range 2 → 1-based display 3).+ expect(dead.line).toBe(3);+ });++ test('a resolving link and validation.links=off both yield no dead-link advisory', async () => {+ const existing = uniqueDoc('rw-existing');+ await writeMd('# Exists\n', existing);+ const linker = uniqueDoc('rw-good-link');+ const good = await writeMd(`# Doc\n\nSee [[${existing}]].\n`, linker);+ expect(good.status).toBe(200);+ expect(+ (good.body.warnings ?? []).some((w) => w.kind === 'lint-violation' && w.code === 'dead-link'),+ ).toBe(false);++ // With the project posture off, even a genuinely dead link stays silent —+ // the setting is read fresh per request.+ const { writeFileSync } = await import('node:fs');+ const { join } = await import('node:path');+ const cfgPath = join(server.contentDir, '.ok', 'config.yml');+ writeFileSync(cfgPath, 'validation:\n links: off\n', 'utf-8');+ try {+ const silenced = await writeMd(+ '# Doc\n\nSee [[definitely-missing-target]].\n',+ uniqueDoc('rw-off'),+ );+ expect(silenced.status).toBe(200);+ expect(+ (silenced.body.warnings ?? []).some(+ (w) => w.kind === 'lint-violation' && w.code === 'dead-link',+ ),+ ).toBe(false);+ } 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 83087f796..c8d6a2b72 100644--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts@@ -141,6 +141,10 @@ const EXEMPT_HANDLERS = new Set([// other read handlers below.'handleLintDoc','handleLintAudit',+ // `/api/audit` (GET) — read-only unified validation audit (markdownlint ++ // dead links) over the project or a sub-path. No writes, no agent identity —+ // same rationale as `handleLintAudit`.+ 'handleAudit',// `/api/template/import` — imports an existing doc as a template. Same// project-config posture as `handleTemplate`; it DOES thread// `extractActorIdentity` (folder timeline) + `extractAgentIdentity` (templatediff --git a/packages/app/tests/integration/audit-http.test.ts b/packages/app/tests/integration/audit-http.test.tsnew file mode 100644index 000000000..b67742f6b--- /dev/null+++ b/packages/app/tests/integration/audit-http.test.ts@@ -0,0 +1,182 @@+/**+ * Integration coverage for the unified validation audit surface+ * (`GET /api/audit`) against a real server + tmp contentDir: one engine+ * fanning out to the markdownlint walk and the backlink-index dead-link+ * read, merged into a single source-tagged diagnostic plane.+ *+ * Contract-level assertions only (status codes, wire-schema shape, scope+ * parity) — the engine internals are free to evolve underneath.+ */++import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import {+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+} from '@inkeep/open-knowledge-core';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { awaitBacklinkIndexed, createTestServer, type TestServer } from './test-harness.ts';++let server: TestServer;++beforeAll(async () => {+ // markdownlint is opt-in (off by default); the unified plane must carry+ // lint findings alongside link findings, so enable it for the whole 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';++// Outer budget exceeds awaitBacklinkIndexed's 30s inner timeout so the+// helper's targeted error surfaces before the runner's generic timeout.+const BACKLINK_SEED_TIMEOUT_MS = 45_000;++function api(pathAndQuery: string): string {+ return `http://127.0.0.1:${server.port}${pathAndQuery}`;+}++describe('GET /api/audit', () => {+ test(+ 'returns lint + dead-link findings in one source-tagged plane',+ async () => {+ const folder = join(server.contentDir, 'audit-http');+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, 'tabbed.md'), TABBED_BODY, 'utf-8');+ writeFileSync(+ join(folder, 'linker.md'),+ '# Linker\n\nSee [[audit-http-ghost-target]].\n',+ 'utf-8',+ );+ try {+ await awaitBacklinkIndexed(server, 'audit-http-ghost-target', 'audit-http/linker');++ const res = await fetch(api('/api/audit'));+ expect(res.status).toBe(200);+ const body: ValidationAuditResponse = ValidationAuditResponseSchema.parse(await res.json());++ const tabbed = body.files.find((f) => f.file === 'audit-http/tabbed.md');+ const md010 = tabbed?.diagnostics.find((d) => d.code === 'MD010');+ expect(md010).toBeDefined();+ expect(md010?.source).toBe('markdownlint');++ const linker = body.files.find((f) => f.file === 'audit-http/linker.md');+ const dead = linker?.diagnostics.find((d) => d.code === 'dead-link');+ expect(dead).toBeDefined();+ expect(dead?.source).toBe('links');+ // Default posture: broken links are warnings (validation.links).+ expect(dead?.severity).toBe('warning');+ expect(dead?.message).toContain('audit-http-ghost-target');+ // The unresolved target rides the wire verbatim (create-page affordance).+ expect(dead?.linkTarget).toBe('audit-http-ghost-target');+ // Line is exact by contract (column approximate): the link sits on+ // the third line of the doc (0-based line 2).+ expect(dead?.range.start.line).toBe(2);++ // The wire counts must roll up from the merged plane itself.+ const flat = body.files.flatMap((f) => f.diagnostics);+ expect(body.errorCount).toBe(flat.filter((d) => d.severity === 'error').length);+ expect(body.warningCount).toBe(flat.filter((d) => d.severity !== 'error').length);+ expect(body.warningCount).toBeGreaterThanOrEqual(2);+ expect(body.fileCount).toBeGreaterThanOrEqual(2);+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ },+ BACKLINK_SEED_TIMEOUT_MS,+ );++ test(+ 'doc scope flags the identical dead link as the whole-project audit',+ async () => {+ const folder = join(server.contentDir, 'audit-parity');+ mkdirSync(folder, { recursive: true });+ writeFileSync(+ join(folder, 'linker.md'),+ '# Linker\n\nSee [[audit-parity-ghost]].\n',+ 'utf-8',+ );+ try {+ await awaitBacklinkIndexed(server, 'audit-parity-ghost', 'audit-parity/linker');++ const project = await fetch(api('/api/audit'));+ const docScoped = await fetch(api('/api/audit?path=audit-parity%2Flinker.md'));+ expect(project.status).toBe(200);+ expect(docScoped.status).toBe(200);+ const projectBody = ValidationAuditResponseSchema.parse(await project.json());+ const docBody = ValidationAuditResponseSchema.parse(await docScoped.json());++ // One predicate, scoped: the doc-scope plane for this file is exactly+ // the project-scope plane restricted to it — same diagnostics, same+ // positions, in both directions.+ const projectEntry = projectBody.files.find((f) => f.file === 'audit-parity/linker.md');+ const docEntry = docBody.files.find((f) => f.file === 'audit-parity/linker.md');+ expect(docEntry).toBeDefined();+ expect(docEntry?.diagnostics.some((d) => d.code === 'dead-link')).toBe(true);+ expect(docEntry).toEqual(projectEntry);++ // The scope filter admits nothing outside the requested doc.+ expect(docBody.files.map((f) => f.file)).toEqual(['audit-parity/linker.md']);+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ },+ BACKLINK_SEED_TIMEOUT_MS,+ );++ test(+ 'doc param scopes by extension-less docName to the same plane as path',+ async () => {+ const folder = join(server.contentDir, 'audit-docparam');+ mkdirSync(folder, { recursive: true });+ writeFileSync(+ join(folder, 'linker.md'),+ '# Linker\n\nSee [[audit-docparam-ghost]].\n',+ 'utf-8',+ );+ try {+ await awaitBacklinkIndexed(server, 'audit-docparam-ghost', 'audit-docparam/linker');++ const byPath = await fetch(api('/api/audit?path=audit-docparam%2Flinker.md'));+ const byDoc = await fetch(api('/api/audit?doc=audit-docparam%2Flinker'));+ expect(byPath.status).toBe(200);+ expect(byDoc.status).toBe(200);+ const pathBody = ValidationAuditResponseSchema.parse(await byPath.json());+ const docBody = ValidationAuditResponseSchema.parse(await byDoc.json());++ // `doc` is pure extension resolution over the same scope machinery —+ // the two spellings must produce the identical plane.+ expect(docBody).toEqual(pathBody);+ expect(docBody.files.some((f) => f.file === 'audit-docparam/linker.md')).toBe(true);+ } finally {+ rmSync(folder, { recursive: true, force: true });+ }+ },+ BACKLINK_SEED_TIMEOUT_MS,+ );++ test('traversal and absolute paths are refused with the invalid-request envelope', async () => {+ for (const bad of ['../outside', '/etc/passwd']) {+ const res = await fetch(api(`/api/audit?path=${encodeURIComponent(bad)}`));+ expect(res.status).toBe(400);+ const body = (await res.json()) as { type?: string };+ expect(body.type).toBe('urn:ok:error:invalid-request');+ }+ });++ test('doc param refuses traversal and combining with path', async () => {+ for (const bad of ['../outside', '/etc/passwd']) {+ const res = await fetch(api(`/api/audit?doc=${encodeURIComponent(bad)}`));+ expect(res.status).toBe(400);+ const body = (await res.json()) as { type?: string };+ expect(body.type).toBe('urn:ok:error:invalid-request');+ }+ const both = await fetch(api('/api/audit?doc=a&path=b.md'));+ expect(both.status).toBe(400);+ });+});diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.tsindex d4f03c500..ff65d05c4 100644--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts@@ -124,6 +124,10 @@ const EXEMPT_HANDLERS = new Set([// does not apply.'handleLintDoc','handleLintAudit',+ // `/api/audit` (GET) — read-only unified validation audit (markdownlint ++ // dead links). No Y.Doc target (reads disk + the in-memory backlink index),+ // so the per-doc conflict gate does not apply.+ 'handleAudit',// `/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/stress/unified-problems.e2e.ts b/packages/app/tests/stress/unified-problems.e2e.tsnew file mode 100644index 000000000..6edde99ab--- /dev/null+++ b/packages/app/tests/stress/unified-problems.e2e.ts@@ -0,0 +1,191 @@+/**+ * Playwright E2E for the unified validation surface: the Problems+ * panel's project scope renders lint AND broken-link findings from+ * `GET /api/audit` with per-row source tags, and the file tree tints + badges+ * problem rows inside the real `@pierre/trees` shadow root — the rung jsdom+ * structurally cannot cover (unsafeCSS paints only in a browser).+ *+ * Freshness trigger 3 (an agent write to an UNOPENED doc tints its tree row+ * via the CC1 disk-ack relay, no project audit involved) is exercised against+ * the live persistence pipeline.+ */++import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import {+ expect,+ filterCriticalErrors,+ type LogEntry,+ test,+ waitForActiveProviderSynced as waitForProvider,+} from './_helpers';++// A hard tab trips markdownlint MD010 (warning under OK's tuned defaults).+const HARD_TAB_BODY = '# Heading\n\n\tindented with a hard tab\n';++/** Open the right-rail Problems tab. */+async function openProblemsTab(page: Page) {+ await page.locator('#tab-problems').click();+ await expect(+ page.locator('ul[aria-label="Problems"]').or(page.getByText('No problems found')),+ ).toBeVisible({ timeout: 5_000 });+}++/** Activate project scope and wait for the audit snapshot to land. */+async function openProjectScope(page: Page) {+ await page.getByTestId('panel-scope-project').click();+ await expect(page.getByTestId('problems-project-scope')).toBeVisible({ timeout: 5_000 });+ await expect(page.getByTestId('problems-audit-summary')).not.toBeEmpty({ timeout: 15_000 });+}++/** The file tree's shadow row for a tree path, evaluated in the live shadow root. */+function treeRowHandle(page: Page, treePath: string) {+ return page.locator('file-tree-container').evaluateHandle((host, path) => {+ return (host as Element & { shadowRoot: ShadowRoot | null }).shadowRoot?.querySelector(+ `[data-type="item"][data-item-path="${path}"]`,+ );+ }, treePath);+}++const errors: LogEntry[] = [];+let openDocName = '';+let lintDocName = '';+let linkDocName = '';++test.beforeEach(async ({ page, api, workerServer }) => {+ // markdownlint is opt-in; enable it so the lint plane carries findings.+ 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 });+ }+ });++ const suffix = randomUUID().slice(0, 8);+ openDocName = `uv-open-${suffix}`;+ lintDocName = `uv-lint-${suffix}`;+ linkDocName = `uv-link-${suffix}`;+ await api.createPage(`${openDocName}.md`);+ await api.createPage(`${lintDocName}.md`);+ await api.createPage(`${linkDocName}.md`);+ await api.replaceDoc(lintDocName, HARD_TAB_BODY);+ await api.replaceDoc(linkDocName, `# Linker\n\nSee [[uv-ghost-${suffix}]].\n`);++ await page.goto(`/#/${openDocName}`);+ await waitForProvider(page);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');+});++test.afterEach(() => {+ expect(filterCriticalErrors(errors), 'Expected zero critical console errors').toEqual([]);+});++test.afterAll(({ workerServer }) => {+ writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');+});++test.describe('unified Problems — project scope', () => {+ test('lint and dead-link findings render together, source-tagged', async ({ page }) => {+ await openProblemsTab(page);+ await openProjectScope(page);++ // Both seeded files group in the plane.+ await expect(page.getByText(`${lintDocName}.md`)).toBeVisible({ timeout: 15_000 });+ await expect(page.getByText(`${linkDocName}.md`)).toBeVisible();++ // Rows are source-tagged: at least one lint chip and one link chip.+ const tags = page.getByTestId('problems-source-tag');+ await expect(tags.filter({ hasText: 'lint' }).first()).toBeVisible();+ await expect(tags.filter({ hasText: 'link' }).first()).toBeVisible();++ // The dead link names its unresolved target and reads as links/dead-link.+ await expect(page.getByText('links/dead-link').first()).toBeVisible();+ });+});++test.describe('unified Problems — file-tree indicators', () => {+ test('a project audit tints problem rows in the live shadow root, clean rows stay bare', async ({+ page,+ }) => {+ await openProblemsTab(page);+ await openProjectScope(page);++ // The tint attribute lands on the real shadow-DOM rows. Broken links are+ // warnings by default (validation.links), like the lint findings.+ await expect+ .poll(+ async () => {+ const row = await treeRowHandle(page, `${linkDocName}.md`);+ return row.evaluate((el) => el?.getAttribute('data-ok-problem') ?? null);+ },+ { timeout: 15_000 },+ )+ .toBe('warning');+ await expect+ .poll(async () => {+ const row = await treeRowHandle(page, `${lintDocName}.md`);+ return row.evaluate((el) => el?.getAttribute('data-ok-problem') ?? null);+ })+ .toBe('warning');++ // Count badge is injected next to the label.+ const badgeText = await (await treeRowHandle(page, `${linkDocName}.md`)).evaluate(+ (el) => el?.querySelector('[data-ok-problem-badge]')?.textContent ?? null,+ );+ expect(badgeText).toBe('1');++ // The unsafeCSS actually paints: a tinted row's label color differs from a+ // clean row's — the pixels jsdom cannot verify.+ const colors = await page.locator('file-tree-container').evaluate(+ (host, paths) => {+ const shadow = (host as Element & { shadowRoot: ShadowRoot | null }).shadowRoot;+ const colorOf = (path: string) => {+ const section = shadow?.querySelector(+ `[data-type="item"][data-item-path="${path}"] [data-item-section="content"]`,+ );+ return section ? getComputedStyle(section as Element).color : null;+ };+ return { problem: colorOf(paths[0] as string), clean: colorOf(paths[1] as string) };+ },+ [`${linkDocName}.md`, `${openDocName}.md`],+ );+ expect(colors.problem).not.toBeNull();+ expect(colors.clean).not.toBeNull();+ expect(colors.problem).not.toBe(colors.clean);+ });++ test('an agent write to an unopened doc tints its row via disk-ack, no audit run', async ({+ page,+ api,+ }) => {+ const suffix = randomUUID().slice(0, 8);+ const sleeperDoc = `uv-sleeper-${suffix}`;+ await api.createPage(`${sleeperDoc}.md`);++ // No Problems panel interaction at all — the only freshness path available+ // is the per-doc disk-ack re-validate.+ await api.replaceDoc(sleeperDoc, `# Sleeper\n\nSee [[uv-sleeper-ghost-${suffix}]].\n`);++ await expect+ .poll(+ async () => {+ const row = await treeRowHandle(page, `${sleeperDoc}.md`);+ return row.evaluate((el) => el?.getAttribute('data-ok-problem') ?? null);+ },+ // Bounded by the persistence debounce + disk-ack + 500ms revalidate+ // debounce — generous ceiling, converges much earlier in practice.+ { timeout: 30_000 },+ )+ .toBe('warning');+ });+});diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex a31484b00..4e8257772 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -33,6 +33,7 @@ import { type Config, ConfigSchema, trustSystemCertificates } from '@inkeep/open* Config loaded via preAction hook: CLI > ENV > project > user > Zod defaults.*/import { Command } from 'commander';+import { auditCommand } from './commands/audit.ts';import { authCommand } from './commands/auth/index.ts';import { bugReportCommand } from './commands/bug-report.ts';import { cleanCommand } from './commands/clean.ts';@@ -231,6 +232,10 @@ program.addCommand(preview);// lint command — headless markdown linting (whole project, a folder, or a file)program.addCommand(lintCommand(() => resolvedConfig));+// audit command — unified validation audit (lint + broken internal links) via+// the running project server; CLI sibling of the `audit` MCP tool+program.addCommand(auditCommand(() => resolvedConfig));+// ui command — serves the React editor (sibling of `start`).const ui = uiCommand(() => resolvedConfig);program.addCommand(ui);diff --git a/packages/cli/src/commands/audit.test.ts b/packages/cli/src/commands/audit.test.tsnew file mode 100644index 000000000..0d5634b3e--- /dev/null+++ b/packages/cli/src/commands/audit.test.ts@@ -0,0 +1,257 @@+/**+ * Unit tests for `ok audit` — target-path translation, server-first dispatch+ * (planted lock + stubbed global fetch, mirroring `sync.test.ts`), report+ * rendering over the unified plane, and exit-code semantics.+ */++import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { hostname, tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ValidationAuditResponse } from '@inkeep/open-knowledge-core';+import type { Config } from '@inkeep/open-knowledge-server';+import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { runAudit, toContentRelativeTarget } from './audit.ts';++// `runAudit` only reads `content.dir` (via `resolveContentDir`) from config.+const minimalConfig = { content: { dir: '.' } } as Config;++function payload(over: Partial<ValidationAuditResponse> = {}): ValidationAuditResponse {+ return {+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [],+ ...over,+ };+}++function diagnostic(over: Record<string, unknown> = {}) {+ return {+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 1 } },+ severity: 'warning' as const,+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ ...over,+ };+}++function collectIo() {+ const out: string[] = [];+ const err: string[] = [];+ return {+ io: { out: (l: string) => out.push(l), err: (l: string) => err.push(l) },+ out,+ err,+ };+}++describe('toContentRelativeTarget', () => {+ const contentDir = '/home/user/project';++ test('joins a relative path onto the invocation cwd and relativizes', () => {+ expect(toContentRelativeTarget('guides/intro.md', contentDir, contentDir)).toBe(+ 'guides/intro.md',+ );+ });++ test('resolves from a nested invocation cwd', () => {+ expect(toContentRelativeTarget('intro.md', join(contentDir, 'guides'), contentDir)).toBe(+ 'guides/intro.md',+ );+ });++ test('normalizes a leading-dot path', () => {+ expect(toContentRelativeTarget('./guides', contentDir, contentDir)).toBe('guides');+ });++ test('returns empty string for the content dir itself', () => {+ expect(toContentRelativeTarget('.', contentDir, contentDir)).toBe('');+ });++ test('rejects a path escaping the content dir', () => {+ expect(toContentRelativeTarget('../outside', contentDir, contentDir)).toBeNull();+ expect(toContentRelativeTarget('/etc/passwd', contentDir, contentDir)).toBeNull();+ });+});++describe('runAudit', () => {+ const origFetch = globalThis.fetch;+ let dir: string;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ok-audit-test-'));+ const lockDir = join(dir, '.ok', 'local');+ mkdirSync(lockDir, { recursive: true });+ // Minimal live lock: our own pid (alive), matching hostname, non-zero port.+ writeFileSync(+ join(lockDir, 'server.lock'),+ JSON.stringify({ pid: process.pid, hostname: hostname(), port: 54321 }),+ );+ });++ afterEach(() => {+ globalThis.fetch = origFetch;+ rmSync(dir, { recursive: true, force: true });+ });++ function stubFetch(+ body: unknown,+ status = 200,+ ): { urls: string[]; inits: (RequestInit | undefined)[] } {+ const urls: string[] = [];+ const inits: (RequestInit | undefined)[] = [];+ globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => {+ urls.push(String(url));+ inits.push(init);+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ return { urls, inits };+ }++ test('clean audit: GET /api/audit with cli version headers, exit 0', async () => {+ const { urls, inits } = stubFetch(payload({ fileCount: 3 }));+ const { io, out } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(0);+ expect(urls[0]).toBe('http://127.0.0.1:54321/api/audit');+ const headers = inits[0]?.headers as Record<string, string>;+ expect(headers['x-ok-client-kind']).toBe('cli');+ expect(headers['x-ok-client-runtime']).toBe(RUNTIME_VERSION);+ expect(out.join('\n')).toContain('No problems in 3 files');+ });++ test('scopes the query to the contentDir-relative target', async () => {+ const { urls } = stubFetch(payload());+ const { io } = collectIo();++ await runAudit('guides/intro.md', {}, minimalConfig, dir, dir, io);++ expect(urls[0]).toBe('http://127.0.0.1:54321/api/audit?path=guides%2Fintro.md');+ });++ test('renders the unified plane with source-tagged rows and exits 1 on problems', async () => {+ stubFetch(+ payload({+ fileCount: 2,+ errorCount: 1,+ warningCount: 1,+ files: [+ {+ file: 'a.md',+ diagnostics: [+ diagnostic(),+ diagnostic({+ severity: 'error',+ source: 'links',+ code: 'dead-link',+ message: 'Link target "missing" does not resolve to an existing document.',+ }),+ ],+ },+ ],+ }),+ );+ const { io, out } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ const text = out.join('\n');+ expect(text).toContain('a.md');+ expect(text).toContain('markdownlint/MD010');+ expect(text).toContain('links/dead-link');+ expect(text).toContain('2 problems');+ });++ test('--errors-only ignores warning-severity findings for the exit code', async () => {+ stubFetch(+ payload({+ fileCount: 1,+ warningCount: 1,+ files: [{ file: 'a.md', diagnostics: [diagnostic()] }],+ }),+ );+ const { io } = collectIo();++ const code = await runAudit(undefined, { errorsOnly: true }, minimalConfig, dir, dir, io);++ expect(code).toBe(0);+ });++ test('--json emits the full uncapped payload', async () => {+ const body = payload({+ fileCount: 1,+ warningCount: 1,+ files: [{ file: 'a.md', diagnostics: [diagnostic()] }],+ });+ stubFetch(body);+ const { io, out } = collectIo();++ const code = await runAudit(undefined, { json: true }, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ expect(JSON.parse(out.join('\n'))).toEqual(body);+ });++ test('surfaces engine degradation warnings in the report', async () => {+ stubFetch(+ payload({ warnings: ['links validation unavailable: backlink index is not configured'] }),+ );+ const { io, out } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(0);+ expect(out.join('\n')).toContain('links validation unavailable');+ });++ test('errors with `ok start` guidance when no server lock is live', async () => {+ rmSync(join(dir, '.ok', 'local', 'server.lock'));+ const { io, err } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ expect(err.join('\n')).toContain('ok start');+ expect(err.join('\n')).toContain('ok lint');+ });++ test('rejects a target outside the content dir before dialing the server', async () => {+ const { urls } = stubFetch(payload());+ const { io, err } = collectIo();++ const code = await runAudit('../outside', {}, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ expect(urls).toHaveLength(0);+ expect(err.join('\n')).toContain('outside the content directory');+ });++ test('surfaces the problem+json title on a non-OK response', async () => {+ stubFetch({ title: 'Invalid path.' }, 400);+ const { io, err } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ expect(err.join('\n')).toContain('Invalid path.');+ });++ test('errors on an unexpected response shape', async () => {+ stubFetch({ nonsense: true });+ const { io, err } = collectIo();++ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);++ expect(code).toBe(1);+ expect(err.join('\n')).toContain('unexpected response shape');+ });+});diff --git a/packages/cli/src/commands/audit.ts b/packages/cli/src/commands/audit.tsnew file mode 100644index 000000000..db6d4019d--- /dev/null+++ b/packages/cli/src/commands/audit.ts@@ -0,0 +1,173 @@+/**+ * `ok audit [path]` — unified read-only validation audit: every content+ * problem (markdown-lint violations AND broken internal links) in one grouped+ * report. CLI sibling of the `audit` MCP tool and `GET /api/audit`.+ *+ * Server-first by necessity, not preference: the links validator reads the+ * running server's in-memory backlink index (there is no disk-only dead-link+ * oracle), so this command delegates to the project's live server instead of+ * walking files. No running server is an actionable error — `ok lint` remains+ * the headless, lint-only alternative.+ */++import { isAbsolute, relative, resolve, sep } from 'node:path';+import {+ clientVersionHeaders,+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+} from '@inkeep/open-knowledge-core';+import {+ type Config,+ RUNTIME_VERSION,+ readServerLock,+ resolveContentDir,+ resolveLockDir,+} from '@inkeep/open-knowledge-server';+import { Command } from 'commander';+import { getInvocationCwd } from '../project-anchor.ts';+import { formatLintReport, type LintReportInput } from './lint.ts';++interface AuditOptions {+ json?: boolean;+ errorsOnly?: boolean;+}++interface AuditIo {+ out: (line: string) => void;+ err: (line: string) => void;+}++const defaultIo: AuditIo = {+ out: (line) => process.stdout.write(`${line}\n`),+ err: (line) => process.stderr.write(`${line}\n`),+};++const SERVER_NOT_RUNNING_MESSAGE =+ 'OpenKnowledge server is not running — the links validator needs the live backlink index. ' ++ 'Start it with `ok start` (or open OK Desktop) and re-run. For headless lint-only checks, use `ok lint`.';++export function auditCommand(getConfig: () => Config): Command {+ return new Command('audit')+ .description(+ 'Unified validation audit (markdown lint + broken internal links) via the running project server',+ )+ .argument('[path]', 'Folder or file to audit, relative to where you run the command')+ .option('--json', 'Emit the full structured JSON response instead of formatted text')+ .option(+ '--errors-only',+ "Exit non-zero only on error-severity problems (broken links default to warnings; the project's validation.links setting can raise them to errors)",+ )+ .action(async (path: string | undefined, opts: AuditOptions) => {+ const exitCode = await runAudit(path, opts, getConfig(), process.cwd(), getInvocationCwd());+ if (exitCode !== 0) process.exitCode = exitCode;+ });+}++/**+ * Core audit flow, separated from the Commander wiring so tests can drive it+ * with a planted lock + stubbed `fetch` and injected writers.+ */+export async function runAudit(+ path: string | undefined,+ opts: AuditOptions,+ config: Config,+ projectDir: string,+ invocationCwd: string,+ io: AuditIo = defaultIo,+): Promise<number> {+ const contentDir = resolveContentDir(config, projectDir);++ let target: string | undefined;+ if (path !== undefined) {+ const rel = toContentRelativeTarget(path, invocationCwd, contentDir);+ if (rel === null) {+ io.err(`Path is outside the content directory (${contentDir}): ${path}`);+ return 1;+ }+ target = rel === '' ? undefined : rel;+ }++ // Same server-first discovery as `ok sync`: the lock anchor is the project+ // root, and `readServerLock` already prunes stale same-host locks.+ const lock = readServerLock(resolveLockDir(projectDir));+ if (!lock || lock.port <= 0) {+ io.err(SERVER_NOT_RUNNING_MESSAGE);+ return 1;+ }++ const query = target === undefined ? '' : `?path=${encodeURIComponent(target)}`;+ let res: Response;+ try {+ res = await fetch(`http://127.0.0.1:${lock.port}/api/audit${query}`, {+ headers: clientVersionHeaders({ kind: 'cli', runtimeVersion: RUNTIME_VERSION }),+ });+ } catch (e) {+ io.err(`Could not reach the OpenKnowledge server on port ${lock.port}: ${String(e)}`);+ return 1;+ }++ if (!res.ok) {+ // RFC 9457 problem+json — `title` carries the user-visible message; fall+ // back through legacy shapes, then the HTTP status.+ const body = (await res.json().catch(() => ({}))) as {+ title?: string;+ error?: string;+ message?: string;+ };+ io.err(+ `Audit failed: ${body.title ?? body.error ?? body.message ?? `server responded with ${res.status}`}`,+ );+ return 1;+ }++ const parsed = ValidationAuditResponseSchema.safeParse(await res.json().catch(() => null));+ if (!parsed.success) {+ // Name the offending fields: the headless CI consumer has no DevTools, so+ // a client/server version skew is otherwise indistinguishable from a+ // transient parse error. The Zod issues are pure structural metadata.+ const summary = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');+ io.err(`Audit failed: unexpected response shape from the server. Schema issues: ${summary}`);+ return 1;+ }+ const result = parsed.data;++ if (opts.json === true) {+ // Unlike the MCP tool (agent-context-bound, capped at 10×10), the CLI is+ // a terminal/CI surface — emit the full uncapped plane.+ io.out(JSON.stringify(result, null, 2));+ } else {+ io.out(formatLintReport(toReportInput(result)));+ }++ const failed =+ opts.errorsOnly === true ? result.errorCount > 0 : result.errorCount + result.warningCount > 0;+ return failed ? 1 : 0;+}++/**+ * Translate the user's path (relative to where they invoked the command) into+ * the contentDir-relative, forward-slash form `GET /api/audit?path=` expects.+ * Returns `''` for the content dir itself (audit everything) and `null` when+ * the path escapes the content dir.+ */+export function toContentRelativeTarget(+ path: string,+ invocationCwd: string,+ contentDir: string,+): string | null {+ const rel = relative(contentDir, resolve(invocationCwd, path));+ if (rel === '') return '';+ if (rel.startsWith('..') || isAbsolute(rel)) return null;+ return rel.split(sep).join('/');+}++function toReportInput(result: ValidationAuditResponse): LintReportInput {+ return {+ files: result.files.map((f) => ({ file: f.file, fixed: false, diagnostics: f.diagnostics })),+ warnings: result.warnings,+ fileCount: result.fileCount,+ errorCount: result.errorCount,+ warningCount: result.warningCount,+ fixedCount: 0,+ };+}diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.tsindex 211af175e..408d824d9 100644--- a/packages/cli/src/commands/lint.ts+++ b/packages/cli/src/commands/lint.ts@@ -14,7 +14,7 @@ import {} 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 { 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';@@ -75,8 +75,38 @@ function hasProblems(result: LintRunResult): boolean {return result.errorCount > 0 || result.warningCount > 0;}+/**+ * Structural report input: the fields the renderer actually reads. Wire+ * payloads type `source`/`severity` as plain strings (loose by design so a+ * new validator doesn't fail an older client's schema), so the renderer must+ * not require the narrower in-process `LintDiagnostic` — `ok audit` feeds+ * `/api/audit`'s unified plane through this same formatter.+ */+interface ReportDiagnostic {+ range: { start: { line: number; character: number } };+ severity: string;+ source: string;+ code: string;+ message: string;+}++interface ReportFile {+ file: string;+ fixed: boolean;+ diagnostics: ReportDiagnostic[];+}++export interface LintReportInput {+ files: ReportFile[];+ warnings: string[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ fixedCount: number;+}+/** Render one file's heading + its diagnostics as report lines. */-function renderFileBlock(file: FileLintResult): string[] {+function renderFileBlock(file: ReportFile): 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.@@ -89,7 +119,7 @@ function renderFileBlock(file: FileLintResult): string[] {}/** Render an eslint/markdownlint-style grouped report. */-export function formatLintReport(result: LintRunResult): string {+export function formatLintReport(result: LintReportInput): string {const lines: string[] = [];for (const file of result.files) {if (file.diagnostics.length > 0) lines.push(...renderFileBlock(file));diff --git a/packages/cli/src/content/lint-runner.ts b/packages/cli/src/content/lint-runner.tsindex db6f3475d..fc9927f73 100644--- a/packages/cli/src/content/lint-runner.ts+++ b/packages/cli/src/content/lint-runner.ts@@ -28,7 +28,7 @@ import {resolveNativeConfigForDoc,} from '@inkeep/open-knowledge-server';-export interface FileLintResult {+interface FileLintResult {/** Path relative to `contentDir` (as produced by `node:path`). */file: string;diagnostics: LintDiagnostic[];diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 2f30860be..96dbf267b 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -206,6 +206,10 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''telemetry.localSink.enabled','telemetry.localSink.logs.maxBytes','telemetry.localSink.spans.maxBytes',+ // `validation.*` — the audit plane's non-plugin knobs (broken-link+ // posture + file-tree indicators), shared like `contentRules.*`.+ 'validation.fileTreeIndicators',+ 'validation.links',]);});diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex ca830d881..ed44d0f7f 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 { DEFAULT_LINKS_VALIDATION, LINKS_VALIDATION_SETTINGS } from '../markdown/lint/types.ts';import { THEME_PLUGIN_IDS } from '../theme/theme-plugins.ts';import { fieldRegistry } from './field-registry.ts';@@ -673,6 +674,40 @@ export const ConfigSchema = z.looseObject({.default({ enabled: false }),}).default({ markdownlint: { enabled: false } }),+ // Validation-surface behavior (the unified audit plane's non-plugin knobs).+ // PROJECT scope, like `contentRules`: how broken links are classified and+ // whether the file tree surfaces problem indicators are team-shared+ // authoring decisions. Deliberately a SIBLING of `contentRules`, not a child+ // — `contentRules`' direct children are exactly the lint-plugin slices, a+ // lockstep contract enforced by `linter-leaf-registry-consistency.test.ts`.+ validation: z+ .looseObject({+ // 'off' hides broken-link findings from the whole plane (audit route,+ // MCP audit tool, ok audit, Problems panel, tree); 'warning'/'error'+ // set their severity. Default warning: a broken link is often a typo+ // or a page-yet-to-be-written, not necessarily an error.+ links: z+ .enum(LINKS_VALIDATION_SETTINGS)+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description:+ "How broken internal links are reported on the validation plane: 'off' hides them, 'warning' (default) or 'error' sets their severity.",+ })+ .default(DEFAULT_LINKS_VALIDATION),+ fileTreeIndicators: z+ .boolean()+ .register(fieldRegistry, {+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description:+ 'Whether the file tree tints and badges files that have validation problems.',+ })+ .default(true),+ })+ .default({ links: DEFAULT_LINKS_VALIDATION, fileTreeIndicators: true }),// PROJECT-LOCAL scope: external link-hover previews send the hovered URL to// the destination site to fetch its metadata (egress). Read per-machine from// the project-local layer, never a committed/shared config, so one clone'sdiff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 206eb99e2..8ab50c02e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -452,6 +452,7 @@ export { MarkdownManager, type SerializeCallOptions } from './markdown/index.ts'export {applyTextEdits,canonicalRuleId,+ DEFAULT_LINKS_VALIDATION,DEFAULT_LINTER_CONFIG,DEFAULT_MARKDOWNLINT_CONFIG,displayCategoryForRule,@@ -459,7 +460,9 @@ export {fixDocument,fixMarkdownText,isMarkdownlintJsonConfig,+ LINKS_VALIDATION_SETTINGS,LINT_PLUGINS,+ type LinksValidationSetting,type LintAuditResponse,LintAuditResponseSchema,type LintConfigResponse,@@ -495,6 +498,12 @@ export {resolveMarkdownlintConfig,runMarkdownlint,toEffectiveBase,+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+ type ValidationDiagnostic,+ type ValidationDocResult,+ ValidationDocResultSchema,+ type ValidationSource,} from './markdown/lint/index.ts';export { markdownToHtml, mdastToHtml } from './markdown/mdast-to-html.ts';export { normalizeDocRelativeAssetUrl } from './markdown/resolve-image-url.ts';diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex e78a1381d..9291ee4db 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -81,6 +81,26 @@ export const LintAuditResponseSchema = z.object({export type LintDocResult = z.infer<typeof LintDocResultSchema>;export type LintAuditResponse = z.infer<typeof LintAuditResponseSchema>;+const ValidationDiagnosticSchema = LintDiagnosticSchema.extend({+ linkTarget: z.string().optional(),+});++export const ValidationDocResultSchema = z.object({+ file: z.string(),+ diagnostics: z.array(ValidationDiagnosticSchema),+});++export const ValidationAuditResponseSchema = z.object({+ files: z.array(ValidationDocResultSchema),+ fileCount: z.number(),+ errorCount: z.number(),+ warningCount: z.number(),+ warnings: z.array(z.string()),+});++export type ValidationDocResult = z.infer<typeof ValidationDocResultSchema>;+export type ValidationAuditResponse = z.infer<typeof ValidationAuditResponseSchema>;+export const LintFixRequestSchema = z.object({docName: safeDocNameField,diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 8a154ce30..754f5e68e 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -45,6 +45,10 @@ export {MarkdownlintRuleWriteRequestSchema,type PersistedLinterConfig,toEffectiveBase,+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+ type ValidationDocResult,+ ValidationDocResultSchema,} from './config-schemas.ts';export { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';export { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';@@ -64,6 +68,7 @@ export {} from './rule-catalog-categories.ts';export { applyTextEdits } from './text-edits.ts';export type {+ LinksValidationSetting,LintDiagnostic,LintPosition,LintRange,@@ -76,4 +81,7 @@ export type {RuleCatalogEntry,RuleOptionSpec,RuleOptionType,+ ValidationDiagnostic,+ ValidationSource,} from './types.ts';+export { DEFAULT_LINKS_VALIDATION, LINKS_VALIDATION_SETTINGS } from './types.ts';diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 617f6e5b9..0f756702b 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -27,6 +27,18 @@ export interface LintDiagnostic {fixes?: LintTextEdit[];}+const VALIDATION_SOURCES = [...LINT_PLUGIN_IDS, 'links'] as const;+export type ValidationSource = (typeof VALIDATION_SOURCES)[number];++export interface ValidationDiagnostic extends Omit<LintDiagnostic, 'source'> {+ source: ValidationSource;+ linkTarget?: string;+}++export const LINKS_VALIDATION_SETTINGS = ['off', 'warning', 'error'] as const;+export type LinksValidationSetting = (typeof LINKS_VALIDATION_SETTINGS)[number];+export const DEFAULT_LINKS_VALIDATION: LinksValidationSetting = 'warning';+type MarkdownlintRuleParams = Record<string, unknown>;export const MARKDOWNLINT_RULE_SEVERITIES = ['error', 'warning'] as const;diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.tsindex c99738746..d7758a76d 100644--- a/packages/core/src/schemas/api/agent-write.ts+++ b/packages/core/src/schemas/api/agent-write.ts@@ -275,19 +275,20 @@ export const RenderWarningSchema = zexport 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+ * A content-rule violation on the post-write document — the full validation+ * plane: markdown-lint findings AND broken internal links. 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.+ * config + the project's `validation.links` posture, 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`). */+ /** Which validator produced it — a plugin registry id (e.g. `markdownlint`) or `links`. */source: z.string(),- /** The engine's native rule id, unprefixed (e.g. `MD010`). */+ /** The engine's native rule id, unprefixed (e.g. `MD010`, `dead-link`). */code: z.string(),/** Human-readable, already-resolved message. */message: z.string(),@@ -295,6 +296,8 @@ export const LintViolationWarningSchema = z/** 1-based line / column in the source document (agent-facing display units). */line: z.number().int().positive(),column: z.number().int().positive(),+ /** `links` findings only: the unresolved target docName, verbatim. */+ linkTarget: z.string().optional(),}).loose() satisfies StandardSchemaV1;export type LintViolationWarning = z.infer<typeof LintViolationWarningSchema>;diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 42d1d204e..9e74691ef 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -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 — 20 tools (router; the MCP tool descriptions carry each tool's full contract)+## Tool index — 21 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), `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`).+- **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` (markdown-lint violations: pass `document` for one doc, omit for the whole project; pass `fix: true` with `document` to auto-fix fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one read-only report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`).- **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`.@@ -82,7 +82,7 @@ Knowledge-base docs are factual artifacts. Every claim must be traceable, and **## Linking — standard markdown links (MUST)-Link every noun-phrase that names another document — `[text](./relative/path.md)` — and link liberally. **Every link must resolve to a doc that exists by the time you're done** (a same-pass forward-reference you create later in the pass is fine; for one that genuinely won't exist, leave the mention as plain prose + a tracked task). Never backtick a link (`` `[text](./foo.md)` `` is a bug) and never use HTML `<a>`. **Read `brokenLinks` on every `write`/`edit` response: `[]` means all links resolve; a populated list names each broken `href` + `reason` (`no-such-doc` / `no-such-file` / `unresolvable`) — fix them in a follow-up `edit`.** `links({ kind: "dead" })` is the authoritative end-state audit (the editor's red-underline is slug-tolerant and lies, so trust the tool). External web sources are NOT inline body links (see Grounding). Full rule set + the `[[Page]]` legacy note: `references/linking.md`.+Link every noun-phrase that names another document — `[text](./relative/path.md)` — and link liberally. **Every link must resolve to a doc that exists by the time you're done** (a same-pass forward-reference you create later in the pass is fine; for one that genuinely won't exist, leave the mention as plain prose + a tracked task). Never backtick a link (`` `[text](./foo.md)` `` is a bug) and never use HTML `<a>`. **Read `brokenLinks` on every `write`/`edit` response: `[]` means all links resolve; a populated list names each broken `href` + `reason` (`no-such-doc` / `no-such-file` / `unresolvable`) — fix them in a follow-up `edit`.** `audit` is the authoritative end-state link check (the editor's red-underline is slug-tolerant and lies, so trust the tool). External web sources are NOT inline body links (see Grounding). Full rule set + the `[[Page]]` legacy note: `references/linking.md`.## Folders, frontmatter, templatesdiff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 2d0e3cfec..0a821bbb6 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -70,6 +70,7 @@ import {createWorkspaceSearchDocument,DEFAULT_ATTACHMENT_FOLDER_PATH,DEFAULT_DEDUP_MODE,+ DEFAULT_LINKS_VALIDATION,DEFAULT_LINTER_CONFIG,DeadLinksSuccessSchema,DeletePathRequestSchema,@@ -111,6 +112,7 @@ import {LinkGraphSuccessSchema,LinkPreviewRequestSchema,LinkPreviewResponseSchema,+ type LinksValidationSetting,LintAuditResponseSchema,LintConfigResponseSchema,LintDocResultSchema,@@ -246,6 +248,8 @@ import {UploadRequestSchema,unwrapFrontmatterFences,updateWorkspaceSearchCorpus,+ ValidationAuditResponseSchema,+ type ValidationDiagnostic,type WorkspaceSearchCorpus,type WorkspaceSearchDocument,type WorkspaceSearchIntent,@@ -365,6 +369,7 @@ import {resolveEffectiveLinterConfig,resolveNativeConfigForDoc,} from './lint/resolve-config.ts';+import { createProjectValidators, runValidationAudit } from './lint/validation-audit.ts';import { validateMermaidFences } from './mermaid-validator.ts';import {extractPageIcon,@@ -474,7 +479,7 @@ import {} from './backlink-index.ts';import { getBootTimings } from './boot-timings.ts';import { composeAndWriteRawBody, type PrecomputedParse, replaceRawBody } from './bridge-intake.ts';-import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';+import { isConfigDoc, isLinkIndexExcludedDoc, isSystemDoc } from './cc1-broadcast.ts';import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';import type { ResolveStrategy } from './conflict-storage.ts';import type { ContentFilter } from './content-filter.ts';@@ -2903,6 +2908,11 @@ export interface ApiExtensionOptions {* Omitted in tests → falls back to `DEFAULT_LINTER_CONFIG`.*/getLinterBaseConfig?: () => LinterConfig;+ /**+ * Fresh-per-request broken-link posture (`validation.links`). Omitted in+ * tests → falls back to the default ('warning').+ */+ getLinksValidationSetting?: () => LinksValidationSetting;}interface WorkspaceSearchCacheEntry {@@ -3021,6 +3031,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {getSemanticSimilarityFloor,embeddingsSecretsFile,getLinterBaseConfig,+ getLinksValidationSetting,ephemeral = false,linkPreviewFetch,getLinkPreviewsEnabled,@@ -18941,11 +18952,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// `.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.+ // advisory channel — the full validation plane, not just lint: every enabled+ // lint source PLUS broken internal links, so an agent that writes a dead+ // wiki-link hears about it on the write response without a separate `audit`+ // round-trip. 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 and links are off.const LINT_VIOLATION_CAP = 10;async function computeLintViolations(source: string,@@ -18953,7 +18965,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {): 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+ // already committed (CRDT + disk + snapshot), so a validation 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 {@@ -18961,7 +18973,41 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {docName,onProblem: (problem) => log.warn({ problem, docName }, '[lint] native config problem'),});- return (await lintDocument(source, effective, docName))+ const lintFindings = await lintDocument(source, effective, docName);++ // Links plane, via the SAME audit validator the Problems panel and the+ // `audit` tool consume (one canonical predicate, honoring the project's+ // `validation.links` posture). The live-derived index updates on a+ // 100 ms debounce AFTER a change, so at this point it does not yet see+ // the write being advised — refresh this one doc synchronously first+ // (idempotent: the debounced pass re-applies the same bytes).+ let linkFindings: ValidationDiagnostic[] = [];+ const linksSetting = getLinksValidationSetting?.() ?? DEFAULT_LINKS_VALIDATION;+ if (backlinkIndex && linksSetting !== 'off' && !isLinkIndexExcludedDoc(docName)) {+ backlinkIndex.updateDocumentFromMarkdown(docName, source);+ const linksValidator = createProjectValidators({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig: base,+ backlinkIndex,+ linksValidation: linksSetting,+ admittedDocNames: collectAdmittedDocNames,+ docFilePathFor: (d) => resolveDocFilePath(contentDir, d),+ }).find((validator) => validator.id === 'links');+ if (linksValidator) {+ const run = await linksValidator.run({+ targetPath: resolveDocFilePath(contentDir, docName) ?? `${docName}.md`,+ });+ linkFindings = run.files.flatMap((file) => file.diagnostics);+ }+ }++ return [...lintFindings, ...linkFindings]+ .sort(+ (a, b) =>+ a.range.start.line - b.range.start.line ||+ a.range.start.character - b.range.start.character,+ ).slice(0, LINT_VIOLATION_CAP).map((d) => ({kind: 'lint-violation' as const,@@ -18972,11 +19018,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// 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,+ ...('linkTarget' in d && d.linkTarget !== undefined ? { linkTarget: d.linkTarget } : {}),}));} catch (err) {log.warn({ err, docName },- '[lint] advisory lint pass failed post-write; omitting advisories',+ '[lint] advisory validation pass failed post-write; omitting advisories',);return [];}@@ -19179,6 +19226,66 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'lint-audit', method: 'GET', skipBodyParse: true },);+ // Unified validation audit: every registered project validator (markdownlint+ // walk + backlink-index dead-link read) merged into one source-tagged plane.+ // Additive alongside /api/lint/audit and /api/dead-links, which keep their+ // single-validator contracts.+ const handleAudit = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const rawTarget = url.searchParams.get('path');+ let target = rawTarget === null || rawTarget === '' ? undefined : rawTarget;+ // Absolute paths and traversal must not reach the validators: the+ // lint walk reads file bytes under this scope, so an unchecked path+ // is an arbitrary-directory read for any connected caller.+ if (target !== undefined && !isValidRelativeContentPath(target)) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid path.', {+ handler: 'audit',+ });+ return;+ }+ // `doc` scopes by docName (extension-less). The client freshness path+ // knows docNames from disk-ack frames, never file extensions, so the+ // extension resolution has to happen here. A doc indexed from a live+ // CRDT session may not be on disk yet — fall back to the default+ // extension so the links validator can still scope to it (mirrors the+ // links validator's own fallback).+ const rawDoc = url.searchParams.get('doc');+ const docParam = rawDoc === null || rawDoc === '' ? undefined : rawDoc;+ if (docParam !== undefined) {+ if (target !== undefined || !isValidRelativeContentPath(docParam)) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid doc.', {+ handler: 'audit',+ });+ return;+ }+ target = resolveDocFilePath(contentDir, docParam) ?? `${docParam}.md`;+ }+ const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;+ const validators = createProjectValidators({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig,+ liveSourceFor: liveLintSourceFor,+ backlinkIndex: backlinkIndex ?? null,+ linksValidation: getLinksValidationSetting?.(),+ admittedDocNames: collectAdmittedDocNames,+ docFilePathFor: (docName) => resolveDocFilePath(contentDir, docName),+ });+ const result = await runValidationAudit(validators, { targetPath: target });+ successResponse(res, 200, ValidationAuditResponseSchema, result, { handler: 'audit' });+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to audit project.', {+ handler: 'audit',+ cause: e,+ });+ }+ },+ { handler: 'audit', method: 'GET', skipBodyParse: true },+ );+const handleLintFix = withValidation(LintFixRequestSchema,async (_req, res, body) => {@@ -19574,6 +19681,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {'/api/lint': handleLintDoc,'/api/lint/audit': handleLintAudit,'/api/lint/fix': handleLintFix,+ '/api/audit': handleAudit,'/api/suggest-links': handleSuggestLinks,'/api/page-headings': handlePageHeadings,'/api/create-page': handleCreatePage,diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 224f7cd90..9a1ac8ed1 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -44,6 +44,8 @@ describe('extractWikiLinksFromMarkdown', () => {target: 'beta',anchor: null,snippet: 'Alpha links to beta for deployment notes.',+ line: 0,+ column: 15,},]);});@@ -64,6 +66,8 @@ describe('extractWikiLinksFromMarkdown', () => {target: 'alpha',anchor: null,snippet: 'See alpha.',+ line: 0,+ column: 4,},]);});@@ -76,6 +80,8 @@ describe('extractWikiLinksFromMarkdown', () => {target: 'beta',anchor: null,snippet: 'See beta.',+ line: 2,+ column: 4,},]);});@@ -92,8 +98,8 @@ describe('extractWikiLinksFromMarkdown', () => {].join('\n');expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'alpha', anchor: null, snippet: 'See alpha.' },- { target: 'gamma', anchor: null, snippet: 'And gamma.' },+ { target: 'alpha', anchor: null, snippet: 'See alpha.', line: 0, column: 4 },+ { target: 'gamma', anchor: null, snippet: 'And gamma.', line: 6, column: 4 },]);});@@ -111,8 +117,8 @@ describe('extractWikiLinksFromMarkdown', () => {].join('\n');expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'alpha', anchor: null, snippet: 'Before alpha.' },- { target: 'beta', anchor: null, snippet: 'After beta.' },+ { target: 'alpha', anchor: null, snippet: 'Before alpha.', line: 0, column: 7 },+ { target: 'beta', anchor: null, snippet: 'After beta.', line: 6, column: 6 },]);});@@ -120,8 +126,20 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'See [[alpha]] and [[beta]] for more.\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'alpha', anchor: null, snippet: 'See alpha and beta for more.' },- { target: 'beta', anchor: null, snippet: 'See alpha and beta for more.' },+ {+ target: 'alpha',+ anchor: null,+ snippet: 'See alpha and beta for more.',+ line: 0,+ column: 4,+ },+ {+ target: 'beta',+ anchor: null,+ snippet: 'See alpha and beta for more.',+ line: 0,+ column: 14,+ },]);});@@ -129,7 +147,13 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'See [[guide#installation]] for setup.\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'guide', anchor: 'installation', snippet: 'See guide#installation for setup.' },+ {+ target: 'guide',+ anchor: 'installation',+ snippet: 'See guide#installation for setup.',+ line: 0,+ column: 4,+ },]);});@@ -137,7 +161,7 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'See [[guide|the guide]] for setup.\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'guide', anchor: null, snippet: 'See the guide for setup.' },+ { target: 'guide', anchor: null, snippet: 'See the guide for setup.', line: 0, column: 4 },]);});@@ -145,7 +169,7 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'See [[API#auth|Auth Docs]] for setup.\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'API', anchor: 'auth', snippet: 'See Auth Docs for setup.' },+ { target: 'API', anchor: 'auth', snippet: 'See Auth Docs for setup.', line: 0, column: 4 },]);});@@ -155,7 +179,13 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'Not a link: \\[[page]] but [[real]] is.\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'real', anchor: null, snippet: 'Not a link: [[page]] but real is.' },+ {+ target: 'real',+ anchor: null,+ snippet: 'Not a link: [[page]] but real is.',+ line: 0,+ column: 25,+ },]);});@@ -165,7 +195,13 @@ describe('extractWikiLinksFromMarkdown', () => {const markdown = 'See `foo``bar` and [[target]].\n';expect(extractWikiLinksFromMarkdown(markdown)).toEqual([- { target: 'target', anchor: null, snippet: 'See foo``bar and target.' },+ {+ target: 'target',+ anchor: null,+ snippet: 'See foo``bar and target.',+ line: 0,+ column: 17,+ },]);});@@ -183,9 +219,17 @@ describe('extractWikiLinksFromMarkdown', () => {const links = extractWikiLinksFromMarkdown(markdown);const elapsed = performance.now() - start;- expect(links).toEqual([{ target: 'target', anchor: null, snippet: 'See target.' }]);+ expect(links).toEqual([+ { target: 'target', anchor: null, snippet: 'See target.', line: 2, column: 4 },+ ]);expect(elapsed).toBeLessThan(1000);});++ test('offsets link lines by the caller-supplied lineOffset', () => {+ expect(extractWikiLinksFromMarkdown('See [[alpha]].', '', 3)).toEqual([+ { target: 'alpha', anchor: null, snippet: 'See alpha.', line: 3, column: 4 },+ ]);+ });});describe('BacklinkIndex', () => {@@ -467,6 +511,142 @@ describe('BacklinkIndex', () => {}});+ test('getDeadLinks positions each broken link at its 0-based full-doc source line', () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-link-lines-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ const index = new BacklinkIndex({ projectDir, contentDir });+ // Frontmatter and the fenced decoy shift the body: a body-relative or+ // fence-blind line count would land on the wrong line.+ const markdown = [+ '---', // line 0+ 'title: Alpha', // line 1+ '---', // line 2+ '# Alpha', // line 3+ '', // line 4+ '```ts', // line 5+ 'const decoy = "[[ghost-wiki]] and [gone](./ghost-md.md)";', // line 6+ '```', // line 7+ '', // line 8+ 'See [[ghost-wiki]].', // line 9+ 'And [also gone](./ghost-md.md).', // line 10+ '',+ ].join('\n');+ index.updateDocumentFromMarkdown('alpha', markdown);++ const deadLinks = index.getDeadLinks(['alpha']);+ expect(deadLinks.map((entry) => entry.target)).toEqual(['ghost-md', 'ghost-wiki']);++ const mdSource = deadLinks[0]?.sources[0];+ const wikiSource = deadLinks[1]?.sources[0];+ expect(wikiSource).toEqual(expect.objectContaining({ source: 'alpha', line: 9 }));+ expect(mdSource).toEqual(expect.objectContaining({ source: 'alpha', line: 10 }));+ // Column is approximate by contract (flat-text offset) — assert presence only.+ expect(typeof wikiSource?.column).toBe('number');+ expect(typeof mdSource?.column).toBe('number');+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a target broken from multiple source docs carries a per-source position', () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-link-multi-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ const index = new BacklinkIndex({ projectDir, contentDir });+ index.updateDocumentFromMarkdown('alpha', 'See [[ghost]].\n');+ index.updateDocumentFromMarkdown('beta', '# Beta\n\nAlso [[ghost]].\n');++ const deadLinks = index.getDeadLinks(['alpha', 'beta']);+ expect(deadLinks.map((entry) => entry.target)).toEqual(['ghost']);+ expect(deadLinks[0]?.sources).toEqual([+ expect.objectContaining({ source: 'alpha', line: 0 }),+ expect.objectContaining({ source: 'beta', line: 2 }),+ ]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('dead-link positions survive a cache save/load round-trip', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-link-cache-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ const index = new BacklinkIndex({ projectDir, contentDir });+ index.updateDocumentFromMarkdown('alpha', '# Alpha\n\nSee [[ghost]].\n');+ await index.saveToDisk();++ const reloaded = new BacklinkIndex({ projectDir, contentDir });+ expect(await reloaded.loadFromDisk()).toBe(true);+ expect(reloaded.getDeadLinks(['alpha'])[0]?.sources[0]).toEqual(+ expect.objectContaining({ source: 'alpha', line: 2 }),+ );+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a pre-position backlinks cache loads and serves entries without positions', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-link-legacy-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ // The exact on-disk shape older servers wrote: backward entries carry only+ // {source, anchor, snippet}.+ const cacheDir = join(projectDir, '.ok', LOCAL_DIR, 'cache', 'main');+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(+ join(cacheDir, 'backlinks.json'),+ JSON.stringify({+ backward: {+ ghost: [{ source: 'alpha', anchor: null, snippet: 'See ghost.' }],+ // Invalid positions (hand-edited or corrupt cache) must degrade to+ // "position unknown", not leak through to consumers — including+ // negative and fractional numbers, which pass a bare typeof check.+ wraith: [+ { source: 'alpha', anchor: null, snippet: 'See wraith.', line: '7', column: -2 },+ ],+ shade: [{ source: 'alpha', anchor: null, snippet: 'See shade.', line: 1.5 }],+ },+ forward: { alpha: ['ghost', 'wraith', 'shade'] },+ externalForward: {},+ }),+ 'utf-8',+ );++ const index = new BacklinkIndex({ projectDir, contentDir });+ expect(await index.loadFromDisk()).toBe(true);+ expect(index.getBacklinks('ghost')).toEqual([+ { source: 'alpha', anchor: null, snippet: 'See ghost.' },+ ]);+ const legacySource = index.getDeadLinks(['alpha']).find((e) => e.target === 'ghost')+ ?.sources[0];+ expect(legacySource).toEqual(+ expect.objectContaining({ source: 'alpha', snippet: 'See ghost.' }),+ );+ expect(legacySource?.line).toBeUndefined();+ expect(legacySource?.column).toBeUndefined();+ const corruptSource = index.getDeadLinks(['alpha']).find((e) => e.target === 'wraith')+ ?.sources[0];+ expect(corruptSource?.line).toBeUndefined();+ expect(corruptSource?.column).toBeUndefined();+ const fractionalSource = index.getDeadLinks(['alpha']).find((e) => e.target === 'shade')+ ?.sources[0];+ expect(fractionalSource?.line).toBeUndefined();++ // Re-indexing the source doc upgrades its entry with a position.+ index.updateDocumentFromMarkdown('alpha', 'See [[ghost]].\n');+ expect(index.getDeadLinks(['alpha'])[0]?.sources[0]).toEqual(+ expect.objectContaining({ source: 'alpha', line: 0 }),+ );+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('rebuilds from disk and persists cache per branch', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-project-'));const contentDir = join(projectDir, 'content');@@ -1107,71 +1287,107 @@ describe('extractMarkdownLinksFromMarkdown', () => {test('extracts relative inline markdown links', () => {const md = 'See [related](./other.md) for details.';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual<ExtractedWikiLink[]>([- { target: 'other', anchor: null, snippet: 'See related for details.' },+ { target: 'other', anchor: null, snippet: 'See related for details.', line: 0, column: 4 },]);});test('extracts root-absolute markdown links from the content root', () => {const md = 'See [the guide](/docs/guide.md) for details.';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual<ExtractedWikiLink[]>([- { target: 'docs/guide', anchor: null, snippet: 'See the guide for details.' },+ {+ target: 'docs/guide',+ anchor: null,+ snippet: 'See the guide for details.',+ line: 0,+ column: 4,+ },]);});test('extracts multiple markdown links from the same line', () => {const md = 'See [page A](./a.md) and [page B](./b.md) for more.';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual<ExtractedWikiLink[]>([- { target: 'a', anchor: null, snippet: 'See page A and page B for more.' },- { target: 'b', anchor: null, snippet: 'See page A and page B for more.' },+ { target: 'a', anchor: null, snippet: 'See page A and page B for more.', line: 0, column: 4 },+ {+ target: 'b',+ anchor: null,+ snippet: 'See page A and page B for more.',+ line: 0,+ column: 15,+ },]);});test('resolves links relative to the source doc directory', () => {const md = 'See [overview](../overview.md).';expect(extractMarkdownLinksFromMarkdown(md, 'folder/page')).toEqual([- { target: 'overview', anchor: null, snippet: 'See overview.' },+ { target: 'overview', anchor: null, snippet: 'See overview.', line: 0, column: 4 },]);});test('extracts internal links with optional titles', () => {const md = 'See [overview](./overview.md "Project overview") for details.';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'overview', anchor: null, snippet: 'See overview for details.' },+ {+ target: 'overview',+ anchor: null,+ snippet: 'See overview for details.',+ line: 0,+ column: 4,+ },]);});test('extracts markdown link anchors', () => {const md = 'See [install](./guide.md#install) for details.';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'guide', anchor: 'install', snippet: 'See install for details.' },+ {+ target: 'guide',+ anchor: 'install',+ snippet: 'See install for details.',+ line: 0,+ column: 4,+ },]);});test('ignores external links', () => {const md = 'Visit [example](https://example.com) and [local](./local.md).';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'local', anchor: null, snippet: 'Visit example and local.' },+ { target: 'local', anchor: null, snippet: 'Visit example and local.', line: 0, column: 18 },]);});test('ignores image syntax while still extracting sibling links', () => {const md = 'See  and [docs](./docs.md).';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'docs', anchor: null, snippet: expect.any(String) as string },+ {+ target: 'docs',+ anchor: null,+ snippet: expect.any(String) as string,+ line: 0,+ column: 41,+ },]);});test('ignores links inside fenced code blocks', () => {const md = ['See [page](./page.md).', '', '```', '[ignore](./ignore.md)', '```'].join('\n');expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'page', anchor: null, snippet: 'See page.' },+ { target: 'page', anchor: null, snippet: 'See page.', line: 0, column: 4 },]);});test('ignores links inside inline code spans', () => {const md = 'Use `[skip](./skip.md)` then [real](./real.md).';expect(extractMarkdownLinksFromMarkdown(md, 'notes')).toEqual([- { target: 'real', anchor: null, snippet: expect.any(String) as string },+ {+ target: 'real',+ anchor: null,+ snippet: expect.any(String) as string,+ line: 0,+ column: 27,+ },]);});@@ -1186,6 +1402,12 @@ describe('extractMarkdownLinksFromMarkdown', () => {expect(extractMarkdownLinksFromMarkdown('Just text.', 'notes')).toEqual([]);expect(extractMarkdownLinksFromMarkdown('[ext](https://example.com)', 'notes')).toEqual([]);});++ test('offsets link lines by the caller-supplied lineOffset', () => {+ expect(extractMarkdownLinksFromMarkdown('Read [the guide](./guide.md).', 'notes', 4)).toEqual([+ { target: 'guide', anchor: null, snippet: 'Read the guide.', line: 4, column: 5 },+ ]);+ });});// ── BacklinkIndex: markdown link integration ───────────────────────────────────diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex ff37046f1..13b0ded51 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -46,6 +46,17 @@ export interface ExtractedWikiLink {target: string;anchor: string | null;snippet: string | null;+ /**+ * 0-based source line of the occurrence (the extractor's `lineOffset` param+ * folds a stripped-frontmatter prefix back in, keeping this full-doc exact).+ */+ line?: number;+ /**+ * 0-based offset into the markdown-stripped flat rendering of the line —+ * approximate against the raw source column (escapes, inline-code backticks,+ * and leading list/heading prefixes are collapsed before offsets are taken).+ */+ column?: number;}interface ExtractedExternalLink {@@ -58,6 +69,14 @@ export interface BacklinkEntry {source: string;anchor: string | null;snippet: string | null;+ /**+ * 0-based full-doc position of the link occurrence in the source doc (line+ * exact, column approximate — see `ExtractedWikiLink`). Absent on entries+ * deserialized from a cache written before positions were indexed; re-indexing+ * the source doc fills them in.+ */+ line?: number;+ column?: number;}interface DocumentForwardLinkEntry {@@ -104,8 +123,15 @@ export type GraphNode = DocGraphNode | ExternalGraphNode;export { isOrphanMode, ORPHAN_MODES, type OrphanMode };+interface BackwardLinkMeta {+ anchor: string | null;+ snippet: string | null;+ line?: number;+ column?: number;+}+interface BranchGraphState {- backward: Map<string, Map<string, { anchor: string | null; snippet: string | null }>>;+ backward: Map<string, Map<string, BackwardLinkMeta>>;forward: Map<string, Set<string>>;externalForward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;externalBackward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;@@ -174,18 +200,23 @@ function parseSkillBundleDocAnyScope(}function mergeLinkMeta(- existing: { anchor: string | null; snippet: string | null } | undefined,- next: { anchor: string | null; snippet: string | null },-): { anchor: string | null; snippet: string | null } {+ existing: BackwardLinkMeta | undefined,+ next: BackwardLinkMeta,+): BackwardLinkMeta {if (!existing) return next;+ // The position travels as a (line, column) unit — mixing one occurrence's+ // line with another's column would point at a coordinate no link occupies.+ const positioned = existing.line !== undefined ? existing : next;return {anchor: existing.anchor ?? next.anchor,snippet: existing.snippet ?? next.snippet,+ line: positioned.line,+ column: positioned.column,};}function getRepresentativeAnchor(- sources: Map<string, { anchor: string | null; snippet: string | null }> | undefined,+ sources: Map<string, BackwardLinkMeta> | undefined,): string | null {if (!sources) return null;for (const [, meta] of [...sources.entries()].sort(([a], [b]) => a.localeCompare(b))) {@@ -561,16 +592,36 @@ function extractExternalMarkdownLinksFromLine(return { text: flatText, occurrences };}+/**+ * Number of source lines a `stripFrontmatter` frontmatter block occupied —+ * the line offset that maps body-relative extractor lines back to full-doc+ * lines. The matched block always ends in a newline (or sits at EOF with an+ * empty body), so counting newlines after the extractors' own CRLF/CR+ * normalization equals the count of full lines removed.+ */+function frontmatterLineCount(frontmatter: string): number {+ if (!frontmatter) return 0;+ const normalized = frontmatter.replaceAll('\r\n', '\n').replaceAll('\r', '\n');+ let count = 0;+ for (let i = 0; i < normalized.length; i++) {+ if (normalized[i] === '\n') count++;+ }+ return count;+}+export function extractMarkdownLinksFromMarkdown(markdown: string,sourceDocName: string,+ lineOffset = 0,): ExtractedWikiLink[] {const source = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');const lines = source.split('\n');const links: ExtractedWikiLink[] = [];let fence: FenceState | null = null;- for (const line of lines) {+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {+ const line = lines[lineIndex] ?? '';+if (fence) {if (isFenceClose(line, fence)) fence = null;} else {@@ -584,6 +635,8 @@ export function extractMarkdownLinksFromMarkdown(target,anchor,snippet: snippetAround(extracted.text, start, end),+ line: lineOffset + lineIndex,+ column: start,})),);}@@ -596,6 +649,7 @@ export function extractMarkdownLinksFromMarkdown(export function extractWikiLinksFromMarkdown(markdown: string,sourceDocName = '',+ lineOffset = 0,): ExtractedWikiLink[] {const source = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');const lines = source.split('\n');@@ -618,6 +672,8 @@ export function extractWikiLinksFromMarkdown(target,anchor,snippet: snippetAround(extracted.text, start, end),+ line: lineOffset + lineIndex,+ column: start,})),);}@@ -872,10 +928,15 @@ function serializeState(state: BranchGraphState): SerializedBranchGraphState {backward: Object.fromEntries([...state.backward.entries()].map(([target, sources]) => [target,+ // `line`/`column` are undefined on entries carried over from a+ // pre-position cache; JSON.stringify drops them, so the on-disk shape+ // only ever holds real positions.[...sources.entries()].map(([source, meta]) => ({source,anchor: meta.anchor,snippet: meta.snippet,+ line: meta.line,+ column: meta.column,})),]),),@@ -919,6 +980,10 @@ function buildExternalBackward(return externalBackward;}+function cachePosition(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;+}+function deserializeState(data: SerializedBranchGraphState): BranchGraphState {const externalForward = new Map(Object.entries(data.externalForward ?? {}).map(([source, targets]) => [@@ -945,6 +1010,12 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {{anchor: entry.anchor ?? null,snippet: entry.snippet ?? null,+ // Cache files predating position indexing lack these fields, and+ // the cache is read without schema validation — admit non-negative+ // integers only (typeof alone lets -2 / 1.5 / NaN through to the+ // wire) so a stale/corrupt file degrades to "position unknown".+ line: cachePosition(entry.line),+ column: cachePosition(entry.column),},]),),@@ -1139,7 +1210,12 @@ export class BacklinkIndex {}sources.set(docName,- mergeLinkMeta(sources.get(docName), { anchor: link.anchor, snippet: link.snippet }),+ mergeLinkMeta(sources.get(docName), {+ anchor: link.anchor,+ snippet: link.snippet,+ line: link.line,+ column: link.column,+ }),);}@@ -1165,9 +1241,10 @@ export class BacklinkIndex {updateDocumentFromMarkdown(docName: string, markdown: string, branch = this.activeBranch): void {try {- const { body } = stripFrontmatter(markdown);- const wikiLinks = extractWikiLinksFromMarkdown(body, docName);- const mdLinks = extractMarkdownLinksFromMarkdown(body, docName);+ const { frontmatter, body } = stripFrontmatter(markdown);+ const lineOffset = frontmatterLineCount(frontmatter);+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset);+ const mdLinks = extractMarkdownLinksFromMarkdown(body, docName, lineOffset);const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);// Merge: wiki links take precedence for duplicate targets (they have richer snippet context)@@ -1385,7 +1462,13 @@ export class BacklinkIndex {target,sources: [...sources.entries()].filter(([source]) => !sourceDocSet || sourceDocSet.has(source))- .map(([source, meta]) => ({ source, anchor: meta.anchor, snippet: meta.snippet }))+ .map(([source, meta]) => ({+ source,+ anchor: meta.anchor,+ snippet: meta.snippet,+ line: meta.line,+ column: meta.column,+ })).sort((a, b) => a.source.localeCompare(b.source)),})).filter((entry) => entry.sources.length > 0)@@ -1663,9 +1746,10 @@ export class BacklinkIndex {}const { docName, mtimeMs, markdown } = result.value;mtimes.set(docName, mtimeMs);- const { body } = stripFrontmatter(markdown);- const wikiLinks = extractWikiLinksFromMarkdown(body, docName);- const mdLinks = extractMarkdownLinksFromMarkdown(body, docName);+ const { frontmatter, body } = stripFrontmatter(markdown);+ const lineOffset = frontmatterLineCount(frontmatter);+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset);+ const mdLinks = extractMarkdownLinksFromMarkdown(body, docName, lineOffset);const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);const seen = new Set(wikiLinks.map((l) => l.target));@@ -1692,7 +1776,12 @@ export class BacklinkIndex {}sources.set(docName,- mergeLinkMeta(sources.get(docName), { anchor: link.anchor, snippet: link.snippet }),+ mergeLinkMeta(sources.get(docName), {+ anchor: link.anchor,+ snippet: link.snippet,+ line: link.line,+ column: link.column,+ }),);}for (const link of externalLinks) {diff --git a/packages/server/src/lint/validation-audit.test.ts b/packages/server/src/lint/validation-audit.test.tsnew file mode 100644index 000000000..19729da52--- /dev/null+++ b/packages/server/src/lint/validation-audit.test.ts@@ -0,0 +1,343 @@+/**+ * Unit tests for the unified validation audit: the validator registry fanning+ * out to the real lint walk (`auditProject`) and a real in-memory+ * `BacklinkIndex` over a temp content tree, merged into one source-tagged+ * diagnostic plane.+ */++import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ DEFAULT_LINTER_CONFIG,+ type LinterConfig,+ SUPPORTED_DOC_EXTENSIONS,+ ValidationAuditResponseSchema,+} from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { BacklinkIndex } from '../backlink-index.ts';+import {+ createProjectValidators,+ runValidationAudit,+ type ValidationAuditDeps,+} from './validation-audit.ts';++let root: string;+let index: BacklinkIndex;+let admitted: Set<string>;++const lintOn: LinterConfig = {+ ...DEFAULT_LINTER_CONFIG,+ plugins: { markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true } },+};++// 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';++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-validation-audit-')));+ index = new BacklinkIndex({ projectDir: root, contentDir: root });+ admitted = new Set();+});+afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++/** Write the doc to disk AND index it — the two views production keeps in sync. */+function seedDoc(docName: string, markdown: string): void {+ const abs = join(root, `${docName}.md`);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, markdown, 'utf-8');+ index.updateDocumentFromMarkdown(docName, markdown);+ admitted.add(docName);+}++function docFilePathFor(docName: string): string | null {+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {+ if (existsSync(join(root, `${docName}${ext}`))) return `${docName}${ext}`;+ }+ return null;+}++function deps(overrides: Partial<ValidationAuditDeps> = {}): ValidationAuditDeps {+ return {+ projectDir: root,+ contentDir: root,+ baseConfig: lintOn,+ backlinkIndex: index,+ admittedDocNames: () => admitted,+ docFilePathFor,+ ...overrides,+ };+}++describe('runValidationAudit', () => {+ test('merges lint and link findings into one source-tagged plane', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files.map((f) => f.file)).toEqual(['dirty.md', 'linker.md']);+ const lintDiagnostics = result.files[0]?.diagnostics ?? [];+ expect(lintDiagnostics.some((d) => d.source === 'markdownlint' && d.code === 'MD010')).toBe(+ true,+ );+ expect(result.files[1]?.diagnostics).toEqual([+ {+ range: { start: { line: 2, character: 4 }, end: { line: 2, character: 4 } },+ // Default posture: broken links are warnings (validation.links).+ severity: 'warning',+ source: 'links',+ code: 'dead-link',+ message: 'Link target "ghost" does not resolve to an existing document.',+ linkTarget: 'ghost',+ },+ ]);+ expect(result.errorCount).toBe(0);+ expect(result.warningCount).toBeGreaterThan(1);+ expect(result.fileCount).toBe(2);+ // The engine plane must survive the wire schema untouched — the audit+ // route serializes through it.+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);+ });++ test('a target broken from two source docs is attributed to both files', async () => {+ seedDoc('a', '# A\n\nSee [[ghost]].\n');+ seedDoc('b', '# B\n\nAlso [[ghost]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files.map((f) => f.file)).toEqual(['a.md', 'b.md']);+ for (const entry of result.files) {+ expect(entry.diagnostics).toHaveLength(1);+ expect(entry.diagnostics[0]?.source).toBe('links');+ expect(entry.diagnostics[0]?.message).toContain('"ghost"');+ expect(entry.diagnostics[0]?.linkTarget).toBe('ghost');+ }+ expect(result.warningCount).toBe(2);+ });++ test('validation.links=error raises dead links to errors; off silences them cleanly', async () => {+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');++ const asError = await runValidationAudit(+ createProjectValidators(deps({ linksValidation: 'error' })),+ );+ expect(asError.files[0]?.diagnostics[0]?.severity).toBe('error');+ expect(asError.errorCount).toBe(1);++ const off = await runValidationAudit(createProjectValidators(deps({ linksValidation: 'off' })));+ expect(off.files.every((f) => f.diagnostics.every((d) => d.source !== 'links'))).toBe(true);+ // A deliberate off is not a degradation — no warning in the plane.+ expect(off.warnings).toEqual([]);+ });++ test('returns link findings when the project has not enabled markdownlint', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');++ const result = await runValidationAudit(+ createProjectValidators(deps({ baseConfig: DEFAULT_LINTER_CONFIG })),+ );++ expect(result.files.map((f) => f.file)).toEqual(['linker.md']);+ expect(result.files[0]?.diagnostics.map((d) => d.source)).toEqual(['links']);+ expect(result.errorCount).toBe(0);+ expect(result.warningCount).toBe(1);+ expect(result.fileCount).toBe(2);+ });++ test('a doc with lint and link problems yields one file entry sorted by position', async () => {+ seedDoc('both', '# Both\n\n\tindented with a tab\n\nSee [[ghost]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files.map((f) => f.file)).toEqual(['both.md']);+ const diagnostics = result.files[0]?.diagnostics ?? [];+ const tabIndex = diagnostics.findIndex((d) => d.code === 'MD010');+ const linkIndex = diagnostics.findIndex((d) => d.code === 'dead-link');+ expect(tabIndex).toBeGreaterThanOrEqual(0);+ expect(linkIndex).toBeGreaterThanOrEqual(0);+ expect(diagnostics[tabIndex]?.range.start.line).toBe(2);+ expect(diagnostics[linkIndex]?.range.start.line).toBe(4);+ expect(tabIndex).toBeLessThan(linkIndex);+ });++ test('a folder scope restricts both validators to docs under it', async () => {+ seedDoc('top', '# Top\n\nSee [[ghost]].\n');+ seedDoc('sub/inner', '# Inner\n\n\tindented with a tab\n\nSee [[ghost2]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()), {+ targetPath: 'sub',+ });++ expect(result.files.map((f) => f.file)).toEqual(['sub/inner.md']);+ const codes = result.files[0]?.diagnostics.map((d) => d.code) ?? [];+ expect(codes).toContain('MD010');+ expect(codes).toContain('dead-link');+ const messages = result.files.flatMap((f) => f.diagnostics.map((d) => d.message));+ expect(messages.some((m) => m.includes('"ghost"'))).toBe(false);+ expect(result.fileCount).toBe(1);+ });++ test('a doc-file scope returns exactly the whole-project findings for that doc', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');+ const validators = createProjectValidators(deps());++ const whole = await runValidationAudit(validators);+ const scoped = await runValidationAudit(validators, { targetPath: 'linker.md' });++ expect(scoped.files).toEqual([+ whole.files.find((f) => f.file === 'linker.md') ?? { file: 'missing', diagnostics: [] },+ ]);+ expect(scoped.fileCount).toBe(1);+ expect(scoped.warningCount).toBe(1);+ });++ test('a scope matching no docs returns no findings even when dead links exist elsewhere', async () => {+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()), {+ targetPath: 'empty',+ });++ expect(result.files).toEqual([]);+ expect(result.errorCount).toBe(0);+ });++ test('degrades to lint-only with a warning when no backlink index is configured', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');++ const result = await runValidationAudit(createProjectValidators(deps({ backlinkIndex: null })));++ expect(result.files.map((f) => f.file)).toEqual(['dirty.md']);+ expect(result.errorCount).toBe(0);+ expect(result.warnings).toContain(+ 'links validation unavailable: backlink index is not configured',+ );+ });++ test('an additional registered validator merges into the plane', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ const extra = {+ id: 'extra',+ run: async () => ({+ files: [+ {+ file: 'dirty.md',+ diagnostics: [+ {+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },+ severity: 'error' as const,+ source: 'links' as const,+ code: 'extra-rule',+ message: 'extra finding',+ },+ ],+ },+ ],+ fileCount: 0,+ warnings: ['extra warning'],+ }),+ };++ const result = await runValidationAudit([...createProjectValidators(deps()), extra]);++ expect(result.files.map((f) => f.file)).toEqual(['dirty.md']);+ const codes = result.files[0]?.diagnostics.map((d) => d.code) ?? [];+ expect(codes).toContain('MD010');+ expect(codes).toContain('extra-rule');+ expect(result.warnings).toContain('extra warning');+ });++ test('a clean, fully-linked project audits clean', async () => {+ seedDoc('a', '# A\n\nSee [[b]].\n');+ seedDoc('b', '# B\n\nBack to [[a]].\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files).toEqual([]);+ expect(result.errorCount).toBe(0);+ expect(result.warningCount).toBe(0);+ expect(result.fileCount).toBe(2);+ expect(result.warnings).toEqual([]);+ });++ test('a validator that throws degrades to a warning without discarding the others', async () => {+ seedDoc('dirty', DOC_WITH_TAB);+ const boom = {+ id: 'boom',+ run: async () => {+ throw new Error('kaboom');+ },+ };++ const result = await runValidationAudit([...createProjectValidators(deps()), boom]);++ // The lint validator's results survive the sibling validator's throw.+ expect(result.files.map((f) => f.file)).toEqual(['dirty.md']);+ expect(result.files[0]?.diagnostics.some((d) => d.code === 'MD010')).toBe(true);+ // The throw becomes a validator-tagged warning, not an unhandled rejection.+ expect(result.warnings).toContain('validator "boom" failed: kaboom');+ });++ test('a dead link from an admitted-but-unsaved source still names a file', async () => {+ // Admitted in the index but not on disk yet: docFilePathFor returns null, so+ // the finding falls back to the default extension rather than emitting null.+ const fakeIndex: Pick<BacklinkIndex, 'getDeadLinks'> = {+ getDeadLinks: () => [+ {+ target: 'ghost',+ sources: [{ source: 'unsaved', anchor: null, snippet: null, line: 3, column: 2 }],+ },+ ],+ };++ const result = await runValidationAudit(+ createProjectValidators(+ deps({+ backlinkIndex: fakeIndex,+ admittedDocNames: () => ['unsaved'],+ docFilePathFor: () => null,+ }),+ ),+ );++ expect(result.files).toHaveLength(1);+ expect(result.files[0]?.file).toBe('unsaved.md');+ expect(result.files[0]?.diagnostics[0]?.range.start).toEqual({ line: 3, character: 2 });+ // A malformed finding (file: null) would fail the wire schema and 500 the route.+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);+ });++ test('a dead link from a pre-position cache degrades to the start of the doc', async () => {+ // Entries deserialized from a cache written before positions were indexed+ // carry no line/column; the finding degrades to the doc start, not undefined.+ const fakeIndex: Pick<BacklinkIndex, 'getDeadLinks'> = {+ getDeadLinks: () => [+ { target: 'ghost', sources: [{ source: 'legacy', anchor: null, snippet: null }] },+ ],+ };++ const result = await runValidationAudit(+ createProjectValidators(+ deps({+ backlinkIndex: fakeIndex,+ admittedDocNames: () => ['legacy'],+ docFilePathFor: () => 'legacy.md',+ }),+ ),+ );++ expect(result.files[0]?.file).toBe('legacy.md');+ expect(result.files[0]?.diagnostics[0]?.range).toEqual({+ start: { line: 0, character: 0 },+ end: { line: 0, character: 0 },+ });+ // An undefined position would fail the wire schema and 500 the route.+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);+ });+});diff --git a/packages/server/src/lint/validation-audit.ts b/packages/server/src/lint/validation-audit.tsnew file mode 100644index 000000000..763f1ee79--- /dev/null+++ b/packages/server/src/lint/validation-audit.ts@@ -0,0 +1,251 @@+/**+ * Unified validation audit: a project-validator registry one level above the+ * lint-plugin registry (`LINT_PLUGINS`, untouched). Each validator answers+ * "given the project (or a sub-path), what per-file diagnostics hold?" behind+ * one interface while owning its own execution model — the lint validator+ * walks the content tree via `auditProject`; the links validator reads the+ * in-memory `BacklinkIndex`. The engine fans out and merges everything into+ * one source-tagged diagnostic plane. Backs `GET /api/audit` + MCP `audit`.+ */++import {+ DEFAULT_LINKS_VALIDATION,+ type LinksValidationSetting,+ type LinterConfig,+ SUPPORTED_DOC_EXTENSIONS,+ type ValidationDiagnostic,+} from '@inkeep/open-knowledge-core';+import type { BacklinkIndex } from '../backlink-index.ts';+import { getLogger } from '../logger.ts';+import { auditProject } from './audit.ts';++interface FileValidationResult {+ /** Path relative to `contentDir`. */+ file: string;+ diagnostics: ValidationDiagnostic[];+}++export interface ValidationAuditResult {+ files: FileValidationResult[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ warnings: string[];+}++export interface ValidationScope {+ /** contentDir-relative folder or doc-file path; absent audits the whole project. */+ targetPath?: string;+}++interface ValidatorRunResult {+ files: FileValidationResult[];+ /**+ * In-scope docs this validator scanned as a full-scan authority; 0 when it+ * reads an index instead of walking. The engine keeps the max across+ * validators as the plane's `fileCount`.+ */+ fileCount: number;+ warnings: string[];+}++export interface ProjectValidator {+ readonly id: string;+ run(scope: ValidationScope): Promise<ValidatorRunResult>;+}++export interface ValidationAuditDeps {+ projectDir: string;+ contentDir: string;+ baseConfig: LinterConfig;+ /** Live CRDT source overlay for loaded docs (see `AuditOptions.liveSourceFor`). */+ liveSourceFor?: (docRelPath: string) => string | null;+ /** Null when the server booted without a backlink index; links findings degrade to a warning. */+ backlinkIndex: Pick<BacklinkIndex, 'getDeadLinks'> | null;+ /**+ * Project posture for broken links (`validation.links`): 'off' silences the+ * links validator entirely, 'warning' (default) / 'error' set the severity.+ */+ linksValidation?: LinksValidationSetting;+ /** Every docName that currently exists — the dead-link existence oracle. */+ admittedDocNames: () => Iterable<string>;+ /** docName → on-disk contentDir-relative path, null when no file exists yet. */+ docFilePathFor: (docName: string) => string | null;+}++/**+ * The registered project validators. Admitting a new validator means appending+ * one factory here — the engine body never changes.+ */+export function createProjectValidators(deps: ValidationAuditDeps): ProjectValidator[] {+ return [createLintValidator(deps), createLinksValidator(deps)];+}++/** Fan out to every validator, then merge into one per-file diagnostic plane. */+export async function runValidationAudit(+ validators: readonly ProjectValidator[],+ scope: ValidationScope = {},+): Promise<ValidationAuditResult> {+ // Isolate validators: a throw degrades to a warning in the shared plane+ // instead of collapsing the whole audit (and discarding the validators that+ // succeeded) into an opaque 500. Extends the links validator's existing+ // null-index -> warning degradation to any unexpected throw, including from a+ // future validator.+ const results = await Promise.all(+ validators.map(async (validator) => {+ try {+ return await validator.run(scope);+ } catch (error) {+ // The plane's warning carries only `.message`; the stack goes to the+ // server log or a deep validator throw is undebuggable in production.+ getLogger('validation-audit').error(+ { err: error, validatorId: validator.id },+ '[audit] validator threw; degrading to a plane warning',+ );+ const message = error instanceof Error ? error.message : String(error);+ return {+ files: [],+ fileCount: 0,+ warnings: [`validator "${validator.id}" failed: ${message}`],+ } satisfies ValidatorRunResult;+ }+ }),+ );++ const byFile = new Map<string, ValidationDiagnostic[]>();+ const warnings: string[] = [];+ let fileCount = 0;+ for (const result of results) {+ warnings.push(...result.warnings);+ fileCount = Math.max(fileCount, result.fileCount);+ for (const entry of result.files) {+ const merged = byFile.get(entry.file);+ if (merged) merged.push(...entry.diagnostics);+ else byFile.set(entry.file, [...entry.diagnostics]);+ }+ }++ const files = [...byFile.entries()]+ .map(([file, diagnostics]) => ({ file, diagnostics: diagnostics.sort(byPosition) }))+ .sort((a, b) => a.file.localeCompare(b.file));++ let errorCount = 0;+ let warningCount = 0;+ for (const entry of files) {+ for (const diagnostic of entry.diagnostics) {+ if (diagnostic.severity === 'error') errorCount++;+ else warningCount++;+ }+ }++ return { files, fileCount, errorCount, warningCount, warnings };+}++function byPosition(a: ValidationDiagnostic, b: ValidationDiagnostic): number {+ return (+ a.range.start.line - b.range.start.line ||+ a.range.start.character - b.range.start.character ||+ a.source.localeCompare(b.source) ||+ a.code.localeCompare(b.code)+ );+}++function createLintValidator(deps: ValidationAuditDeps): ProjectValidator {+ return {+ id: 'lint',+ async run(scope) {+ const audit = await auditProject({+ projectDir: deps.projectDir,+ contentDir: deps.contentDir,+ baseConfig: deps.baseConfig,+ targetPath: scope.targetPath,+ liveSourceFor: deps.liveSourceFor,+ });+ return { files: audit.files, fileCount: audit.fileCount, warnings: audit.warnings };+ },+ };+}++function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator {+ const setting = deps.linksValidation ?? DEFAULT_LINKS_VALIDATION;+ return {+ id: 'links',+ async run(scope) {+ // 'off' is a clean empty contribution, not a degradation warning — the+ // project chose to silence link validation.+ if (setting === 'off') {+ return { files: [], fileCount: 0, warnings: [] };+ }+ const severity = setting === 'error' ? 'error' : 'warning';+ if (!deps.backlinkIndex) {+ return {+ files: [],+ fileCount: 0,+ warnings: ['links validation unavailable: backlink index is not configured'],+ };+ }+ const admitted = [...deps.admittedDocNames()];+ const sourceFilter = scopedSourceDocNames(admitted, scope.targetPath);+ // `getDeadLinks` reads an empty source filter as "no filter" — a scope+ // matching zero docs must short-circuit here or it would silently widen+ // back to the whole project.+ if (sourceFilter !== undefined && sourceFilter.length === 0) {+ return { files: [], fileCount: 0, warnings: [] };+ }+ const deadLinks = deps.backlinkIndex.getDeadLinks(admitted, sourceFilter);++ const byFile = new Map<string, ValidationDiagnostic[]>();+ for (const { target, sources } of deadLinks) {+ for (const occurrence of sources) {+ // A source indexed from a live CRDT doc may not be on disk yet — fall+ // back to the default extension so the finding still names a file.+ const file = deps.docFilePathFor(occurrence.source) ?? `${occurrence.source}.md`;+ // Entries deserialized from a pre-position cache carry no position;+ // degrade to the start of the doc rather than dropping the finding.+ const line = occurrence.line ?? 0;+ const character = occurrence.column ?? 0;+ const diagnostics = byFile.get(file) ?? [];+ diagnostics.push({+ range: { start: { line, character }, end: { line, character } },+ severity,+ source: 'links',+ code: 'dead-link',+ message: `Link target "${target}" does not resolve to an existing document.`,+ // The unresolved target, verbatim, so the Problems panel's+ // create-the-missing-page affordance never parses the message.+ linkTarget: target,+ });+ byFile.set(file, diagnostics);+ }+ }+ return {+ files: [...byFile.entries()].map(([file, diagnostics]) => ({ file, diagnostics })),+ fileCount: 0,+ warnings: [],+ };+ },+ };+}++/**+ * Translate a path scope into the dead-link source filter: a doc-file path+ * narrows to that one doc, anything else is a folder prefix over the admitted+ * set. This parallels the lint walk's scope intent but classifies by suffix+ * over the in-memory admitted set, not the on-disk `statSync` `resolveScope`+ * uses — so an admitted-but-unpersisted doc can scope differently across the+ * two validators. The filter is always a subset of the admitted set, so doc+ * scope stays a provable restriction of the project-wide dead-link predicate.+ */+function scopedSourceDocNames(+ admitted: readonly string[],+ targetPath: string | undefined,+): string[] | undefined {+ if (targetPath === undefined || targetPath === '') return undefined;+ const lower = targetPath.toLowerCase();+ if (SUPPORTED_DOC_EXTENSIONS.some((ext) => lower.endsWith(ext))) {+ const docName = targetPath.slice(0, targetPath.lastIndexOf('.'));+ return admitted.filter((name) => name === docName);+ }+ const prefix = `${targetPath.replace(/\/+$/, '')}/`;+ return admitted.filter((name) => name.startsWith(prefix));+}diff --git a/packages/server/src/mcp/tools/audit.test.ts b/packages/server/src/mcp/tools/audit.test.tsnew file mode 100644index 000000000..146df731b--- /dev/null+++ b/packages/server/src/mcp/tools/audit.test.ts@@ -0,0 +1,379 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import {+ describe as _bunDescribe,+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ test,+} from 'vitest';+import { type Config, ConfigSchema } from '../../config/schema.ts';+import type { AuditDeps } from './audit.ts';+import { AUDIT_WARNING_CAP, DESCRIPTION, register } from './audit.ts';+import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';+import type { ServerInstance } from './shared.ts';+import {+ AUDIT_FILE_CAP,+ AUDIT_FILE_DIAGNOSTIC_CAP,+ 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 AuditHandlerArgs {+ path?: string;+}++interface RegisteredTool {+ name: string;+ description: string;+ annotations?: Record<string, unknown>;+ handler: (args: AuditHandlerArgs) => Promise<ToolResult>;+}++function createFakeServer() {+ let registered: RegisteredTool | undefined;+ const server = {+ registerTool(+ name: string,+ cfg: { description?: string; annotations?: Record<string, unknown> },+ handler: (args: AuditHandlerArgs) => 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): AuditDeps {+ return { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwdDir };+}++let testServer: FetchTestServer;+let baseUrl: string;+let tmpDir: string;+const seenRequests: string[] = [];++// Stub diagnostics mirror the real `/api/audit` plane (pinned by the+// audit-http integration test): the lint validator emits markdownlint+// warnings; the links validator emits `links/dead-link` errors whose message+// names the unresolved target.+function lintWarning(line: number) {+ return {+ range: { start: { line, character: 0 }, end: { line, character: 1 } },+ severity: 'warning',+ source: 'markdownlint',+ code: 'MD010',+ message: 'Hard tabs',+ };+}++function deadLinkError(line: number, target: string) {+ return {+ range: { start: { line, character: 4 }, end: { line, character: 4 } },+ severity: 'error',+ source: 'links',+ code: 'dead-link',+ message: `Link target "${target}" does not resolve to an existing document.`,+ };+}++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) =>+ line % 2 === 0 ? lintWarning(line) : deadLinkError(line, 'ghost'),+ ),+ }));+ const all = files.flatMap((f) => f.diagnostics);+ const errorCount = all.filter((d) => d.severity === 'error').length;+ return {+ ok: true,+ files,+ fileCount,+ errorCount,+ warningCount: all.length - errorCount,+ warnings: [],+ };+}++beforeAll(async () => {+ testServer = await startFetchTestServer({+ 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/audit') {+ const path = url.searchParams.get('path');+ if (path === 'clean') {+ return Response.json({+ ok: true,+ files: [],+ fileCount: 4,+ errorCount: 0,+ warningCount: 0,+ warnings: [],+ });+ }+ if (path === 'over-cap') {+ return Response.json(auditPayloadOf(AUDIT_FILE_CAP + 2, AUDIT_FILE_DIAGNOSTIC_CAP + 3));+ }+ if (path === 'degraded') {+ // A validator degraded (e.g. no backlink index): no problems found,+ // but the run is incomplete — a warning, no files.+ return Response.json({+ ok: true,+ files: [],+ fileCount: 3,+ errorCount: 0,+ warningCount: 0,+ warnings: ['links validation unavailable: backlink index is not configured'],+ });+ }+ if (path === 'problems-and-warnings') {+ return Response.json({+ ok: true,+ files: [{ file: 'notes/ideas.md', diagnostics: [deadLinkError(9, 'ghost')] }],+ fileCount: 3,+ errorCount: 1,+ warningCount: 0,+ warnings: ['could not read drafts: EACCES'],+ });+ }+ if (path === 'many-warnings') {+ return Response.json({+ ok: true,+ files: [],+ fileCount: 20,+ errorCount: 0,+ warningCount: 0,+ warnings: Array.from(+ { length: AUDIT_WARNING_CAP + 5 },+ (_, i) => `could not read dir-${i}: EACCES`,+ ),+ });+ }+ return Response.json({+ ok: true,+ files: [+ { file: 'guides/tabs.md', diagnostics: [lintWarning(2)] },+ { file: 'notes/ideas.md', diagnostics: [deadLinkError(9, 'ghost')] },+ ],+ 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-audit-test-'));+ seenRequests.length = 0;+});++afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true });+});++describe('audit — registration + DESCRIPTION', () => {+ test('registers exactly one tool named "audit"', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ expect(getTool().name).toBe('audit');+ });++ test('declares read-only tool annotations', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ expect(getTool().annotations).toEqual({+ readOnlyHint: true,+ idempotentHint: true,+ });+ });++ test('DESCRIPTION routes link-validation intent here and away from the navigation reader', () => {+ expect(DESCRIPTION).toContain('markdownlint');+ expect(DESCRIPTION).toContain('broken');+ expect(DESCRIPTION).toContain('`links`');+ expect(DESCRIPTION).toContain('navigation');+ expect(DESCRIPTION).toContain('`path`');+ });++ 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('audit — unified project audit', () => {+ test('no args hits /api/audit and returns both validator sources tagged', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({});+ expect(seenRequests).toContain('/api/audit?');+ const s = result.structuredContent as {+ files: Array<{ file: string; diagnostics: Array<{ source: string; severity: string }> }>;+ fileCount: number;+ errorCount: number;+ warningCount: number;+ };+ expect(s.files).toHaveLength(2);+ expect(s.files.map((f) => f.file)).toEqual(['guides/tabs.md', 'notes/ideas.md']);+ expect(s.files[0]?.diagnostics[0]?.source).toBe('markdownlint');+ expect(s.files[1]?.diagnostics[0]?.source).toBe('links');+ expect(s.files[1]?.diagnostics[0]?.severity).toBe('error');+ expect(s.fileCount).toBe(4);+ expect(s.errorCount).toBe(1);+ expect(s.warningCount).toBe(1);+ const text = result.content[0]?.text ?? '';+ expect(text).toContain('1 error');+ expect(text).toContain('1 warning');+ expect(text).toContain('markdownlint/MD010');+ expect(text).toContain('links/dead-link');+ // Text output displays 1-based lines from the 0-based wire range.+ expect(text).toContain('line 10');+ expect(text).toContain('"ghost"');+ });++ 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/audit?path=sub%2Fdir');+ });++ test('a clean scope reports no problems with the scanned-doc total', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'clean' });+ const s = result.structuredContent as {+ files: unknown[];+ fileCount: number;+ errorCount: number;+ warningCount: number;+ };+ expect(s.files).toHaveLength(0);+ expect(s.fileCount).toBe(4);+ expect(s.errorCount).toBe(0);+ expect(s.warningCount).toBe(0);+ expect(result.content[0]?.text).toContain('No problems across 4 documents');+ });+});++describe('audit — degradation visibility', () => {+ test('a degraded run surfaces the warning in text and is not reported as clean', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'degraded' });+ const text = result.content[0]?.text ?? '';+ // The warning reaches the text channel (the channel an agent reads)...+ expect(text).toContain('links validation unavailable: backlink index is not configured');+ // ...and the summary flags the run as incomplete, not a bare "No problems.".+ expect(text).toContain('could not fully complete');+ expect(text).toContain('Audit incomplete');+ const s = result.structuredContent as { warnings?: string[] };+ expect(s.warnings).toEqual(['links validation unavailable: backlink index is not configured']);+ });++ test('warnings surface alongside problems, not only in the structured channel', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'problems-and-warnings' });+ const text = result.content[0]?.text ?? '';+ expect(text).toContain('links/dead-link');+ expect(text).toContain('could not read drafts: EACCES');+ expect(text).toContain('Audit incomplete');+ });++ test('the warnings channel is capped like the diagnostics channels', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl, tmpDir));+ const result = await getTool().handler({ path: 'many-warnings' });+ const s = result.structuredContent as { warnings?: string[]; omittedWarningCount?: number };+ expect(s.warnings).toHaveLength(AUDIT_WARNING_CAP);+ expect(s.omittedWarningCount).toBe(5);+ expect(result.content[0]?.text ?? '').toContain('… and 5 more warnings');+ });+});++describe('audit — output cap', () => {+ interface AuditStructured {+ files: Array<{+ file: string;+ diagnostics: Array<{ source?: string }>;+ omittedDiagnosticCount?: number;+ }>;+ fileCount: number;+ errorCount: number;+ warningCount: number;+ omittedFileCount?: number;+ }++ test('over-cap audits truncate both channels but keep totals uncapped', 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.+ // The stub alternates warning/error, so of 13 per file, 6 are errors.+ const perFile = AUDIT_FILE_DIAGNOSTIC_CAP + 3;+ const errorsPerFile = Math.floor(perFile / 2);+ expect(s.fileCount).toBe(AUDIT_FILE_CAP + 2);+ expect(s.errorCount).toBe((AUDIT_FILE_CAP + 2) * errorsPerFile);+ expect(s.warningCount).toBe((AUDIT_FILE_CAP + 2) * (perFile - errorsPerFile));++ 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');+ // Both validator sources survive the capped view.+ expect(text).toContain('markdownlint/MD010');+ expect(text).toContain('links/dead-link');+ const shownFileHeaders = text.match(/^doc-\d+\.md:$/gm) ?? [];+ expect(shownFileHeaders).toHaveLength(AUDIT_FILE_CAP);+ });+});diff --git a/packages/server/src/mcp/tools/audit.ts b/packages/server/src/mcp/tools/audit.tsnew file mode 100644index 000000000..f4ea4b298--- /dev/null+++ b/packages/server/src/mcp/tools/audit.ts@@ -0,0 +1,225 @@+/**+ * `audit` MCP tool — unified read-only validation audit.+ *+ * One call runs every registered content validator — markdownlint rules AND+ * internal-link resolution — and returns the merged per-file diagnostic plane+ * from `GET /api/audit`. Broken links are reported under the SOURCE doc that+ * contains them (a dead link is fixed by editing its source), with a line+ * position. Report-only: there is no fix shape here — auto-fixable lint rules+ * go through `lint({ document, fix: true })`, link repairs through+ * `edit`/`write`.+ */++import { z } from 'zod';+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';+import {+ AUDIT_FILE_CAP,+ AUDIT_FILE_DIAGNOSTIC_CAP,+ countSummary,+ formatDiagnosticLine,+ HOCUSPOCUS_NOT_RUNNING_ERROR,+ httpGet,+ looseObjectArray,+ outputSchemaWithText,+ ROUTED_CWD_DESCRIPTION,+ resolveProjectServerContext,+ textPlusStructured,+ textResult,+} from './shared.ts';++export const DESCRIPTION = [+ '[Requires: Hocuspocus server] Unified validation audit: every content problem — markdown-lint violations AND broken internal links — in one read-only call, grouped by the file to fix.',+ '',+ '- No args → audit every in-scope `.md`/`.mdx` doc; pass `path` to scope to a folder or a single file.',+ '- To CHECK whether links resolve, use this tool: each broken link is reported under the SOURCE doc that contains it, at the offending line. (The `links` tool is the navigation/graph reader — backlinks, forward links, orphans, hubs — not the validation surface.)',+ '',+ "Each diagnostic carries a `source` naming the validator ('markdownlint' rule violations; 'links' broken internal links), a `code` (e.g. MD010, dead-link), `message`, a 0-based LSP `range` (for links: line exact, column approximate), and `severity` ('error' | 'warning' — broken links default to warnings; the project's `validation.links` setting can raise them to errors or hide them). Only files with at least one problem are listed, plus `fileCount`/`errorCount`/`warningCount` totals. 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.",+ '',+ 'Read-only: nothing is modified. Auto-fix fixable lint findings with `lint({ document, fix: true })`; broken links need content edits via `edit`/`write`.',+].join('\n');++/**+ * Degradation warnings (unreadable files/dirs, an unavailable validator) are+ * agent-context-bound like the diagnostics, so the same cap applies — a project+ * with many unreadable files must not flood the agent through this channel. The+ * HTTP endpoint stays the uncapped surface for GUI consumers.+ */+export const AUDIT_WARNING_CAP = 10;++/** Fix routing is per-validator: lint has an auto-fix shape, links never do. */+const FIX_ROUTING_HINT =+ 'Auto-fix fixable lint findings with `lint({ document, fix: true })`; broken links need content edits via `edit`/`write`.';++interface AuditPositionPayload {+ line?: number;+ character?: number;+}++interface AuditDiagnosticPayload {+ source?: string;+ code?: string;+ message?: string;+ severity?: string;+ range?: { start?: AuditPositionPayload; end?: AuditPositionPayload };+}++interface AuditDocPayload {+ file?: string;+ diagnostics?: AuditDiagnosticPayload[];+}++interface AuditResponsePayload {+ files?: AuditDocPayload[];+ fileCount?: number;+ errorCount?: number;+ warningCount?: number;+ warnings?: string[];+}++export interface AuditDeps {+ serverUrl: ServerUrlOrResolver;+ config: ConfigOrResolver;+ resolveCwd: (explicit?: string) => Promise<string>;+}++interface AuditArgs {+ path?: string;+ cwd?: string;+}++export function register(server: ServerInstance, deps: AuditDeps): void {+ server.registerTool(+ 'audit',+ {+ description: DESCRIPTION,+ inputSchema: {+ path: z+ .string()+ .optional()+ .describe(+ 'Audit scope: a folder or single doc file (content-dir-relative). Default: the whole project.',+ ),+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),+ },+ outputSchema: outputSchemaWithText({+ files: looseObjectArray+ .optional()+ .describe('Per-file diagnostics — only files with at least one problem.'),+ fileCount: z.number().optional().describe('Total in-scope documents scanned.'),+ errorCount: z.number().describe('Total error-severity findings across validators.'),+ warningCount: z.number().describe('Total warning-severity findings across validators.'),+ warnings: z+ .array(z.string())+ .optional()+ .describe('Non-fatal issues (unreadable files/dirs, unavailable validators).'),+ omittedWarningCount: z+ .number()+ .optional()+ .describe('Warnings omitted from `warnings` by the output cap.'),+ omittedFileCount: z+ .number()+ .optional()+ .describe('Files with problems omitted from `files` by the output cap.'),+ cwd: z.string().describe('Absolute directory the audit ran against.'),+ }),+ annotations: {+ readOnlyHint: true,+ idempotentHint: true,+ },+ },+ async (args: AuditArgs) => {+ 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);+ return runAudit(args.path, url, cwd);+ },+ );+}++async function runAudit(path: string | undefined, url: string, cwd: string) {+ const query = path ? `?path=${encodeURIComponent(path)}` : '';+ const result = await httpGet(url, `/api/audit${query}`);+ if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);+ const { ok: _ok, ...rest } = result;+ const data = rest as AuditResponsePayload;+ 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 warnings = data.warnings ?? [];+ const shownWarnings = warnings.slice(0, AUDIT_WARNING_CAP);+ const omittedWarningCount = warnings.length - shownWarnings.length;++ const structured = {+ files: shownFiles,+ fileCount,+ errorCount,+ warningCount,+ ...(shownWarnings.length > 0 ? { warnings: shownWarnings } : {}),+ ...(omittedWarningCount > 0 ? { omittedWarningCount } : {}),+ ...(omittedFileCount > 0 ? { omittedFileCount } : {}),+ cwd,+ };++ // Surface degradation warnings in the text channel too: an agent reads text,+ // so a partial run (a skipped/unreadable file, an unavailable validator) must+ // not be byte-indistinguishable from a genuinely clean one.+ const warningBlock =+ warnings.length > 0+ ? [+ `Audit incomplete — ${warnings.length} warning${warnings.length === 1 ? '' : 's'} (findings may be partial):`,+ ...shownWarnings.map((w) => ` ⚠ ${w}`),+ ...(omittedWarningCount > 0+ ? [` … and ${omittedWarningCount} more warning${omittedWarningCount === 1 ? '' : 's'}`]+ : []),+ ]+ : [];++ const scope = path ? ` in ${path}` : '';+ if (files.length === 0) {+ const summary =+ warnings.length > 0+ ? `No problems found across ${fileCount} document${fileCount === 1 ? '' : 's'}${scope}, but the audit could not fully complete.`+ : `No problems across ${fileCount} document${fileCount === 1 ? '' : 's'}${scope}.`;+ return textPlusStructured([summary, ...warningBlock].join('\n'), 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, ...warningBlock, FIX_ROUTING_HINT].join('\n'),+ structured,+ );+}diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.tsindex 9640bbd4e..e7ff53f36 100644--- a/packages/server/src/mcp/tools/index.ts+++ b/packages/server/src/mcp/tools/index.ts@@ -1,7 +1,7 @@/*** MCP tool registry.*- * Reads: exec, search, history, links, skills, config, palette, preview_url, share_link+ * Reads: exec, search, history, links, skills, config, palette, preview_url, share_link, lint, audit* Writes: write, edit, delete, move, checkpoint, restore_version* Conflicts: conflicts, resolve_conflict* Workflow: workflow (kind: ingest | research | consolidate | discover)@@ -38,6 +38,7 @@ import { createEnsureSingleFileSession } from '../../ensure-single-file-session.import type { AgentIdentity } from '../agent-identity.ts';import { getCurrentMcpLogger, type McpLogger } from '../logger.ts';import { createLoggedServer } from '../tool-logging.ts';+import { register as registerAudit } from './audit.ts';import { register as registerCheckpoint } from './checkpoint.ts';import { register as registerConfig } from './config.ts';import { register as registerConflicts } from './conflicts.ts';@@ -154,6 +155,14 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOresolveCwd: named('lint'),identityRef: opts.identityRef,});+ // Unified validation audit — one read-only call spanning every content+ // validator (markdownlint + link resolution) via `GET /api/audit`. Broken+ // links validate here; the `links` tool stays the navigation/graph reader.+ registerAudit(registrationServer, {+ serverUrl: opts.serverUrl,+ config: opts.config,+ resolveCwd: named('audit'),+ });// 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.tsindex 6b0c61fd9..d11cb5ebe 100644--- a/packages/server/src/mcp/tools/lint.test.ts+++ b/packages/server/src/mcp/tools/lint.test.ts@@ -12,15 +12,13 @@ import {} from 'vitest';import { type Config, ConfigSchema } from '../../config/schema.ts';import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';+import { DESCRIPTION, type LintDeps, register } from './lint.ts';+import type { ServerInstance } from './shared.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';+ 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.diff --git a/packages/server/src/mcp/tools/lint.ts b/packages/server/src/mcp/tools/lint.tsindex 0d81beb50..edf6df4f2 100644--- a/packages/server/src/mcp/tools/lint.ts+++ b/packages/server/src/mcp/tools/lint.ts@@ -22,7 +22,11 @@ import { z } from 'zod';import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ AUDIT_FILE_CAP,+ AUDIT_FILE_DIAGNOSTIC_CAP,agentIdentityFields,+ countSummary,+ formatDiagnosticLine,HOCUSPOCUS_NOT_RUNNING_ERROR,httpGet,httpPost,@@ -47,15 +51,6 @@ export const DESCRIPTION = ['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@@ -336,19 +331,3 @@ async function lintAudit(path: string | undefined, url: string, cwd: string) {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/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.tsindex 3672506c4..db51e5487 100644--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts@@ -232,6 +232,7 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no'edit','write','links',+ 'audit',]);test('every registerTool registration declares `text` in its outputSchema', () => {diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.tsindex f23b50064..a06d65e73 100644--- a/packages/server/src/mcp/tools/registry.test.ts+++ b/packages/server/src/mcp/tools/registry.test.ts@@ -43,6 +43,7 @@ const EXPECTED_TOOLS = ['preview_url','share_link','lint',+ 'audit',// Writes — CRUD verbs + version'write','edit',@@ -127,7 +128,7 @@ function captureRegistered(): string[] {return names;}-describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install + skills + lint)', () => {+describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install + skills + lint + audit)', () => {test('registers exactly the expected number of tools', () => {const names = captureRegistered();expect(names.length).toBe(EXPECTED_TOOLS.length);@@ -173,7 +174,8 @@ describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install* / `resolve_conflict` all mutate KB content, but the shadow repo versions every* 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+ * otherwise). `audit` is a pure read (unified lint + link validation report; no+ * fix shape). `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 = [@@ -193,6 +195,7 @@ const OK_AUTO_APPROVED_TOOLS = ['resolve_conflict','workflow','lint',+ 'audit',] as const;describe('docked-terminal auto-approve classification', () => {diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.tsindex 86b0c7247..730b8b179 100644--- a/packages/server/src/mcp/tools/shared.ts+++ b/packages/server/src/mcp/tools/shared.ts@@ -896,3 +896,46 @@ export function parseRenameCollidingPairs(value: unknown): RenameCollisionPair[]: [];});}++/**+ * Audit output caps shared by the `lint` (project-audit shape) and `audit`+ * tools: 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. One definition so the two tools' outputs+ * can never silently diverge for the same scope.+ */+export const AUDIT_FILE_CAP = 10;+export const AUDIT_FILE_DIAGNOSTIC_CAP = 10;++/**+ * Structural diagnostic shape the `lint` and `audit` text formatters read —+ * the intersection of both tools' wire payload types (all optional, since it+ * describes loosely-deserialized server output). One definition so the two+ * tools' human-facing summaries can never silently diverge (same contract as+ * the shared caps above).+ */+export interface FormattableDiagnostic {+ severity?: string;+ range?: { start?: { line?: number } };+ source?: string;+ code?: string;+ message?: string;+}++/** One diagnostic as a human-facing text line: ` ✘ line 12 markdownlint/MD010: Hard tabs`. */+export function formatDiagnosticLine(d: FormattableDiagnostic): 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();+}++/** `2 errors, 1 warning` / `no problems` — the count clause in a summary header. */+export 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/server-factory.ts b/packages/server/src/server-factory.tsindex 72cf25435..548daac9f 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -21,10 +21,12 @@ import {type ConfigIssue,createBasenameIndex,DEFAULT_ATTACHMENT_FOLDER_PATH,+ DEFAULT_LINKS_VALIDATION,DEFAULT_LINTER_CONFIG,DOCUMENT_OPEN_BYTE_LIMIT,humanFormat,isKnownConfigError,+ type LinksValidationSetting,type LinterConfig,type MarkdownManager,type PersistedLinterConfig,@@ -682,6 +684,18 @@ export function createServer(options: ServerOptions): ServerInstance {return persisted ? toEffectiveBase(persisted) : DEFAULT_LINTER_CONFIG;}+ // Same fresh-per-request contract as `readLinterBaseConfig`: the broken-link+ // posture (`validation.links`) must apply to the next audit without a restart.+ function readLinksValidationSetting(): LinksValidationSetting {+ const project = readConfigSafely({+ absPath: resolveConfigPath('project', projectDir),+ sideline: false,+ warn: (message) =>+ log.warn({ message }, '[config] could not read project config for link validation'),+ });+ return project.value.validation?.links ?? DEFAULT_LINKS_VALIDATION;+ }+// 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.@@ -1803,6 +1817,7 @@ export function createServer(options: ServerOptions): ServerInstance {semanticSearch,getSemanticSimilarityFloor: () => readSemanticSearchConfig().similarityFloor,getLinterBaseConfig: () => readLinterBaseConfig(),+ getLinksValidationSetting: () => readLinksValidationSetting(),getLinkPreviewsEnabled: readLinkPreviewsEnabled,embeddingsSecretsFile: secretsFilePath(configHomedirOverride),ephemeral,