Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Reduce Open Knowledge MCP descriptions and remove conflict tools (#5211)
tim-inkeep764e14e3b369
diff --git a/.changeset/audit-scope-errors.md b/.changeset/audit-scope-errors.mdnew file mode 100644index 000000000..6f57ad925--- /dev/null+++ b/.changeset/audit-scope-errors.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': minor+---++Report empty scopes and reject unknown paths in `ok lint` and `ok audit`.diff --git a/.changeset/canonical-link-resolution.md b/.changeset/canonical-link-resolution.mdnew file mode 100644index 000000000..6c0fcc3bc--- /dev/null+++ b/.changeset/canonical-link-resolution.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': minor+---++Resolve shorthand and `.md` links consistently across the editor, graph, and audit. Existing ambiguous links may point elsewhere after upgrading; [review them](https://openknowledge.ai/docs/reference/core-concepts#review-links-after-upgrading).diff --git a/.changeset/mcp-guidance-budget.md b/.changeset/mcp-guidance-budget.mdnew file mode 100644index 000000000..735552c69--- /dev/null+++ b/.changeset/mcp-guidance-budget.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Shorten MCP tool guidance to reduce context use.diff --git a/.changeset/remove-conflict-mcp-tools.md b/.changeset/remove-conflict-mcp-tools.mdnew file mode 100644index 000000000..4100dc1fe--- /dev/null+++ b/.changeset/remove-conflict-mcp-tools.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': minor+---++Remove the `conflicts` and `resolve_conflict` MCP tools. Resolve conflicts in the app and [refresh agent guidance](https://openknowledge.ai/docs/reference/mcp#refresh-agent-guidance).diff --git a/.changeset/rename-preserves-links.md b/.changeset/rename-preserves-links.mdnew file mode 100644index 000000000..f2083200f--- /dev/null+++ b/.changeset/rename-preserves-links.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Preserve link targets and display text when moving or renaming documents.diff --git a/.changeset/warm-backlink-snapshot.md b/.changeset/warm-backlink-snapshot.mdnew file mode 100644index 000000000..a234f67f3--- /dev/null+++ b/.changeset/warm-backlink-snapshot.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Avoid rereading unchanged linked documents after restarting Open Knowledge.diff --git a/docs/content/advanced/content-rules/overview.mdx b/docs/content/advanced/content-rules/overview.mdxindex c05d61cfb..41617d0f5 100644--- a/docs/content/advanced/content-rules/overview.mdx+++ b/docs/content/advanced/content-rules/overview.mdx@@ -46,6 +46,8 @@ ok lint --json # structured JSON outputok lint --errors-only # exit non-zero only on error-severity problems```+Both `ok lint` and `ok audit` accept an existing file or directory as their scope. For a missing document stem without `.md` or `.mdx`, they try the same path with `.mdx`, then `.md`; an explicit `.md` or `.mdx` path must exist as written. A typo returns a not-found error naming the supplied path and exits with code 1, before `--fix` can change files. With `--json`, this error is an RFC 9457 problem response object. An existing empty or ignored directory succeeds with zero findings, an informational warning, and exit code 0. An explicitly named file is still checked even if an ignore rule excludes it from directory scans. Server-backed `ok audit` refuses hidden-segment scopes: it checks zero documents, reports the refusal as an ordinary warning, and exits with code 0; headless `ok lint` checks an explicitly named hidden path. A missing configured content directory also returns a not-found error and exits with code 1.+The exit code is non-zero when any problem is found. Findings are warnings unless your `.markdownlint.*` promotes a rule to `"error"`, so `--errors-only` gates CI on just the rules you chose to enforce. Only markdownlint rules can be promoted — [frontmatter](/docs/advanced/content-rules/frontmatter) findings are always warnings, so `--errors-only` never gates on them.### What it returns@@ -205,7 +207,7 @@ The structured content is close to `ok lint --json`, with four differences:| Cap fields | — | `omittedFileCount`, per-file `omittedDiagnosticCount`, `omittedWarningCount` || Fix-mode keys | — | `diagnosticsArePreFix`, `reLintFailure` (only when the post-write re-lint could not report) |-Everything else matches: `files[].diagnostics` with 0-based `range`, `severity`, `source`, `code`, `message`, plus `errorCount`, `warningCount`, `fileCount` on an audit, configuration or degradation `warnings`, and `ran` for the selected source families. Audit output is capped project-wide at 10 warnings, plus 10 files × 10 diagnostics per file — the text channel marks the remainder with "… and N more", the structured channel with the three cap fields above. Counts always reflect the full scan, and re-running with a narrower `path` recovers the detail. With `fix: true` the summary reports what was applied and what remains: `Fixed 1 problem in docs/guide.md.` followed by the unfixable findings.+Everything else matches: `files[].diagnostics` with 0-based `range`, `severity`, `source`, `code`, `message`, plus `errorCount`, `warningCount`, `fileCount` on an audit, configuration or degradation `warnings`, and `ran` for the selected source families. Audit output is capped project-wide at 10 warnings, plus 10 files × 10 diagnostics per file — the text channel marks the remainder with "… and N more", the structured channel with the three cap fields above. Counts always reflect the full scan. A narrower `path` reduces competing files but does not lift per-file caps. For all lint findings in one document, call `lint({ document: "file" })`; project-tree OKF findings remain capped. With `fix: true` the summary reports what was applied and what remains: `Fixed 1 problem in docs/guide.md.` followed by the unfixable findings.When the fix landed but the post-write re-lint could not report, the response carries `diagnosticsArePreFix: true` and explains itself in `reLintFailure`: `reason` is the machine-readable discriminant (`re-lint-threw` or `source-went-blind`) and `message` is the prose. The diagnostics and counts are then the PRE-fix set and `fixedCount` is 0, so re-run `lint` to see what remains rather than reading 0 as nothing fixed.@@ -213,6 +215,8 @@ When the fix landed but the post-write re-lint could not report, the response caThe agent-side `ok audit` — content-rule problems and broken links in one read-only call, grouped by file, same 10 × 10 + 10-warning cap with `omittedWarningCount` when warnings are dropped, no fix shape. Its text and structured results both report `ran`. If the reserved-log policy withholds one or more link findings, `brokenLinkSuppression: { reason: "reserved-log-policy", count: N }` makes that filtered result explicit without exposing paths or hrefs; the text result says the same. If a selected validator degrades, its family remains in `ran` and the `warnings` channel explains why; a partial degradation may still have contributed findings.+The `path` scope follows the same file, directory, extension fallback, and valid-empty rules as the CLI. To inspect omitted findings for one file, use `lint({ document: "file" })` for document lint and `links({ kind: "dead", sourceDocuments: ["file"] })` for raw dead links. The raw link query also includes links excluded by audit policy. Narrowing the audit does not remove its per-file caps, and project-tree OKF findings remain capped.+### Write responsesEvery write response carries validation findings for the document it touched, on two channels. Both nest under `document` in the structured content, and both are advisory: a finding never blocks the write.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex f43ab277b..0bc60f0ef 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -99,6 +99,8 @@ Links work the way they do in the editors you already know:- **Link to a section.** Append `#` and the heading's slug to a doc link — `[text](./spec.md#data-model-v2)` — and the WYSIWYG editor opens the doc scrolled to that heading (the source editor ignores the fragment and opens at the top). The slug is the heading text in lowercase with accents dropped, every run of characters that aren't letters or digits replaced by one hyphen, and hyphens trimmed from both ends: `## Data model: v2` becomes `data-model-v2`, `## FAQ:` becomes `faq`, and a second identical heading in the same doc gets `-1`. Agents write the same form in chat, so a reply about one part of a long spec can take you straight to it.- **Press `Cmd+K` with text selected.** The link popover opens with the URL field focused, pre-filled from your clipboard when it holds a URL. With the cursor inside an existing link, `Cmd+K` opens that link for editing. With no selection, `Cmd+K` keeps opening the command palette, as everywhere else. To reach the command palette while text is selected, use `Cmd+P` (`Ctrl+P` on Windows / Linux), which always opens it.+For legacy wiki links and ambiguous names, see [how links resolve and what to review after upgrading](../reference/core-concepts.md#review-links-after-upgrading).+## Right-click menu and spell checkIn the desktop app, right-clicking editable text opens a native context menu. Any editable field gets **Cut / Copy / Paste / Select All**; when there's a selection or a flagged word under the cursor, **Search with Google** joins it — plus, on macOS, **Look Up** (the dictionary panel).diff --git a/docs/content/features/skills/reference.mdx b/docs/content/features/skills/reference.mdxindex b1396fea3..893699124 100644--- a/docs/content/features/skills/reference.mdx+++ b/docs/content/features/skills/reference.mdx@@ -23,7 +23,7 @@ A new skill goes into a skills folder the project already has. OpenKnowledge nev| Project | The project's existing skills folder (`.agents/skills/<name>/` when `.agents/` is there, else `.claude/skills/<name>/` and so on) | Other project-local editor skills directories || Global | The same, under your home directory | Other home editor skills directories |-OpenKnowledge keeps one source folder per skill. Other locations use symlinks by default, so they read the same bytes. The install menu can convert a location to a copy, which OpenKnowledge refreshes until it is edited independently outside the app.+OpenKnowledge keeps one source folder per skill. Other locations use symlinks by default, so they read the same bytes. The install menu can convert a location to a copy. OpenKnowledge refreshes a recorded, unedited copy from the source when the skill watcher runs or the server starts; a source edit may reach the copy after a delay. Editing the copy directly forks it, so later refreshes preserve those edits.**Make source** relocates the real folder. Moving between Project and Global re-creates the skill in the destination scope: history does not transfer, and the editor locations the destination scope can host are re-projected there. Its `.agents/skills` hub entry, any **Add custom path** locations, and any AI tool with no skills folder at that scope are removed at the source and not re-created at the destination; add the ones the destination scope can hold again from the destination skill. That applies to a move that succeeded: if the move fails, the same list names locations it had already removed at the source, so adding them from the destination would spread the copy the failure left behind. Project skills are versioned with project content. Global skills outside a base carry no version history.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex fea933902..08a1d7847 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -154,7 +154,7 @@ Every command takes `--cwd <path>` to run from another directory, `--log-level <## Commands that run for you-The rest of the CLI exists mostly for tooling and automation. Your AI editor spawns `ok mcp` to talk to the knowledge base; `ok repair-skills` refreshes bundled editor skills automatically during `ok start`; and `ok diagnose` / `ok bug-report` produce support bundles when something goes wrong. Run `ok --help` if you want to see an overview of all commands.+The rest of the CLI exists mostly for tooling and automation. Your AI editor spawns `ok mcp` to talk to the knowledge base. `ok start` repairs existing editor connection settings; it leaves installed editor skills alone. Run `ok repair-skills` explicitly to restore missing project skill copies and repair user-global bundles. To update an existing project skill, follow [Refresh agent guidance](./mcp.mdx#refresh-agent-guidance). `ok diagnose` and `ok bug-report` produce support bundles when something goes wrong. Run `ok --help` for an overview of all commands.## Remove OpenKnowledgediff --git a/docs/content/reference/core-concepts.md b/docs/content/reference/core-concepts.mdindex 1383f976d..40d84fa1b 100644--- a/docs/content/reference/core-concepts.md+++ b/docs/content/reference/core-concepts.md@@ -88,6 +88,14 @@ The set of files the engine treats as your knowledge base is the configured contInternal cross-references are written with **standard markdown links**. The recommended form is **relative** — `[text](./sibling.md)`, `[text](../folder/doc.md)` — which stays portable across GitHub, Obsidian, VS Code, and published sites. A **root-absolute** form (`[text](/folder/doc.md)`, where the leading slash means the content root) is equally valid and convenient for cross-folder links. The two never mix: never glue `./` onto a content-root path, since `./folder/doc.md` written from a doc already inside `folder/` resolves to the doubled, broken `folder/folder/doc.md` — `write`/`edit` flag exactly this in their `brokenLinks` response. Whenever document A links to document B, OpenKnowledge automatically records the inverse on B: a **backlink** from B back to A.+### Review links after upgrading++A wiki link such as `[[notes/beta.md]]` first checks for a document whose path is exactly `notes/beta.md`. If none exists, OpenKnowledge removes **one** terminal `.md` or `.mdx` (case-insensitive) and resolves `notes/beta`. It does not repeatedly remove suffixes: `[[notes/beta.md.md]]` can fall back to `notes/beta.md`, but not `notes/beta`. If the suffix-free name finds no document, resolution tries the original spelling.++After the original exact-path check, OpenKnowledge fully resolves the suffix-stripped spelling: exact path, case- and punctuation-insensitive slug, folder `index` page (or its same-named page), then matching basename when the link has no slash. Only if that finds nothing does it try the original spelling's fuzzy, folder-index, and basename fallbacks. Without a Markdown suffix, those checks run once on the original spelling. If multiple paths have the same fuzzy slug or basename, the path smallest in UTF-16 code-unit order wins. For example, with `reports/index.md` and `reports-md.md`, `[[reports.md]]` opens `reports/index` before trying the fuzzy match for `reports-md`. An exact, case-matching path avoids a fuzzy tie.++After upgrading, review existing wiki links and shorthand targets that omit a folder, differ only by case or punctuation, or end in `.md` or `.mdx`. Open each link or use the MCP `links` tool with `kind: "forward"` to inspect its resolved destination. If a valid link now opens a different document, replace its target with the intended document's exact path. Use `audit` to find broken links, but do not rely on it to detect a link that still resolves to the wrong document. For new cross-document links, prefer the explicit relative or root-absolute Markdown paths above.+You never write backlinks by hand. They are computed from the links you already write, and together they form the **link graph**: the network of relationships across your knowledge base.```html previewdiff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex 48cb1bdb3..20abb01ab 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -6,9 +6,9 @@ description: Tools the OpenKnowledge MCP server exposes to AI agents.The MCP server gives AI agents structured access to your knowledge base. A few tools answer without a running server: `exec` (fs-direct shell reads straight off the disk — only the backlink and forward-link enrichment needs the server; history comes from the shadow repo on disk), plus `config` and `palette`. `preview_url` resolves from the project's lock files, but treats opening a preview as demand: if no server is running it auto-starts one (under the `OK_MCP_AUTOSTART` gate).-Every other read tool (`search`, `links`, `history`, etc.) and all write tools route through the Hocuspocus server, which OpenKnowledge auto-starts on the first call that needs it, under the same `OK_MCP_AUTOSTART` gate. All tools take a `cwd` (an absolute path inside the target project) that selects which project the call lands on; a globally registered server requires it unless the client advertises exactly one root.+Every other read tool (`search`, `links`, `history`, etc.) and all write tools route through the Hocuspocus server, which OpenKnowledge auto-starts on the first call that needs it, under the same `OK_MCP_AUTOSTART` gate. Routed stdio calls use `cwd`, an absolute project or worktree path: it is required until a project is selected unless the client advertises exactly one root. Project-bound HTTP calls may omit `cwd` and stay confined to their configured root. The `exec` tool also uses `cwd` as its read command's directory.-The surface is **21 tools**. The four write verbs — `write`, `edit`, `delete`, `move` — are native CRUD operations polymorphic over a target. `write`, `edit`, and `delete` nest per-target fields inside the address key (`write({ document: { path, content } })`) and take exactly one target per call: `document`, `folder`, `template`, or `skill` — plus `asset` for `write` and `delete`, and a `documents` batch on `write` that writes several docs in order, each entry carrying its own `summary`. `move` takes flat `from`/`to` paths and auto-detects a document, folder, or asset, with nested `template` and `skill` targets for those two.+The surface is **19 tools**. The four write verbs — `write`, `edit`, `delete`, `move` — are native CRUD operations polymorphic over a target. `write`, `edit`, and `delete` nest per-target fields inside the address key (`write({ document: { path, content } })`) and take exactly one target per call: `document`, `folder`, `template`, or `skill` — plus `asset` for `write` and `delete`, and a `documents` batch on `write` that writes several docs in order, each entry carrying its own `summary`. `move` takes flat `from`/`to` paths and auto-detects a document, folder, or asset, with nested `template` and `skill` targets for those two.To point an MCP client at this server, locally or over a tunnel from another machine, see [Connect remote agents](/docs/remote-control/connecting-agents).@@ -18,7 +18,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac| --- | --- || `exec` | Read-only shell (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`); reads return frontmatter, backlinks, recent history, and any unresolved [comments](/docs/features/comments) left on the doc. When the [frontmatter schemas](/docs/advanced/content-rules/frontmatter) plugin is on, doc and folder entries also carry `schemas: …` naming the JSON Schema files that govern them — the contract to read before writing. Fs-direct; works without the server. || `search` | Ranked workspace search (title boost + body BM25 + recency; same engine the cmd-K palette uses). `intent: "omnibar"` narrows to fast title/path matching (`full_text`, the default, includes the body); `scopes` filters hit kinds; `limit` caps rows (default 20, max 100). When [semantic search](/docs/reference/configuration#semantic-search) is enabled, an embeddings signal is additionally fused into `full_text` ranking (opt-in, content egress) — pass `semantic: false` to force pure-lexical. Right after boot, an empty result set with `ready: false` means the index is still building — retry after a couple of seconds rather than treating it as no matches. |-| `links` | Wiki-link graph. `kind` selects: `backlinks`, `forward`, `dead`, `orphans`, `hubs`, or `suggest`. Accepts an array (e.g. `["dead", "orphans", "hubs"]`) to fetch several views in one call; each view nests under its own key in the response. `dead` is the raw graph view: unlike `audit`, it still lists unresolved links whose source is a skill document (always) or a lowercase-stemmed `log.md`/`log.mdx` (while the project's default-on `validation.suppressLogLinkAdvisories` is on, with `audit` reporting `brokenLinkSuppression` when it withheld them) — read those deliberately, not as a repair queue |+| `links` | Link relationships. `kind` selects: `backlinks`, `forward`, `dead`, `orphans`, `hubs`, or `suggest`; shorthand wiki targets resolve to the same document in every view, including after edits. 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. `dead` is the raw graph view: unlike `audit`, it still lists unresolved links whose source is a skill document (always) or a lowercase-stemmed `log.md`/`log.mdx` (while the project's default-on `validation.suppressLogLinkAdvisories` is on, with `audit` reporting `brokenLinkSuppression` when it withheld them) — read those deliberately, not as a repair queue || `lint` | Report content-rule problems (markdownlint style rules, frontmatter schema validation, document-level OKF checks) 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 and project-wide at 10 warnings with accurate totals; configuration or runtime degradation problems ride a separate `warnings` channel, with `omittedWarningCount` when warnings are dropped. Successful responses include `ran`, the enabled document-lint source families selected for that call (`markdownlint`, `frontmatter`, and/or document-level `okf`). A family absent from `ran` was not checked, and `[]` means no checks were selected at all. 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`. A fix that landed but could not be re-verified sets `diagnosticsArePreFix` (branch on it) and explains itself in `reLintFailure`, whose `reason` is a closed discriminant and whose `message` is the prose. Example output: [content rules overview](/docs/advanced/content-rules/overview#ai-agents) || `audit` | Unified read-only validation audit: every content problem — content-rule violations (markdownlint, frontmatter schemas, OKF) **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; 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). Skill documents are excluded from the broken-link half: a skill's links routinely name files it creates only at runtime (use `links({ kind: "dead" })` to see them; links from other documents to a skill still validate; documents that merely sit under a dot directory, such as `.github/CI_RUNBOOK.md`, keep their findings). A lowercase-stemmed `log.md` or `log.mdx` at any depth is excluded the same way while the project's default-on `validation.suppressLogLinkAdvisories` setting is on, because a log's entries deliberately reference pages that moved or were never written, and repairing them would rewrite the history (`links({ kind: "dead" })` is unconditional and still reports them, and `LOG.md` is an ordinary document that keeps its findings). Successful responses include `ran`: enabled document-lint families plus `links` unless link validation is off. Document and project-tree OKF checks share the `okf` family, and a family absent from `ran` was not checked. A selected family remains in `ran` if it degrades, with the reason explained in `warnings`; a partial degradation may still have contributed findings. Same 10 × 10 output cap as `lint`'s audit, plus a warning cap set project-wide at 10 warnings, with accurate totals and `omittedWarningCount` when warnings are dropped. 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 |@@ -30,17 +30,21 @@ To point an MCP client at this server, locally or over a tunnel from another mac| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) || `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) || `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |-| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything |+| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`. Links to the moved document keep pointing to it. The old path stops existing; no redirect or stub is left behind. The move can also edit referring documents to preserve their existing link targets, including links to documents that did not move when the new path would otherwise take precedence. Correctly resolving shorthand stays unchanged; necessary wiki rewrites preserve displayed text, aliases and headings. Renaming or moving a page in the app's sidebar rewrites links the same way, so the old name stays visible as link text. A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything || `install` | Manage **where** a skill is available. A skill is one real folder (its source, which itself loads) plus managed copies/symlinks at other locations — there is no draft state and no "uninstall everywhere". `add` / `remove` change the other locations (editor ids, `agents`, or custom root paths); `mode` flips an editor copy↔symlink; `source` relocates the real folder. To make a skill stop existing, use `delete` || `import` | Acquire a skill from a full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), `owner/repo[/subpath]`, a git URL, or a local / `file://` path into the vendor-neutral `.agents/skills/<name>/` hub as versioned content — live immediately, with cross-harness projection via `install`. Pass the required `add` array with at least one install location (an editor id, `agents`, or a custom root path). Use `skill` to choose one skill from a multi-skill source or a `skills({ query })` result. Records provenance in `.ok/skills-lock.json`; a name collision lands under `<name>-imported`; scripts are imported as content and never executed || `checkpoint` | Save a project-wide version snapshot — a single restore point. Returns its `version` || `restore_version` | Restore one `document` or `skill` to a historical `version` (the SHA from `history` or `checkpoint`) |-| `conflicts` | Read tracked conflicts. `kind: "list"` enumerates them (`{ file, detectedAt, conflict, reason?, conflictKind?, docName }`); `kind: "content"` returns one file's stages and metadata (`{ file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions }`). `conflictKind: "stale-external-write"` identifies a protected stale save; Git working-tree overlays use `conflict.kind: "working-tree"` |-| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content` / `delete`, narrowed by that conflict's `resolutionOptions`). Only `merge-native` creates a resolution commit |++## Audit scopes and complete results++The `path` scope for `audit` and project-wide `lint` selects an existing file or directory first. If a document stem without `.md` or `.mdx` does not exist, OpenKnowledge tries `.mdx` before `.md`; an explicitly supplied document extension must exist as written. An unknown scope returns a not-found error naming the path and how to correct it. An existing empty or ignored scope reports zero documents checked and an informational warning, rather than implying the content passed validation. The CLI equivalents, `ok audit` and `ok lint`, share these path-resolution rules: unknown scopes exit 1 (before any `--fix` write), while valid zero-document scopes exit 0. `audit`, project-wide `lint` and server-backed `ok audit` refuse hidden-segment scopes: zero documents are checked and the refusal is an ordinary warning, not the informational empty-scope one (`ok audit` exits 0). Headless `ok lint` checks them when explicitly named.++Narrowing `path` reduces competing files, but does not lift per-file caps. Use `lint({ document: "guides/intro" })` for all document-lint findings, and `links({ kind: "dead", sourceDocuments: ["guides/intro"] })` for raw unresolved links from that document. Project-tree OKF findings in MCP audit results remain capped. Diagnostic totals always cover the full scan.## Output shape mirrors the input-The write verbs nest their result under the same target key you wrote, mirroring the input: `write({ folder })` returns `{ folder: { ok, path } }`, `edit({ document })` returns `{ document: { … } }`, and a batch returns `{ documents: [ … ] }`. The preview envelope (`previewUrl`, `previewUrlSource`, `warning`) stays at the top level on `write` and `edit` responses; read tools (`search`, `links`, `exec`) attach a route-only `previewUrl` to each hit or entry instead. `conflicts` and `links` nest the same way under their `kind`.+The write verbs nest their result under the same target key you wrote, mirroring the input: `write({ folder })` returns `{ folder: { ok, path } }`, `edit({ document })` returns `{ document: { … } }`, and a batch returns `{ documents: [ … ] }`. The preview envelope (`previewUrl`, `previewUrlSource`, `warning`) stays at the top level on `write` and `edit` responses; read tools (`search`, `links`, `exec`) attach a route-only `previewUrl` to each hit or entry instead. `links` nests the same way under its `kind`.## Advisory warnings@@ -73,14 +77,14 @@ A doc can land in conflict through a Git merge, a pull that collides with a loca"type": "urn:ok:error:doc-in-conflict","title": "Document is in conflict.","status": 409,- "detail": "The document is in a conflict state. Call conflicts({ kind: \"content\" }) + resolve_conflict before retrying.",+ "detail": "The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.","file": "notes/sso.md","conflict": { "kind": "reconcile", "reason": "disk-markers" },"resolutionOptions": ["mine", "content", "delete"]}```-A write that first detects the stale file during its final disk flush returns a different 409, `urn:ok:error:stale-external-write`. The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Resolve and re-read before retrying, so you don't duplicate an append that already reached `ours`.+A write that first detects the stale file during its final disk flush returns a different 409, `urn:ok:error:stale-external-write`. The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Ask the user to resolve the conflict, then re-read the document. Do not repeat the operation: compare the resolved content with the intended result and make only any remaining edit.`conflict.kind` says where the conflict came from, and the kind decides what a resolve does. `merge-native` is a git merge that left unmerged stages in the index. Resolving one stages your choice with git and commits the merge once no `merge-native` conflict is left. `working-tree` is a pull-only overlay collision, pinned to the origin blob it hit. `reconcile` is OpenKnowledge's own three-way merge of the editor against disk, including protected stale saves; no git object holds those stages, so OpenKnowledge snapshots them when it detects the conflict. Resolving a `working-tree` or `reconcile` conflict commits nothing.@@ -92,22 +96,22 @@ A write whose document path cannot be resolved inside the content directory retuA write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. Retry only after the filesystem fault is repaired.-A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so `conflicts()` and `resolve_conflict` do not apply to it. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which are never refused. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.+A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so there is nothing to resolve. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which are never refused. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.### Resolving a conflict-1. `conflicts({ kind: "list" })` returns every tracked conflict as `{ file, detectedAt, conflict, reason?, conflictKind?, docName }`. Call it to detect conflicts without waiting for a 409.-2. `conflicts({ kind: "content", file })` returns `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }`. `ours` is the live Y.Text when the doc is loaded and marker-free; otherwise it falls back to the stage pinned at detection. For a stale external write, `ours` is the protected content and `theirs` is the rejected older save.-3. `resolve_conflict({ file, strategy, content? })` writes the chosen bytes. Send a strategy from that conflict's `resolutionOptions`, not the full set. A `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and sending it anyway returns a 422 with `refusal: "strategy-not-offered"`. The same 422 shape carries `refusal: "markers-in-content"` when the bytes you sent still contain markers, and that field is what tells the two apart. A 404 (`urn:ok:error:no-conflict-tracked`) means nothing is tracked for that path. Re-read the list; it does not mean your resolution was saved. A 500 (`urn:ok:error:internal-server-error`) means the resolution was not recorded: the conflict is still tracked and the call is retryable. Both 500s surface as an error whose text carries the problem title: `Failed to resolve conflict.` from the resolver itself, or `Failed to read request body.` when the request never got that far. The structured content is `{ ok: false, file }`, where `file` is the argument you sent rather than a value from the response. Your `strategy` does not come back either way, so resubmit the `file` and `strategy` you already hold. On `delete` the file may already be gone from disk even though the resolution did not complete; resubmitting `delete` finishes the teardown rather than failing on the missing file.--What `mine` and `theirs` mean depends on the kind. On `merge-native` they are `git checkout --ours` and `git checkout --theirs` (the committed stages 2 and 3), and `delete` is `git rm`. On `working-tree`, `mine` keeps your overlay verbatim and `theirs` restores the pinned origin blob. On `reconcile`, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk bytes captured at detection. `content` always writes the bytes you supply, and `delete` always removes the file.--`file` is a `.md` or `.mdx` path relative to the project directory, extension included. It mirrors the on-disk shape, not the extension-less `document` path the other tools take.--For how a conflict appears and resolves in the app, see [Resolving a conflict](../features/github-sync.mdx#resolving-a-conflict). The `conflicts` and `resolve_conflict` tool descriptions repeat the per-kind rules at the call site.+The MCP server has no conflict tools. An agent that hits `doc-in-conflict` or `stale-external-write` should name the file and ask the user to resolve it in the app; see [Resolving a conflict](../features/github-sync.mdx#resolving-a-conflict). HTTP integrations can list conflicts with `GET /api/sync/conflicts`, then read `GET /api/sync/conflict-content?file=<path>` for `base`, `ours`, `theirs`, the conflict kind, and its current `resolutionOptions`. To resolve one, send `POST /api/sync/resolve-conflict` with `{ file, strategy }`, choosing an offered strategy (`mine`, `theirs`, `content`, or `delete`). The `content` strategy also requires `content`; an empty string keeps an empty file. Content must be free of conflict markers. Use only the strategies returned for that conflict; its kind determines the commit behavior described above.## Preview linksRead and write tools return a `previewUrl` for any doc they touched, but **those are route-only** (`/#/<doc>` with no host:port), meant to identify the doc, not to be opened as-is. Hosts that want to open the editor (Claude Code Desktop's `preview_start({url})`, terminal `open <url>`) call `preview_url` to resolve the full URL once per session.`preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](./configuration.mdx) preference. The write tools (`write`, `edit`) carry the same boolean on the `warning` object, which fires only when no browser is attached to the preview. In the common case (a browser is attached), the write response has no `warning` and no `autoOpen` field. Agents honor `autoOpen` before navigating: `true` (default) follows the host-capability routing in the bundled skill; `false` means the user is managing their own preview window, so the agent surfaces the URL on request but does not open or refresh anything. The value is resolved fresh on every tool call, so a mid-session toggle propagates within 0–1 calls, with no client restart.++## Refresh agent guidance++Update the OpenKnowledge build that serves your MCP connection. If you use the desktop app, update that app; on macOS, the CLI can use its bundled server and skills, so updating only the npm package can leave the desktop's older guidance in use. For a standalone CLI installation, update the CLI.++Then run `ok init` in the project, or turn its editor integration off and on in **Settings → Agent connections**. Reconnect the agent client to load the updated tools and project skill.++In-app agents refresh their bundled skill when a new thread starts. The Claude Code plugin starts OpenKnowledge through `npx @inkeep/open-knowledge@latest mcp` and does not bundle a skill; refresh project guidance with the steps above. `ok repair-skills` repairs user-global bundles and restores missing project copies, but preserves an existing project skill; use the steps above to refresh that copy.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex af7ea06b0..c3a6c5fd6 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -226,7 +226,7 @@ With `--scope user` or `both` (the default), `ok init` also registers the `open-| `~/.ok/skill-state.yml` | Records which skill version is installed, so the step is skipped next time | Outside-project (home dir) || `~/.ok/skill-install-events.jsonl` | Append-only local log of skill-install attempts | Outside-project (home dir) |-The install is **non-fatal** (`ok init` still exits 0 if it fails), **version-gated** (a no-op when the current version is already installed), and needs **no network access**. Skip it for one run with `ok init --no-skills`, or choose individual bundles with `--skills <ids>`. Skipping records nothing and removes nothing, so skills already on the machine are left alone. An installed bundle is remembered in `~/.ok/skill-state.yml` and honored by every later install path; to turn the built-in skills off for good, decline at the first-launch prompt or uninstall from **Settings → Skills Studio**, either of which records a durable machine-wide choice. `ok repair-skills` re-runs it.+The install is **non-fatal** (`ok init` still exits 0 if it fails), **version-gated** (a no-op when the current version is already installed), and needs **no network access**. Skip it for one run with `ok init --no-skills`, or choose individual bundles with `--skills <ids>`. Skipping records nothing and removes nothing, so skills already on the machine are left alone. An installed bundle is remembered in `~/.ok/skill-state.yml` and honored by every later install path; to turn the built-in skills off for good, decline at the first-launch prompt or uninstall from **Settings → Skills Studio**, either of which records a durable machine-wide choice. `ok repair-skills` explicitly repairs these user-global bundles. Its project sweep restores missing skill copies but leaves existing project copies unchanged; see [Refresh agent guidance](./mcp.mdx#refresh-agent-guidance) to update those.Pi has no user-level MCP config. `ok init` writes its project-scoped bridge extension; using Pi inside OpenKnowledge can also add a [folder trust grant](#pi-folder-trust), whose location respects `PI_CODING_AGENT_DIR`.@@ -274,7 +274,7 @@ On each boot, `ok start` also runs **repair sweeps**: it re-checks a few things| Existing `open-knowledge` MCP entries | The same editor configs `ok init` writes — **both** user-level (`~/.claude.json`, `~/.cursor/mcp.json`, …) and project-level | Outside-project (editor config) **and** in-project || Stale `open-knowledge-ui` entry in `.claude/launch.json` | Project | Removed if present — OK no longer writes launch.json |-Disable both repair sweeps with `OK_RECLAIM_DISABLE=1`. They leave installed editor skills alone; `ok repair-skills` is the explicit command for those. Starting an in-app agent thread creates or refreshes the runtime skill copy listed above.+Disable both repair sweeps with `OK_RECLAIM_DISABLE=1`. They leave installed editor skills alone. `ok repair-skills` explicitly restores missing project copies and repairs user-global bundles; [refresh existing project guidance](./mcp.mdx#refresh-agent-guidance) with `ok init` or the integration settings. Starting an in-app agent thread creates or refreshes the runtime skill copy listed above.Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitignore`, which leaves these runtime files visible in `git status`. Add `local/` to that file or open the project in the desktop app, which updates it automatically. The runtime skill copy is always excluded from the knowledge base.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 5437d78b7..cec85dd82 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -37,7 +37,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.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/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.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/new-item-shortcut-fast-path.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/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.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/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.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/selection-surface-pane-clip.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/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts",+ "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.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/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.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/new-item-shortcut-fast-path.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/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.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/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.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/selection-surface-pane-clip.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/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.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/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex aef63787a..ffee68e05 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -1,4 +1,5 @@import type { EditorView as CodeMirrorView } from '@codemirror/view';+import { i18n } from '@lingui/core';import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -27,6 +28,7 @@ vi.doMock('@lingui/react/macro', () => ({...actualLinguiMacro,Trans: ({ children }: { children: ReactNode }) => <>{children}</>,useLingui: () => ({+ i18n,t: (strings: TemplateStringsArray, ...values: unknown[]) =>strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),}),diff --git a/packages/app/src/components/BottomComposer.drop.dom.test.tsx b/packages/app/src/components/BottomComposer.drop.dom.test.tsxindex 7eb28f147..db813ff42 100644--- a/packages/app/src/components/BottomComposer.drop.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.drop.dom.test.tsx@@ -1,3 +1,4 @@+import { i18n } from '@lingui/core';import * as actualLinguiMacro from '@lingui/react/macro';import {act,@@ -39,6 +40,7 @@ vi.doMock('@lingui/react/macro', () => ({...actualLinguiMacro,Trans: ({ children }: { children: ReactNode }) => <>{children}</>,useLingui: () => ({+ i18n,t: (strings: TemplateStringsArray, ...values: unknown[]) =>strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),}),diff --git a/packages/app/src/components/ConflictView.tsx b/packages/app/src/components/ConflictView.tsxindex 2491ae78b..f1daddcfa 100644--- a/packages/app/src/components/ConflictView.tsx+++ b/packages/app/src/components/ConflictView.tsx@@ -382,7 +382,7 @@ export function ConflictView({</div>{parseMismatch && (<p role="status" className="shrink-0 border-b px-3 py-2 text-xs text-muted-foreground">- {t`This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI.`}+ {t`This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand.`}</p>)}<div className="flex shrink-0 items-center gap-1 border-b px-3 py-2">diff --git a/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsxindex 4516e6029..fa5a3acc0 100644--- a/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx+++ b/packages/app/src/components/DiffViewBoundary.missing-conflict.dom.test.tsx@@ -41,7 +41,7 @@ const FILE = 'notes/roadmap.md';const DOC = 'notes/roadmap';const MISSING_TYPE = 'urn:ok:error:no-conflict-tracked';const MISSING_DETAIL =- 'This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Re-read conflicts({ kind: "list" }) before retrying.';+ 'This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Refresh the conflict list in the OpenKnowledge app before retrying.';const FIRST_CONFLICT: ConflictEntryWire = {file: FILE,docName: DOC,diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsxindex f4ef0c071..7d6dd9d0d 100644--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx@@ -1067,6 +1067,23 @@ describe('ProblemsPanel — project scope', () => {);});+ test('an empty-scope notice is informational rather than a configuration warning', async () => {+ runLintAuditImpl = async () =>+ auditResult({+ fileCount: 0,+ warnings: ['No documents were checked: this scope contains no admitted documents.'],+ });+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);++ fireEvent.click(screen.getByTestId('panel-scope-project'));+ const notice = await screen.findByText(+ 'No documents were checked: this scope contains no admitted documents.',+ );+ expect(notice.closest('[role="status"]')).not.toBeNull();+ expect(screen.queryByRole('list', { name: 'Configuration warnings' })).toBeNull();+ expect(screen.queryByText(/No problems across/)).toBeNull();+ });+test('project audit shows a content-free note when reserved-log links are suppressed', async () => {runLintAuditImpl = async () =>auditResult({diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsxindex 250e61163..99f5c4b79 100644--- a/packages/app/src/components/ProblemsPanel.tsx+++ b/packages/app/src/components/ProblemsPanel.tsx@@ -3,6 +3,7 @@import {type BrokenLinkSuppression,type FrontmatterScope,+ isAuditEmptyScopeWarning,isEditableTextDocFile,type ValidationAuditResponse,type ValidationDocResult,@@ -1048,11 +1049,13 @@ function ProjectAuditResults({onToggleFile: (file: string, open: boolean) => void;}) {const { t } = useLingui();+ const configWarnings = result.warnings.filter((warning) => !isAuditEmptyScopeWarning(warning));+ const emptyScopeWarnings = result.warnings.filter(isAuditEmptyScopeWarning);return (<div className="flex flex-col gap-1">- {result.warnings.length > 0 && (+ {configWarnings.length > 0 && (<ul aria-label={t`Configuration warnings`} className="flex flex-col gap-0.5 pb-1">- {result.warnings.map((warning, index) => (+ {configWarnings.map((warning, index) => (// biome-ignore lint/suspicious/noArrayIndexKey: the warnings array is a static audit snapshot (no reorder/insert between renders), and identical config warnings can legitimately repeat — a text-only key would collide.<li key={`${index}-${warning}`} className="flex items-start gap-1.5 px-2 text-xs"><AlertTriangle@@ -1064,11 +1067,17 @@ function ProjectAuditResults({))}</ul>)}+ {emptyScopeWarnings.map((warning) => (+ <div key={warning} role="status" className="flex items-start gap-1.5 px-2 text-xs">+ <Info aria-hidden="true" className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 text-foreground">{warning}</span>+ </div>+ ))}{result.brokenLinkSuppression !== undefined && (<BrokenLinkSuppressionNote suppression={result.brokenLinkSuppression} />)}{result.files.length === 0 ? (- result.brokenLinkSuppression === undefined ? (+ result.brokenLinkSuppression === undefined && emptyScopeWarnings.length === 0 ? (<PanelEmpty className="px-2"><Pluralvalue={result.fileCount}diff --git a/packages/app/src/components/composer-shared-draft.dom.test.tsx b/packages/app/src/components/composer-shared-draft.dom.test.tsxindex c788d20dd..82609c4b5 100644--- a/packages/app/src/components/composer-shared-draft.dom.test.tsx+++ b/packages/app/src/components/composer-shared-draft.dom.test.tsx@@ -1,4 +1,5 @@import type { CreateScenario, InstallState } from '@inkeep/open-knowledge-core';+import { i18n } from '@lingui/core';import * as actualLinguiMacro from '@lingui/react/macro';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { JSONContent } from '@tiptap/core';@@ -11,6 +12,7 @@ vi.doMock('@lingui/react/macro', () => ({...actualLinguiMacro,Trans: ({ children }: { children: ReactNode }) => <>{children}</>,useLingui: () => ({+ i18n,t: (strings: TemplateStringsArray, ...values: unknown[]) =>strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),}),diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex 8bdf7e5ef..83d2a5dc3 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -19,6 +19,19 @@ describe('deriveKnownFolderPaths', () => {});describe('resolveNavigationTarget', () => {+ test('slug-collision navigation agrees for reversed page inventories', () => {+ for (const order of [+ ['a/b', 'a-b'],+ ['a-b', 'a/b'],+ ]) {+ expect(resolveNavigationTarget('A B', { pages: new Set(order) })).toEqual({+ kind: 'doc',+ target: 'a-b',+ docName: 'a-b',+ });+ }+ });+test('resolves managed-artifact docs as real doc targets (never missing)', () => {const docName = '__skill__/global/foo';expect(resolveNavigationTarget(docName, { pages: new Set() })).toEqual({@@ -143,7 +156,7 @@ describe('resolveNavigationTarget', () => {});});- test('an extension-less page outranks a qualified entry for the same stem', () => {+ test('an exact dotted identity outranks the extension-less page for the same stem', () => {const resolved = resolveNavigationTarget('docs/guide.md', {pages: new Set(['docs/guide.md', 'docs/guide.mdx', 'docs/guide']),folderPaths: new Set(['docs']),@@ -151,8 +164,8 @@ describe('resolveNavigationTarget', () => {expect(resolved).toEqual({kind: 'doc',- target: 'docs/guide',- docName: 'docs/guide',+ target: 'docs/guide.md',+ docName: 'docs/guide.md',});});@@ -775,7 +788,7 @@ describe('editable text docs resolve as doc targets', () => {});});-describe('markdown-extension normalization keeps one room per file', () => {+describe('markdown-extension normalization preserves document identity', () => {test('a managed-artifact skill reference normalizes before the early return', () => {expect(resolveNavigationTarget('__skill__/global/my-skill/references/guide.md', {@@ -799,20 +812,24 @@ describe('markdown-extension normalization keeps one room per file', () => {});});- test('the stripped twin wins over an extension-qualified index entry', () => {+ test('an exact dotted identity wins over its stripped twin', () => {const pages = new Set(['specs/demo/SPEC', 'specs/demo/SPEC.md']);expect(resolveNavigationTarget('specs/demo/SPEC.md', { pages })).toEqual({kind: 'doc',- target: 'specs/demo/SPEC',- docName: 'specs/demo/SPEC',+ target: 'specs/demo/SPEC.md',+ docName: 'specs/demo/SPEC.md',});});- test('repeated extensions collapse to the stem', () => {+ test('only one terminal Markdown extension is removed', () => {const pages = new Set(['notes/idea']);+ expect(resolveNavigationTarget('notes/idea.md.md', { pages })).toMatchObject({+ kind: 'missing',+ });+ pages.add('notes/idea.md');expect(resolveNavigationTarget('notes/idea.md.md', { pages })).toMatchObject({kind: 'doc',- docName: 'notes/idea',+ docName: 'notes/idea.md',});});diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex cf5410096..4cc2ce0d1 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -11,9 +11,9 @@ import {parseManagedArtifactName,parseTemplateContentDocName,projectSkillContentDocName,+ resolveWikiLinkTargetDocName,type SkillScope,templateContentDocName,- toWikiLinkSlug,} from '@inkeep/open-knowledge-core';import type { SkillPreviewFlavor } from '@/lib/doc-hash';import { normalizeDocNameInput } from '@/lib/doc-paths';@@ -107,22 +107,11 @@ function extensionlessTargetPath(target: string): string {const MARKDOWN_TARGET_EXTENSION = /\.(md|mdx)$/i;-function stripMarkdownTargetExtensions(target: string): string {- let candidate = target;- while (MARKDOWN_TARGET_EXTENSION.test(candidate)) {- const next = candidate.replace(MARKDOWN_TARGET_EXTENSION, '');- if (!next) return candidate;- candidate = next;- }- return candidate;-}--function canonicalNavigationTarget(target: string, pages: ReadonlySet<string>): string {+function managedArtifactNavigationTarget(target: string, pages: ReadonlySet<string>): string {const { normalizedTarget, expectsFolder } = normalizeTargetPath(target);if (expectsFolder || !MARKDOWN_TARGET_EXTENSION.test(normalizedTarget)) return target;- const stripped = stripMarkdownTargetExtensions(normalizedTarget);- if (pages.has(normalizedTarget) && !pages.has(stripped)) return target;- return stripped;+ if (pages.has(normalizedTarget)) return target;+ return normalizedTarget.replace(MARKDOWN_TARGET_EXTENSION, '');}export function deriveKnownFolderPaths(docNames: Iterable<string>): Set<string> {@@ -135,27 +124,6 @@ export function deriveKnownFolderPaths(docNames: Iterable<string>): Set<string>return folderPaths;}-function slugResolve(- normalizedTarget: string,- pagesBySlug: ReadonlyMap<string, string> | undefined,-): string | undefined {- if (!pagesBySlug) return undefined;- const slug = toWikiLinkSlug(normalizedTarget);- if (!slug) return undefined;- return pagesBySlug.get(slug);-}--function basenameResolve(- normalizedTarget: string,- pagesByBasename: ReadonlyMap<string, string> | undefined,-): string | undefined {- if (!pagesByBasename) return undefined;- if (normalizedTarget.includes('/')) return undefined;- const slug = toWikiLinkSlug(normalizedTarget);- if (!slug) return undefined;- return pagesByBasename.get(slug);-}-function okReadOnlyAssetPath(docName: string, docExt?: string): string {if (docExt) return `${docName}${docExt}`;const leaf = docName.split('/').pop() ?? '';@@ -187,24 +155,25 @@ export function resolveNavigationTarget(pagesByBasename?: ReadonlyMap<string, string>;},): ResolvedContentTarget {- const target = canonicalNavigationTarget(requestedTarget, options.pages);- if (isManagedArtifactDocName(target)) {- const parsed = parseManagedArtifactName(target);+ const target = requestedTarget;+ const artifactTarget = managedArtifactNavigationTarget(target, options.pages);+ if (isManagedArtifactDocName(artifactTarget)) {+ const parsed = parseManagedArtifactName(artifactTarget);if (parsed?.kind === 'skill' && parsed.scope === 'project') {const docName = projectSkillContentDocName(parsed.name);return { kind: 'doc', target: docName, docName };}- const legacyTemplate = parseLegacyTemplateDocName(target);+ const legacyTemplate = parseLegacyTemplateDocName(artifactTarget);if (legacyTemplate) {const docName = templateContentDocName(legacyTemplate.folder, legacyTemplate.name);return { kind: 'doc', target: docName, docName };}- return { kind: 'doc', target, docName: target };+ return { kind: 'doc', target: artifactTarget, docName: artifactTarget };}- if (parseProjectSkillContentDocName(target)) {- return { kind: 'doc', target, docName: target };+ if (parseProjectSkillContentDocName(artifactTarget)) {+ return { kind: 'doc', target: artifactTarget, docName: artifactTarget };}- const templateContent = parseTemplateContentDocName(target);+ const templateContent = parseTemplateContentDocName(artifactTarget);if (templateContent) {const docName = templateContentDocName(templateContent.folder, templateContent.name);return { kind: 'doc', target: docName, docName };@@ -223,71 +192,55 @@ export function resolveNavigationTarget(}const extensionlessTarget = extensionlessTargetPath(target);- if (- !expectsFolder &&- extensionlessTarget !== normalizedTarget &&- options.pages.has(extensionlessTarget)- ) {- return {- kind: 'doc',- target: extensionlessTarget,- docName: extensionlessTarget,- };- }-- if (!expectsFolder && options.pages.has(normalizedTarget)) {- return {- kind: 'doc',- target: normalizedTarget,- docName: normalizedTarget,- };- }+ const resolvedDocName = expectsFolder+ ? undefined+ : resolveWikiLinkTargetDocName(normalizedTarget, {+ pages: options.pages,+ pagesBySlug: options.pagesBySlug ?? new Map<string, string>(),+ pagesByBasename: options.pagesByBasename,+ });- if (!expectsFolder) {- const slugMatchDocName = slugResolve(extensionlessTarget, options.pagesBySlug);- if (slugMatchDocName) {+ const folderTargets = expectsFolder+ ? [extensionlessTarget]+ : [normalizedTarget, extensionlessTarget];+ for (const folderTarget of folderTargets) {+ const canonicalIndexDocName = `${folderTarget}/index`;+ if (+ expectsFolder+ ? options.pages.has(canonicalIndexDocName)+ : resolvedDocName === canonicalIndexDocName+ ) {return {- kind: 'doc',- target: slugMatchDocName,- docName: slugMatchDocName,+ kind: 'folder-index',+ target: folderTarget,+ folderPath: folderTarget,+ docName: canonicalIndexDocName,+ noteKind: 'canonical-index',};}- }- const canonicalIndexDocName = `${extensionlessTarget}/index`;- if (options.pages.has(canonicalIndexDocName)) {- return {- kind: 'folder-index',- target: extensionlessTarget,- folderPath: extensionlessTarget,- docName: canonicalIndexDocName,- noteKind: 'canonical-index',- };- }-- const leaf = extensionlessTarget.split('/').pop();- const legacyFolderNoteDocName = leaf ? `${extensionlessTarget}/${leaf}` : null;- if (legacyFolderNoteDocName && options.pages.has(legacyFolderNoteDocName)) {- return {- kind: 'folder-index',- target: extensionlessTarget,- folderPath: extensionlessTarget,- docName: legacyFolderNoteDocName,- noteKind: 'legacy-folder-note',- };- }-- if (!expectsFolder) {- const basenameMatchDocName = basenameResolve(extensionlessTarget, options.pagesByBasename);- if (basenameMatchDocName) {+ const leaf = folderTarget.split('/').pop();+ const legacyFolderNoteDocName = leaf ? `${folderTarget}/${leaf}` : null;+ if (+ legacyFolderNoteDocName &&+ (expectsFolder+ ? options.pages.has(legacyFolderNoteDocName)+ : resolvedDocName === legacyFolderNoteDocName)+ ) {return {- kind: 'doc',- target: basenameMatchDocName,- docName: basenameMatchDocName,+ kind: 'folder-index',+ target: folderTarget,+ folderPath: folderTarget,+ docName: legacyFolderNoteDocName,+ noteKind: 'legacy-folder-note',};}}+ if (resolvedDocName !== undefined) {+ return { kind: 'doc', target: resolvedDocName, docName: resolvedDocName };+ }+const knownFolderPaths = options.folderPaths ?? deriveKnownFolderPaths(options.pages);if (knownFolderPaths.has(extensionlessTarget)) {return {diff --git a/packages/app/src/components/wiki-link-ordering-contract.test.ts b/packages/app/src/components/wiki-link-ordering-contract.test.tsindex a978131b7..25bd0522f 100644--- a/packages/app/src/components/wiki-link-ordering-contract.test.ts+++ b/packages/app/src/components/wiki-link-ordering-contract.test.ts@@ -71,3 +71,33 @@ describe('bare-name resolution ordering contract', () => {expect(viaNavigation('notes', forward)).toBe(viaNavigation('notes', reversed));});});++describe('explicit Markdown suffix navigation parity', () => {+ test.each([+ ['x.md', ['x', 'x.md'], 'x.md'],+ ['x.md.md', ['x', 'x.md', 'x.md.md'], 'x.md.md'],+ ['x.md.md', ['x', 'x.md'], 'x.md'],+ ['notes/beta.md', ['notes/beta', 'notes/beta-md'], 'notes/beta'],+ ['notes/beta.md', ['Notes/Beta', 'notes/beta-md'], 'Notes/Beta'],+ ['Beta Guide.MDX', ['notes/Beta Guide', 'beta-guide-mdx'], 'notes/Beta Guide'],+ ['reports.md', ['reports/index', 'reports-md'], 'reports/index'],+ ['reports.mdx', ['reports/reports', 'reports-mdx'], 'reports/reports'],+ ['beta.md', ['notes/beta', 'beta-md'], 'notes/beta'],+ ['notes/beta.md', ['notes/beta-md'], 'notes/beta-md'],+ ['beta.md', ['notes/beta-md'], 'notes/beta-md'],+ ['reports.md', ['reports.md/index'], 'reports.md/index'],+ ] satisfies Array<[string, string[], string]>)(+ '%s in %j opens %s',+ (target, docNames, expected) => {+ const pages = new Set(docNames);+ expect(viaShared(target, pages)).toBe(expected);+ expect(viaNavigation(target, pages)).toBe(expected);+ },+ );++ test('a doubled suffix does not fall through to a second suffix removal', () => {+ const pages = new Set(['x']);+ expect(viaShared('x.md.md', pages)).toBeUndefined();+ expect(resolveNavigationTarget('x.md.md', { pages }).kind).toBe('missing');+ });+});diff --git a/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.tsindex 4d2ff101d..cac5306b0 100644--- a/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts+++ b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts@@ -121,3 +121,25 @@ describe('WYSIWYG wiki-link activation', () => {expect(currentHash()).toBe('#/__asset__/absent.pdf');});});++describe('WYSIWYG activation preserves Markdown target identity', () => {+ test.each([+ ['notes/beta.md', ['notes/beta', 'notes/beta-md'], 'notes/beta'],+ ['NOTES/BETA.MDX', ['notes/beta', 'notes/beta-mdx'], 'notes/beta'],+ ['beta.md', ['notes/beta', 'beta-md'], 'notes/beta'],+ ['x.md', ['x', 'x.md'], 'x.md'],+ ['x.md.md', ['x', 'x.md'], 'x.md'],+ ['fallback.md', ['fallback-md'], 'fallback-md'],+ ] satisfies Array<[string, string[], string]>)('%s opens %s', (target, docNames, expected) => {+ const pages = new Set(docNames);+ setPageListCache({+ pages,+ folderPaths: new Set(),+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ });+ const { activate, currentHash } = mountWikiLink(target);+ expect(activate()).toBe(true);+ expect(currentHash()).toBe(`#/${expected}`);+ });+});diff --git a/packages/app/src/editor/plugins/wiki-link-source.destination.test.ts b/packages/app/src/editor/plugins/wiki-link-source.destination.test.tsindex 683982593..cd3c2fd0a 100644--- a/packages/app/src/editor/plugins/wiki-link-source.destination.test.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.destination.test.ts@@ -1,9 +1,6 @@import { describe, expect, test } from 'vitest';-import {- buildSourceWikiLinkLookup,- type PageItem,- resolveSourceWikiLinkDestination,-} from './wiki-link-source';+import type { PageItem } from '../extensions/wiki-link-suggestion';+import { buildSourceWikiLinkLookup, resolveSourceWikiLinkDestination } from './wiki-link-source';const CORPUS: PageItem[] = [{ kind: 'page', docName: 'index', title: 'Home' },@@ -19,21 +16,21 @@ describe('source-mode wiki-link destination', () => {test('a target naming a dotted-filename document opens a document route', () => {expect(resolveSourceWikiLinkDestination('acp.daemon', null, LOOKUP)).toEqual({kind: 'hash',- href: '#/acp.daemon',+ href: '#/notes/acp.daemon',});});test('a dot-free bare name opens a document route', () => {expect(resolveSourceWikiLinkDestination('roadmap', null, LOOKUP)).toEqual({kind: 'hash',- href: '#/roadmap',+ href: '#/notes/roadmap',});});test('an anchor rides along on a document route', () => {expect(resolveSourceWikiLinkDestination('acp.daemon', 'setup', LOOKUP)).toEqual({kind: 'hash',- href: '#/acp.daemon#setup',+ href: '#/notes/acp.daemon#setup',});});@@ -73,3 +70,29 @@ describe('buildSourceWikiLinkLookup', () => {expect(LOOKUP.assetPaths?.has('files/meeting.pdf')).toBe(true);});});++describe('source destination preserves Markdown target identity', () => {+ const lookup = buildSourceWikiLinkLookup([+ { docName: 'notes/beta', title: 'Beta' },+ { docName: 'notes/beta-md', title: 'Other' },+ { docName: 'x', title: 'X' },+ { docName: 'x.md', title: 'Dotted X' },+ { docName: 'reports/index', title: 'Reports' },+ { docName: 'fallback-md', title: 'Fallback' },+ ]);++ test.each([+ ['notes/beta.md', 'notes/beta'],+ ['NOTES/BETA.MDX', 'notes/beta'],+ ['beta.md', 'notes/beta'],+ ['x.md', 'x.md'],+ ['x.md.md', 'x.md'],+ ['reports.md', 'reports/index'],+ ['fallback.md', 'fallback-md'],+ ])('%s routes to %s with its heading', (target, expected) => {+ expect(resolveSourceWikiLinkDestination(target, 'setup', lookup)).toEqual({+ kind: 'hash',+ href: `#/${expected}#setup`,+ });+ });+});diff --git a/packages/app/src/editor/plugins/wiki-link-source.test.ts b/packages/app/src/editor/plugins/wiki-link-source.test.tsindex df5eb56d4..25f441577 100644--- a/packages/app/src/editor/plugins/wiki-link-source.test.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.test.ts@@ -5,175 +5,151 @@ import {} from '../link-validation-policy';import {buildKnownWikilinkTargetSet,- buildPageNameSet,- extractWikilinkTarget,+ buildSourceWikiLinkLookup,wikiLinkSourceClass,} from './wiki-link-source';beforeEach(() => resetLinkValidationPolicyForTest());-describe('buildPageNameSet', () => {- test('empty input → empty set', () => {- expect(buildPageNameSet([]).size).toBe(0);- });-- test('indexes docName', () => {- const s = buildPageNameSet([{ docName: 'README', title: '' }]);- expect(s.has('readme')).toBe(true);- expect(s.size).toBe(1);- });-- test('indexes both docName AND title when present', () => {- const s = buildPageNameSet([{ docName: 'CLAUDE', title: 'CLAUDE Guide' }]);- expect(s.has('claude')).toBe(true);- expect(s.has('claude guide')).toBe(true);- expect(s.size).toBe(2);- });-- test('indexes referenced assets by path and basename', () => {- const s = buildPageNameSet([- { kind: 'asset', docName: '/docs/public/Wide.png', title: 'Wide.png' },- ]);- expect(s.has('/docs/public/wide.png')).toBe(true);- expect(s.has('docs/public/wide.png')).toBe(true);- expect(s.has('wide.png')).toBe(true);- });-- test('lowercases everything', () => {- const s = buildPageNameSet([{ docName: 'ReadMe', title: 'The README' }]);- expect(s.has('readme')).toBe(true);- expect(s.has('the readme')).toBe(true);- expect(s.has('ReadMe')).toBe(false);- expect(s.has('The README')).toBe(false);- });-- test('missing/empty title is skipped (only docName indexed)', () => {- const s = buildPageNameSet([{ docName: 'NoTitle', title: '' }]);- expect(s.has('notitle')).toBe(true);- expect(s.size).toBe(1);- });-- test('dedupes when docName === title (case-insensitive)', () => {- const s = buildPageNameSet([{ docName: 'Foo', title: 'foo' }]);- expect(s.has('foo')).toBe(true);- expect(s.size).toBe(1);- });-- test('multiple pages aggregate into one set', () => {- const s = buildPageNameSet([- { docName: 'a', title: 'Alpha' },- { docName: 'b', title: 'Beta' },- { docName: 'c', title: '' },- ]);- expect(s.size).toBe(5);- expect(s.has('a')).toBe(true);- expect(s.has('alpha')).toBe(true);- expect(s.has('b')).toBe(true);- expect(s.has('beta')).toBe(true);- expect(s.has('c')).toBe(true);- });-});--describe('extractWikilinkTarget', () => {- test('plain page name', () => {- expect(extractWikilinkTarget('SomePage')).toBe('somepage');- });-- test('strips #anchor', () => {- expect(extractWikilinkTarget('SomePage#heading-slug')).toBe('somepage');- });-- test('strips |alias', () => {- expect(extractWikilinkTarget('SomePage|display text')).toBe('somepage');- });-- test('strips both anchor and alias (anchor first)', () => {- expect(extractWikilinkTarget('SomePage#heading|display')).toBe('somepage');- });-- test('strips both (alias first — whichever delimiter comes first wins)', () => {- expect(extractWikilinkTarget('SomePage|display#anchor')).toBe('somepage');- });-- test('lowercases', () => {- expect(extractWikilinkTarget('UPPERcase')).toBe('uppercase');- expect(extractWikilinkTarget('CamelCase')).toBe('camelcase');- });-- test('trims leading/trailing whitespace', () => {- expect(extractWikilinkTarget(' spaced ')).toBe('spaced');- expect(extractWikilinkTarget(' spaced#anchor')).toBe('spaced');- });-- test('empty inner → empty string', () => {- expect(extractWikilinkTarget('')).toBe('');- });-- test('whitespace-only inner → empty string', () => {- expect(extractWikilinkTarget(' ')).toBe('');- });-- test('only-anchor inner → empty string (no target)', () => {- expect(extractWikilinkTarget('#anchor-only')).toBe('');- });-- test('only-alias inner → empty string', () => {- expect(extractWikilinkTarget('|alias-only')).toBe('');- });-- test('preserves internal whitespace in the target', () => {- expect(extractWikilinkTarget('Some Page')).toBe('some page');- expect(extractWikilinkTarget('Some Page#heading')).toBe('some page');- });-});-describe('wikiLinkSourceClass', () => {test('validation.links off suppresses the broken wikilink decoration', () => {- const targets = new Set(['known']);+ const targets = buildSourceWikiLinkLookup([{ docName: 'known', title: 'Known' }]);expect(wikiLinkSourceClass('missing', targets)).toBe('cm-wiki-link cm-wiki-link-broken');setLinkValidationVisible(false);expect(wikiLinkSourceClass('missing', targets)).toBe('cm-wiki-link');});-});-describe('end-to-end target matching', () => {- test('valid wikilink resolves — target lookups succeed', () => {- const pageSet = buildPageNameSet([{ docName: 'existing-page', title: 'Existing' }]);- expect(pageSet.has(extractWikilinkTarget('existing-page'))).toBe(true);- expect(pageSet.has(extractWikilinkTarget('EXISTING-PAGE'))).toBe(true);- expect(pageSet.has(extractWikilinkTarget('existing-page#anchor'))).toBe(true);- expect(pageSet.has(extractWikilinkTarget('existing-page|alias'))).toBe(true);- expect(pageSet.has(extractWikilinkTarget('Existing'))).toBe(true);+ test('reuses asset resolution for each lookup and invalidates it with the inventory', () => {+ class CountedAssets extends Set<string> {+ scans = 0;++ override *[Symbol.iterator](): SetIterator<string> {+ this.scans += 1;+ yield* super[Symbol.iterator]();+ }+ }++ const assets = new CountedAssets(['images/Cover.png']);+ const first = {+ pages: new Set<string>(),+ pagesBySlug: new Map<string, string>(),+ assetPaths: assets,+ };+ expect(wikiLinkSourceClass('cover.png', first)).toBe('cm-wiki-link');+ const firstScans = assets.scans;+ expect(firstScans).toBeGreaterThan(0);+ for (let index = 0; index < 200; index += 1)+ expect(wikiLinkSourceClass('cover.png', first)).toBe('cm-wiki-link');+ expect(assets.scans).toBe(firstScans);++ const second = { ...first, assetPaths: new CountedAssets() };+ expect(wikiLinkSourceClass('cover.png', second)).toBe('cm-wiki-link cm-wiki-link-broken');+ });++ test('checks distinct asset links against the inventory index without rescanning assets', () => {+ class CountedAssets extends Set<string> {+ scans = 0;++ override *[Symbol.iterator](): SetIterator<string> {+ this.scans += 1;+ yield* super[Symbol.iterator]();+ }+ }++ const pages = Array.from({ length: 10_000 }, (_, index) => ({+ kind: 'asset',+ docName: `/images/image-${index}.png`,+ title: '',+ }));+ const built = buildSourceWikiLinkLookup(pages);+ const assets = new CountedAssets(built.assetPaths);+ const lookup = { ...built, assetPaths: assets };+ for (let index = 0; index < 200; index += 1) {+ expect(wikiLinkSourceClass(`image-${index}.png`, lookup)).toBe('cm-wiki-link');+ expect(wikiLinkSourceClass(`images/image-${index}.png`, lookup)).toBe('cm-wiki-link');+ }+ expect(assets.scans).toBe(0);+ expect(wikiLinkSourceClass('images/missing.png', lookup)).toBe(+ 'cm-wiki-link cm-wiki-link-broken',+ );});+});- test('broken wikilink → target not in set', () => {- const pageSet = buildPageNameSet([{ docName: 'real', title: 'Real' }]);- expect(pageSet.has(extractWikilinkTarget('ghost'))).toBe(false);- expect(pageSet.has(extractWikilinkTarget('ghost#anchor'))).toBe(false);- });-- test('folder targets are treated as known when a child note exists', () => {- const targetSet = buildKnownWikilinkTargetSet([- { docName: 'reports/index', title: 'Reports' },- { docName: 'reports/q1/summary', title: 'Quarter One Summary' },- ]);-- expect(targetSet.has(extractWikilinkTarget('reports'))).toBe(true);- expect(targetSet.has(extractWikilinkTarget('reports/q1'))).toBe(true);- });-- test('folder rows keep seeding the known-target set: full path AND basename', () => {- const targetSet = buildKnownWikilinkTargetSet([- { kind: 'folder', docName: 'specs/foo', title: 'foo' },- ]);-- expect(targetSet.has(extractWikilinkTarget('specs/foo'))).toBe(true);- expect(targetSet.has(extractWikilinkTarget('foo'))).toBe(true);- });+describe('source decoration target extraction', () => {+ const pages = [+ { docName: 'SomePage', title: 'Some Page' },+ { docName: 'reports/index', title: 'Reports' },+ { docName: 'reports/q1/summary', title: 'Quarter One Summary' },+ { kind: 'folder', docName: 'specs/foo', title: 'foo' },+ ];+ const lookup = buildSourceWikiLinkLookup(pages);+ const known = buildKnownWikilinkTargetSet(pages);++ test.each([+ 'SomePage',+ 'SOMEPAGE',+ 'SomePage#heading',+ 'SomePage|Alias',+ 'SomePage#heading|Alias',+ 'SomePage|Alias#heading',+ ' SomePage ',+ '',+ ' ',+ '#heading',+ '|Alias',+ 'reports',+ 'reports/q1',+ 'specs/foo',+ ])('%s keeps its resolved or anchor-only decoration', (inner) => {+ expect(wikiLinkSourceClass(inner, lookup, known)).toBe('cm-wiki-link');+ });++ test.each(['Some Page', 'Some Page#heading', 'Quarter One Summary', 'foo'])(+ '%s names only a title, so it stays broken like its click destination',+ (inner) => {+ expect(wikiLinkSourceClass(inner, lookup, known)).toBe('cm-wiki-link cm-wiki-link-broken');+ },+ );++ test.each(['ghost', 'ghost#heading', 'ghost|Alias', 'ghost#heading|Alias'])(+ '%s stays broken after removing its heading and alias',+ (inner) => {+ expect(wikiLinkSourceClass(inner, lookup, known)).toBe('cm-wiki-link cm-wiki-link-broken');+ },+ );+});- test('empty target (bare #anchor in wikilink) matches nothing', () => {- const target = extractWikilinkTarget('#anchor-only');- expect(target).toBe('');- expect(Boolean(target)).toBe(false);+describe('source decoration uses document resolution', () => {+ const lookup = buildSourceWikiLinkLookup([+ { docName: 'notes/beta', title: 'Beta' },+ { docName: 'notes/beta-md', title: 'Other' },+ { docName: 'reports/index', title: 'Reports' },+ { docName: 'fallback-md', title: 'Fallback' },+ { docName: 'dotted.md', title: 'Dotted' },+ ]);++ test.each([+ 'notes/beta.md',+ 'NOTES/BETA.MDX#heading|Alias',+ 'beta.md|Alias',+ 'reports.md',+ 'fallback.md',+ 'dotted.md.md',+ ])('%s is decorated as a resolved link', (target) => {+ expect(wikiLinkSourceClass(target, lookup)).toBe('cm-wiki-link');+ });++ test('one suffix removal leaves a genuinely missing link broken', () => {+ const singlePage = buildSourceWikiLinkLookup([{ docName: 'notes/beta', title: 'Beta' }]);+ expect(wikiLinkSourceClass('notes/beta.md.md', singlePage)).toBe(+ 'cm-wiki-link cm-wiki-link-broken',+ );+ expect(wikiLinkSourceClass('missing.md#heading|Alias', lookup)).toBe(+ 'cm-wiki-link cm-wiki-link-broken',+ );+ });++ test('known folder targets retain their decoration without becoming document identities', () => {+ expect(wikiLinkSourceClass('notes', lookup, new Set(['notes']))).toBe('cm-wiki-link');});});diff --git a/packages/app/src/editor/plugins/wiki-link-source.ts b/packages/app/src/editor/plugins/wiki-link-source.tsindex dbac4e529..f04dfc2e7 100644--- a/packages/app/src/editor/plugins/wiki-link-source.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.ts@@ -11,8 +11,11 @@ import {import {buildPagesByBasenameIndex,buildPagesBySlugIndex,+ buildWikiLinkAssetTargetKeys,type HeadingEntry,+ isResolvedWikiLinkTarget,resolveWikiLinkTarget,+ resolveWikiLinkTargetDocName,type WikiLinkLookupIndex,} from '@inkeep/open-knowledge-core';import { openExternalUrl } from '@/lib/external-link';@@ -39,6 +42,7 @@ let pagesCache: PageItem[] | null = null;let pagesCacheTime = 0;let knownTargetSet: Set<string> | null = null;let wikiLinkLookup: WikiLinkLookupIndex | null = null;+const resolvedSourceTargets = new WeakMap<WikiLinkLookupIndex, Map<string, boolean>>();const EMPTY_WIKI_LINK_LOOKUP: WikiLinkLookupIndex = {pages: new Set(),@@ -92,25 +96,11 @@ const wikiLinkBrokenMark = Decoration.mark({class: 'cm-wiki-link cm-wiki-link-broken',});-export function buildPageNameSet(pages: PageItem[]): Set<string> {- const s = new Set<string>();- for (const p of pages) {- s.add(p.docName.toLowerCase());- if (p.title) s.add(p.title.toLowerCase());- if (p.kind === 'asset') {- const path = p.docName.replace(/^\//, '');- s.add(path.toLowerCase());- const slash = path.lastIndexOf('/');- s.add((slash === -1 ? path : path.slice(slash + 1)).toLowerCase());- }- }- return s;-}-export function buildKnownWikilinkTargetSet(pages: PageItem[]): Set<string> {- const s = buildPageNameSet(pages);+ const s = new Set<string>();for (const page of pages) {if (page.kind === 'asset') continue;+ if (page.kind === 'folder') s.add(page.docName.toLowerCase());const segments = page.docName.split('/');segments.pop();let folderPath = '';@@ -132,6 +122,7 @@ export function buildSourceWikiLinkLookup(pages: PageItem[]): WikiLinkLookupIndereturn {pages: docNames,assetPaths,+ assetTargetKeys: buildWikiLinkAssetTargetKeys(assetPaths),pagesBySlug: buildPagesBySlugIndex(docNames, toWikiLinkSlug),pagesByBasename: buildPagesByBasenameIndex(docNames, toWikiLinkSlug),};@@ -155,17 +146,31 @@ export function resolveSourceWikiLinkDestination(classified.url.replace(/^\//, '');return { kind: 'hash', href: hashFromAssetPath(assetPath) };}- return { kind: 'hash', href: hashFromDocName(classified.docName, classified.anchor) };-}--export function extractWikilinkTarget(inner: string): string {- return inner.split(/[#|]/)[0].trim().toLowerCase();+ const docName = resolveWikiLinkTargetDocName(classified.docName, lookup) ?? classified.docName;+ return { kind: 'hash', href: hashFromDocName(docName, classified.anchor) };}-export function wikiLinkSourceClass(inner: string, targetSet: ReadonlySet<string> | null): string {- if (targetSet === null) return 'cm-wiki-link';- const target = extractWikilinkTarget(inner);- return target && !targetSet.has(target) && isLinkValidationVisible()+export function wikiLinkSourceClass(+ inner: string,+ lookup: WikiLinkLookupIndex | null,+ knownTargets?: ReadonlySet<string> | null,+): string {+ if (lookup === null) return 'cm-wiki-link';+ const target = inner.split(/[#|]/)[0].trim();+ let resolved = resolvedSourceTargets.get(lookup);+ if (!resolved) {+ resolved = new Map();+ resolvedSourceTargets.set(lookup, resolved);+ }+ let targetResolved = resolved.get(target);+ if (target && targetResolved === undefined) {+ targetResolved = isResolvedWikiLinkTarget(target, lookup);+ resolved.set(target, targetResolved);+ }+ return target &&+ !targetResolved &&+ !knownTargets?.has(target.toLowerCase()) &&+ isLinkValidationVisible()? 'cm-wiki-link cm-wiki-link-broken': 'cm-wiki-link';}@@ -179,7 +184,7 @@ function buildDecorations(view: EditorView): DecorationSet {WIKI_LINK_RE.lastIndex = 0;let m = WIKI_LINK_RE.exec(text);while (m !== null) {- const className = wikiLinkSourceClass(m[0].slice(2, -2), targetSet);+ const className = wikiLinkSourceClass(m[0].slice(2, -2), wikiLinkLookup, targetSet);const mark = className.includes('cm-wiki-link-broken') ? wikiLinkBrokenMark : wikiLinkMark;builder.add(from + m.index, from + m.index + m[0].length, mark);m = WIKI_LINK_RE.exec(text);diff --git a/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx b/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsxindex 0d20e0b13..a83e18236 100644--- a/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx+++ b/packages/app/src/hooks/use-conflict-composer-prefill.dom.test.tsx@@ -7,6 +7,17 @@ let conflictsState: {conflicts: [],};vi.doMock('@/hooks/use-conflicts', () => ({ useConflicts: () => conflictsState }));+vi.doMock('@/lib/conflict-resolve-draft', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/conflict-resolve-draft')>();+ const { i18n } = await import('@lingui/core');+ return {+ ...actual,+ buildResolveDraft: (filePath: string) =>+ i18n.locale === 'hi'+ ? `hi: ${actual.buildResolveDraft(filePath)}`+ : actual.buildResolveDraft(filePath),+ };+});const { useConflictComposerPrefill } = await import('./use-conflict-composer-prefill');@@ -47,12 +58,13 @@ beforeEach(() => {afterEach(() => vi.clearAllMocks());describe('useConflictComposerPrefill', () => {- test('seeds the resolve instruction for a conflicted doc', () => {+ test('seeds guidance without asking the agent to apply a conflict resolution', () => {conflictsState = { conflicts: [ENTRY] };const input = makeInput();renderHook(() => useConflictComposerPrefill('notes/roadmap', { current: input }));- expect(input.read()).toBe('Resolve all the merge conflicts in notes/roadmap.md.');+ expect(input.read()).toContain('Help me understand the conflict in notes/roadmap.md.');+ expect(input.read()).toContain('I will choose and apply the resolution there.');});test('leaves an unconflicted doc alone', () => {@@ -124,7 +136,8 @@ describe('useConflictComposerPrefill', () => {conflictsState = { conflicts: [ENTRY, DOC2] };const input = makeInput('Resolve all the merge conflicts in notes/roadmap.md.');renderHook(() => useConflictComposerPrefill('notes/doc2', { current: input }));- expect(input.read()).toBe('Resolve all the merge conflicts in notes/doc2.md.');+ expect(input.read()).toContain('notes/doc2.md');+ expect(input.read()).toContain('I will choose and apply the resolution there.');});test('a restored draft the user actually wrote is left alone', () => {@@ -164,4 +177,34 @@ describe('useConflictComposerPrefill', () => {rerender({ doc: 'notes/roadmap' });expect(input.read()).toContain('Keep my Region 2.');});++ test('recognises a restored seed once the locale it was written in activates', async () => {+ const { i18n } = await import('@lingui/core');+ const { buildResolveDraft } = await vi.importActual<+ typeof import('@/lib/conflict-resolve-draft')+ >('@/lib/conflict-resolve-draft');+ const previous = i18n.locale;+ const restored = `hi: ${buildResolveDraft('notes/roadmap.md')}`;+ conflictsState = { conflicts: [ENTRY] };+ const input = makeInput(restored);+ const inputRef = { current: input };+ try {+ act(() => i18n.loadAndActivate({ locale: 'en', messages: {} }));+ const { result, rerender } = renderHook(() =>+ useConflictComposerPrefill('notes/roadmap', inputRef),+ );+ expect(result.current.isSeedIntact).toBe(false);+ expect(input.read()).toBe(restored);++ act(() => i18n.loadAndActivate({ locale: 'hi', messages: {} }));+ rerender();+ expect(result.current.isSeedIntact).toBe(true);++ conflictsState = { conflicts: [] };+ rerender();+ expect(input.read()).toBe('');+ } finally {+ act(() => i18n.loadAndActivate({ locale: previous || 'en', messages: {} }));+ }+ });});diff --git a/packages/app/src/hooks/use-conflict-composer-prefill.ts b/packages/app/src/hooks/use-conflict-composer-prefill.tsindex 6031990a1..ca19eccef 100644--- a/packages/app/src/hooks/use-conflict-composer-prefill.ts+++ b/packages/app/src/hooks/use-conflict-composer-prefill.ts@@ -1,6 +1,7 @@+import { useLingui } from '@lingui/react/macro';import { type RefObject, useEffect, useRef, useState } from 'react';import { useConflicts } from '@/hooks/use-conflicts';-import { buildResolveDraft } from '@/lib/conflict-resolve-draft';+import { buildResolveDraft, isLegacyResolveDraft } from '@/lib/conflict-resolve-draft';interface PrefillTarget {getContent: () => { instruction: string; mentions: string[] };@@ -16,7 +17,9 @@ interface PrefillState {function isSeedText(text: string, conflictFilesKey: string, lastSeed: string | null): boolean {if (text === '') return false;if (text === lastSeed) return true;- return conflictFilesKey.split('\u0000').some((file) => buildResolveDraft(file) === text);+ return conflictFilesKey+ .split('\u0000')+ .some((file) => buildResolveDraft(file) === text || isLegacyResolveDraft(text, file));}export function useConflictComposerPrefill(@@ -24,6 +27,7 @@ export function useConflictComposerPrefill(inputRef: RefObject<PrefillTarget | null>,): PrefillState {const { conflicts } = useConflicts();+ const { i18n } = useLingui();const conflictFile =docName === null ? undefined : conflicts.find((entry) => entry.docName === docName)?.file;@@ -35,6 +39,7 @@ export function useConflictComposerPrefill(const [isSeedIntact, setIsSeedIntact] = useState(false);const lastSeedRef = useRef<string | null>(null);+ // biome-ignore lint/correctness/useExhaustiveDependencies: i18n.locale re-runs recognition after activation because buildResolveDraft reads the active locale.useEffect(() => {const input = inputRef.current;if (input === null) return;@@ -60,7 +65,7 @@ export function useConflictComposerPrefill(input.setText(draft);lastSeedRef.current = draft;setIsSeedIntact(true);- }, [conflictFile, conflictFilesKey, inputRef]);+ }, [conflictFile, conflictFilesKey, inputRef, i18n.locale]);return {isSeedIntact,diff --git a/packages/app/src/lib/acp/tool-call-display.test.ts b/packages/app/src/lib/acp/tool-call-display.test.tsindex 785c9a5b1..d40168268 100644--- a/packages/app/src/lib/acp/tool-call-display.test.ts+++ b/packages/app/src/lib/acp/tool-call-display.test.ts@@ -181,16 +181,6 @@ describe('describeToolCall — Open Knowledge MCP tools', () => {).toEqual({ glyph: 'install', text: 'OpenKnowledge installed trip-log' });});- test('resolve_conflict names its target with a bare `file` string', () => {- expect(- describeToolCall({- title: 'mcp__open-knowledge__resolve_conflict',- toolKind: 'other',- rawInput: { file: 'notes/sso.md', strategy: 'mine' },- }),- ).toEqual({ glyph: 'edit', text: 'OpenKnowledge resolved a conflict in notes/sso' });- });-test('template and asset writes name what they wrote', () => {expect(describeToolCall({diff --git a/packages/app/src/lib/acp/tool-call-display.ts b/packages/app/src/lib/acp/tool-call-display.tsindex 6b7da39e5..ef4b16448 100644--- a/packages/app/src/lib/acp/tool-call-display.ts+++ b/packages/app/src/lib/acp/tool-call-display.ts@@ -236,16 +236,6 @@ function openKnowledgeDisplay(tool: string, args: Record<string, unknown>): Tool};case 'checkpoint':return { glyph: 'history', text: t`OpenKnowledge saved a checkpoint` };- case 'conflicts':- return { glyph: 'check', text: t`OpenKnowledge checked for conflicts` };- case 'resolve_conflict':- return {- glyph: 'edit',- text:- subject === null- ? t`OpenKnowledge resolved a conflict`- : t`OpenKnowledge resolved a conflict in ${subject}`,- };case 'restore_version':return {glyph: 'restore',@@ -334,10 +324,6 @@ function openKnowledgePurpose(tool: string): string | null {return t`Saves a restore point for every document in the project`;case 'restore_version':return t`Restores a document or skill to an earlier version`;- case 'conflicts':- return t`Reads unresolved conflicts between edits`;- case 'resolve_conflict':- return t`Resolves a conflict by choosing which content to keep`;default:return null;}diff --git a/packages/app/src/lib/conflict-resolve-draft.ts b/packages/app/src/lib/conflict-resolve-draft.tsindex 9c6ba1332..dbd189ea7 100644--- a/packages/app/src/lib/conflict-resolve-draft.ts+++ b/packages/app/src/lib/conflict-resolve-draft.ts@@ -1,3 +1,9 @@+import { t } from '@lingui/core/macro';+export function buildResolveDraft(filePath: string): string {- return `Resolve all the merge conflicts in ${filePath}.`;+ return t`Help me understand the conflict in ${filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there.`;+}++export function isLegacyResolveDraft(text: string, filePath: string): boolean {+ return text === `Resolve all the merge conflicts in ${filePath}.`;}diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex a1fd8a076..ee802c05e 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -1138,7 +1138,6 @@"AddR83": ["تعذّر إنشاء المشروع. أعد المحاولة أو اختر موقعًا مختلفًا."],"AdjDox": ["مسودة"],"AeHuzT": ["# نمط واحد في كل سطر.\n# أمثلة:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["حلّ OpenKnowledge تعارضًا في ", ["subject"]],"AeORtB": ["تم التحديد: ",["innermostLabel"],@@ -1250,7 +1249,6 @@"BgV29F": ["حقل بحث المحرر المرئي مركَّز عليه"],"Bgaa_U": ["فشل تحديث إعداد الأداء — ", ["detail"]],"BhLPRk": ["تم التراجع بـ «", ["name"], "» إلى النسخة المثبتة"],- "BhMWIs": ["يقرأ التعارضات غير المحلولة بين التعديلات"],"BiVBP9": ["تعذّر قراءة لغات التدقيق الإملائي."],"BjitBo": ["تنزيل ", ["0"]],"BkGtRl": [@@ -2668,6 +2666,11 @@"Pw5PTU": ["الأصل الخارجي"],"PxZCNM": ["خارج نطاق ما يودعه Open Knowledge."],"Q-DKvr": ["التثبيت من ", ["source"]],+ "Q-a_4h": [+ "ساعدني في فهم التعارض في ",+ ["filePath"],+ ". اشرح ما الذي ينبغي أن أقارنه في عرض التعارضات في OpenKnowledge؛ سأختار الحل وأطبقه هناك."+ ],"Q1mtyd": ["إخفاء الشريط الجانبي"],"Q5fqMz": ["خطأ في الاتصال — أعد المحاولة"],"Q6hhn8": ["التفضيلات"],@@ -3757,7 +3760,6 @@"نسخة للقراءة فقط من كتلة MirrorSource في مستند آخر. حرّرها عند المصدر فتتحدث مباشرةً."],"_XWY2J": ["الطرفية معطّلة"],- "_YWqV2": ["حلّ OpenKnowledge تعارضًا"],"_ayOfA": ["قاعدة معرفة تتبع تنسيق Google Open Knowledge، وهو طريقة مشتركة لتنظيم ما تعرفه. اختر هذا إن أردت أن تعمل ملاحظاتك جيدًا مع أدوات أخرى تفهم التنسيق."],@@ -4764,7 +4766,6 @@"i3f2kh": ["لا توجد أوامر مطابقة."],"i6o7XB": ["البحث عن اللغات"],"i92eAT": ["سننشئ مستودعًا ونبدأ المزامنة — بلا حاجة إلى طرفية."],- "i94lQe": ["تحقق OpenKnowledge من التعارضات"],"i9OyGp": ["تراجع أو إعادة"],"i9TPUi": ["هذا ", ["targetNoun"], " ليس على الفرع <0>", ["branch"], "</0>. ربما لم يُدفع بعد."],"i9toLO": ["ملف إعداد الوكيل"],@@ -5526,9 +5527,6 @@" لأنه يحتوي على مجلد .git"],"pZAs1T": ["فشل تحميل الروابط الصادرة"],- "pZaMLc": [- "يحتوي هذا الملف على أسطر تبدو كعلامات تعارض، لذا لا يمكن قراءة حدود التعارض بشكل موثوق. قم بحله يدويًا أو باستخدام اسأل الذكاء الاصطناعي."- ],"paCw0z": ["كل ما تحت مجلدات ", ["0"], "/ داخل ", ["1"], "/"],"pajIrl": ["تعذّر إيقاف الطرفية: ", ["0"]],"pbwTg6": ["قبل ", ["seconds"], " ثانية"],@@ -6140,7 +6138,6 @@}]],- "uhYnaD": ["يحل تعارضًا باختيار المحتوى الذي يُحتفظ به"],"uksqrP": ["لم يُعثر على المستودع. ربما أُعيدت تسميته أو حُذف أو نُقل."],"ul1Atu": ["يجري التحويل..."],"um-es7": ["أطلق المحرر مع"],@@ -6484,6 +6481,9 @@"xtJgSe": ["يحزم هذا المصدر عدة مهارات — اختر ما تريد استيراده."],"xvv5gL": ["معاينة لقطة الشاشة"],"xxRpzT": ["تم العثور على Slidev على نظامك."],+ "xxxG_a": [+ "يحتوي هذا الملف على أسطر تبدو كعلامات تعارض، لذلك لا يمكن تحديد حدود التعارضات على نحو موثوق. عالج العلامات في الملف يدويًا."+ ],"xzAmL_": ["موافق عليه تلقائيًا"],"xzktOa": ["تحرير رابط الويكي"],"y-LQPF": ["تعذّر حل الصورة ", ["identity"], ". انتقل إلى المرجع."],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 9159f5465..cf1a2e938 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -7107,6 +7107,10 @@ msgstr "مرحبًا بالعالم!"msgid "Help"msgstr "مساعدة"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "ساعدني في فهم التعارض في {filePath}. اشرح ما الذي ينبغي أن أقارنه في عرض التعارضات في OpenKnowledge؛ سأختار الحل وأطبقه هناك."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "تحقق OpenKnowledge من {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "تحقق OpenKnowledge من التعارضات"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "تحقق OpenKnowledge من المشروع"@@ -10559,14 +10559,6 @@ msgstr "قرأ OpenKnowledge إعدادات المشروع"msgid "OpenKnowledge read the setting {key}"msgstr "قرأ OpenKnowledge الإعداد {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "حلّ OpenKnowledge تعارضًا"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "حلّ OpenKnowledge تعارضًا في {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "استعاد OpenKnowledge نسخة سابقة"@@ -11545,10 +11537,6 @@ msgstr "يقرأ سجل إصدارات مستند أو مهارة، أو نشاmsgid "Reads this project's OpenKnowledge settings"msgstr "يقرأ إعدادات OpenKnowledge لهذا المشروع"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "يقرأ التعارضات غير المحلولة بين التعديلات"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "جاهز"@@ -12209,10 +12197,6 @@ msgstr "احسم التعارض في {files} و{overflow} ملفات أخرى قmsgid "Resolved"msgstr "محلول"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "يحل تعارضًا باختيار المحتوى الذي يُحتفظ به"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "يجري تحديد الموقع الافتراضي"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "لا يمكن فتح هذا الملف في محرر النصوص."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "يحتوي هذا الملف على أسطر تبدو كعلامات تعارض، لذا لا يمكن قراءة حدود التعارض بشكل موثوق. قم بحله يدويًا أو باستخدام اسأل الذكاء الاصطناعي."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "يحتوي هذا الملف على أسطر تبدو كعلامات تعارض، لذلك لا يمكن تحديد حدود التعارضات على نحو موثوق. عالج العلامات في الملف يدويًا."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex d5793e170..cb963f794 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -956,7 +956,6 @@"AddR83": ["প্রকল্প তৈরি করা যায়নি। আবার চেষ্টা করুন বা অন্য জায়গা বাছুন।"],"AdjDox": ["খসড়া"],"AeHuzT": ["# প্রতি লাইনে একটি প্যাটার্ন।\\n# উদাহরণ:\\n# drafts/\\n# *.draft.md\\n# !keep.md"],- "AeLo3p": ["OpenKnowledge ", ["subject"], " এ একটি দ্বন্দ্ব সমাধান করেছে"],"AeORtB": ["নির্বাচিত: ",["innermostLabel"],@@ -1045,7 +1044,6 @@"BgV29F": ["দৃশ্য সম্পাদকের খোঁজার ইনপুট ফোকাসে"],"Bgaa_U": ["পারফরম্যান্স সেটিং হালনাগাদ করতে ব্যর্থ — ", ["detail"]],"BhLPRk": ["\"", ["name"], "\"-কে ইনস্টল করা সংস্করণে ফিরিয়ে নেওয়া হয়েছে"],- "BhMWIs": ["সম্পাদনার মধ্যে অমীমাংসিত দ্বন্দ্ব পড়ে"],"BiVBP9": ["বানান পরীক্ষার ভাষা পড়া যায়নি।"],"BjitBo": [["0"], " ডাউনলোড করুন"],"BkGtRl": [@@ -2267,6 +2265,10 @@"Pw5PTU": ["বাহ্যিক অরিজিন"],"PxZCNM": ["Open Knowledge যা কমিট করে তার বাইরে।"],"Q-DKvr": [["source"], " থেকে ইনস্টল করুন"],+ "Q-a_4h": [+ ["filePath"],+ "-এর কনফ্লিক্টটি বুঝতে আমাকে সাহায্য করুন। OpenKnowledge-এর কনফ্লিক্ট দৃশ্যে কী তুলনা করা উচিত তা ব্যাখ্যা করুন; আমি সেখানেই সমাধান বেছে নিয়ে প্রয়োগ করব।"+ ],"Q1mtyd": ["সাইডবার লুকান"],"Q5fqMz": ["সংযোগ ত্রুটি — আবার চেষ্টা করুন"],"Q6hhn8": ["পছন্দ"],@@ -3177,7 +3179,6 @@"অন্য নথির একটি MirrorSource ব্লকের শুধু-পড়ার অনুলিপি। উৎসে সম্পাদনা করুন, এটি সঙ্গে সঙ্গে হালনাগাদ হয়।"],"_XWY2J": ["টার্মিনাল নিষ্ক্রিয়"],- "_YWqV2": ["OpenKnowledge একটি দ্বন্দ্ব সমাধান করেছে"],"_ayOfA": ["এমন একটি জ্ঞানভাণ্ডার যা Google-এর Open Knowledge Format মেনে চলে, অর্থাৎ আপনি যা জানেন তা গুছিয়ে রাখার একটি সাধারণ উপায়। আপনার নোট যদি এই ফরম্যাট বোঝে এমন অন্য টুলের সঙ্গেও ভালো কাজ করুক চান, তবে এটি বাছুন।"],@@ -3994,7 +3995,6 @@"i3f2kh": ["মিলে যাওয়া কোনো কমান্ড নেই।"],"i6o7XB": ["ভাষা খুঁজুন"],"i92eAT": ["আমরা একটি রিপোজিটরি তৈরি করে সিঙ্ক শুরু করব — কোনো টার্মিনাল লাগবে না।"],- "i94lQe": ["OpenKnowledge দ্বন্দ্ব পরীক্ষা করেছে"],"i9OyGp": ["পূর্বাবস্থা বা পুনরায়"],"i9TPUi": ["এই ",@@ -4682,9 +4682,6 @@"-এর উপরের ফোল্ডারটি খোলা হয়েছে, কারণ সেখানে একটি .git ফোল্ডার আছে"],"pZAs1T": ["বহির্গামী লিংক লোড করতে ব্যর্থ"],- "pZaMLc": [- "এই ফাইলে এমন লাইন রয়েছে যা কনফ্লিক্ট মার্কারের মতো দেখায়, তাই কনফ্লিক্টের সীমা নির্ভরযোগ্যভাবে পড়া যাচ্ছে না। এটি নিজে সমাধান করুন বা AI-কে জিজ্ঞেস করুন ব্যবহার করুন।"- ],"paCw0z": [["1"], "/-এর ভেতরের ", ["0"], "/ ফোল্ডারগুলোর নিচের সবকিছু"],"pajIrl": ["টার্মিনাল বন্ধ করা যায়নি: ", ["0"]],"pbwTg6": [["seconds"], " সেকেন্ড আগে"],@@ -5189,7 +5186,6 @@{ "one": ["আরও ", "#", " অংশগ্রহণকারী"], "other": ["আরও ", "#", " অংশগ্রহণকারী"] }]],- "uhYnaD": ["কোন বিষয়বস্তু রাখা হবে তা বেছে দ্বন্দ্ব মেটায়"],"uksqrP": ["রিপোজিটরি পাওয়া যায়নি। হয়তো এর নাম বদলানো হয়েছে, মুছে ফেলা হয়েছে, বা সরানো হয়েছে।"],"ul1Atu": ["রূপান্তর করা হচ্ছে…"],"um-es7": ["সম্পাদকটি পাঠান একটি"],@@ -5459,6 +5455,9 @@"xtJgSe": ["এই উৎসে কয়েকটি স্কিল আছে — আমদানি করার জন্য একটি বাছুন।"],"xvv5gL": ["স্ক্রিনশট প্রিভিউ"],"xxRpzT": ["আপনার সিস্টেমে Slidev পাওয়া গেছে।"],+ "xxxG_a": [+ "এই ফাইলে এমন কিছু লাইন আছে যা কনফ্লিক্ট মার্কারের মতো দেখায়, তাই কনফ্লিক্টের সীমা নির্ভরযোগ্যভাবে বোঝা যাচ্ছে না। ফাইলের মার্কারগুলো হাতে সমাধান করুন।"+ ],"xzAmL_": ["স্বয়ংক্রিয়ভাবে অনুমোদিত"],"xzktOa": ["উইকি লিংক সম্পাদনা করুন"],"y-LQPF": ["সমাধান করা যায় না এমন ছবি ", ["identity"], "। রেফারেন্সে যান।"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex f4e5e8f4a..dba9cdd98 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -7103,6 +7103,10 @@ msgstr "ওহে, বিশ্ব!"msgid "Help"msgstr "সহায়তা"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "{filePath}-এর কনফ্লিক্টটি বুঝতে আমাকে সাহায্য করুন। OpenKnowledge-এর কনফ্লিক্ট দৃশ্যে কী তুলনা করা উচিত তা ব্যাখ্যা করুন; আমি সেখানেই সমাধান বেছে নিয়ে প্রয়োগ করব।"+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10370,10 +10374,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge {subject} পরীক্ষা করেছে"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge দ্বন্দ্ব পরীক্ষা করেছে"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge প্রকল্প পরীক্ষা করেছে"@@ -10555,14 +10555,6 @@ msgstr "OpenKnowledge প্রকল্পের সেটিংস পড়msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge {key} সেটিংটি পড়েছে"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge একটি দ্বন্দ্ব সমাধান করেছে"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge {subject} এ একটি দ্বন্দ্ব সমাধান করেছে"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge একটি পূর্ববর্তী সংস্করণ পুনরুদ্ধার করেছে"@@ -11541,10 +11533,6 @@ msgstr "নথি বা স্কিলের সংস্করণ ইতিmsgid "Reads this project's OpenKnowledge settings"msgstr "এই প্রকল্পের OpenKnowledge সেটিং পড়ে"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "সম্পাদনার মধ্যে অমীমাংসিত দ্বন্দ্ব পড়ে"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "প্রস্তুত"@@ -12205,10 +12193,6 @@ msgstr "মোছার আগে {files} এবং আরও {overflow}টিmsgid "Resolved"msgstr "মীমাংসিত"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "কোন বিষয়বস্তু রাখা হবে তা বেছে দ্বন্দ্ব মেটায়"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "ডিফল্ট জায়গা নির্ধারণ করা হচ্ছে"@@ -15151,8 +15135,8 @@ msgid "This file can't be opened in the text editor."msgstr "এই ফাইলটি টেক্সট সম্পাদকে খোলা যায় না।"#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "এই ফাইলে এমন লাইন রয়েছে যা কনফ্লিক্ট মার্কারের মতো দেখায়, তাই কনফ্লিক্টের সীমা নির্ভরযোগ্যভাবে পড়া যাচ্ছে না। এটি নিজে সমাধান করুন বা AI-কে জিজ্ঞেস করুন ব্যবহার করুন।"+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "এই ফাইলে এমন কিছু লাইন আছে যা কনফ্লিক্ট মার্কারের মতো দেখায়, তাই কনফ্লিক্টের সীমা নির্ভরযোগ্যভাবে বোঝা যাচ্ছে না। ফাইলের মার্কারগুলো হাতে সমাধান করুন।"#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex f1916fedb..2e2a19e9c 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -985,7 +985,6 @@"AddR83": ["Could not create project. Try again or pick a different location."],"AdjDox": ["Draft"],"AeHuzT": ["# One pattern per line.\n# Examples:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge resolved a conflict in ", ["subject"]],"AeORtB": ["Selected: ",["innermostLabel"],@@ -1083,7 +1082,6 @@"BgV29F": ["Visual editor find input focused"],"Bgaa_U": ["Failed to update performance setting — ", ["detail"]],"BhLPRk": ["Reverted \"", ["name"], "\" to the installed version"],- "BhMWIs": ["Reads unresolved conflicts between edits"],"BiVBP9": ["Couldn't read the spelling languages."],"BjitBo": ["Download ", ["0"]],"BkGtRl": [@@ -2339,6 +2337,11 @@"Pw5PTU": ["External origin"],"PxZCNM": ["Outside what Open Knowledge commits."],"Q-DKvr": ["Install from ", ["source"]],+ "Q-a_4h": [+ "Help me understand the conflict in ",+ ["filePath"],+ ". Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+ ],"Q1mtyd": ["Hide sidebar"],"Q5fqMz": ["Connection error — try again"],"Q6hhn8": ["Preferences"],@@ -3262,7 +3265,6 @@"Read-only copy of a MirrorSource block from another doc. Edit at the source and it updates live."],"_XWY2J": ["Terminal disabled"],- "_YWqV2": ["OpenKnowledge resolved a conflict"],"_ayOfA": ["A knowledge base that follows Google's Open Knowledge Format, a shared way of organizing what you know. Pick this if you want your notes to work well with other tools that understand the format."],@@ -4124,7 +4126,6 @@"i3f2kh": ["No matching commands."],"i6o7XB": ["Search languages"],"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],- "i94lQe": ["OpenKnowledge checked for conflicts"],"i9OyGp": ["Undo or redo"],"i9TPUi": ["This ",@@ -4842,9 +4843,6 @@" because it contains a .git folder"],"pZAs1T": ["Failed to load outgoing links"],- "pZaMLc": [- "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."- ],"paCw0z": ["everything under ", ["0"], "/ folders inside ", ["1"], "/"],"pajIrl": ["Could not turn off the terminal: ", ["0"]],"pbwTg6": [["seconds"], "s ago"],@@ -5378,7 +5376,6 @@{ "one": ["#", " more participant"], "other": ["#", " more participants"] }]],- "uhYnaD": ["Resolves a conflict by choosing which content to keep"],"uksqrP": ["Repository not found. It may have been renamed, deleted, or moved."],"ul1Atu": ["Converting..."],"um-es7": ["Ship the editor with a"],@@ -5661,6 +5658,9 @@"xtJgSe": ["This source bundles several skills — choose the one to import."],"xvv5gL": ["Screenshot preview"],"xxRpzT": ["Slidev found on your system."],+ "xxxG_a": [+ "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+ ],"xzAmL_": ["Auto-approved"],"xzktOa": ["Edit wiki link"],"y-LQPF": ["Unresolvable image ", ["identity"], ". Go to reference."],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex bda1b82ee..211d4ac9d 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -7107,6 +7107,10 @@ msgstr "Hello, world!"msgid "Help"msgstr "Help"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge checked {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge checked for conflicts"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge checked the project"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge read the project settings"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge read the setting {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge resolved a conflict"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge resolved a conflict in {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge restored an earlier version"@@ -11545,10 +11537,6 @@ msgstr "Reads the version history of a document or skill, or a folder's activitymsgid "Reads this project's OpenKnowledge settings"msgstr "Reads this project's OpenKnowledge settings"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "Reads unresolved conflicts between edits"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "Ready"@@ -12209,10 +12197,6 @@ msgstr "Resolve the conflict on {files}, +{overflow} more before deleting."msgid "Resolved"msgstr "Resolved"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "Resolves a conflict by choosing which content to keep"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "Resolving default location"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "This file can't be opened in the text editor."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 5766d4522..c231e7936 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -1152,7 +1152,6 @@"AddR83": ["No se pudo crear el proyecto. Inténtalo de nuevo o elige otra ubicación."],"AdjDox": ["Borrador"],"AeHuzT": ["# Un patrón por línea.\n# Ejemplos:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge resolvió un conflicto en ", ["subject"]],"AeORtB": ["Seleccionado: ",["innermostLabel"],@@ -1264,7 +1263,6 @@"BgV29F": ["Campo de búsqueda del editor visual enfocado"],"Bgaa_U": ["No se pudo actualizar el ajuste de rendimiento — ", ["detail"]],"BhLPRk": ["Se revirtió \"", ["name"], "\" a la versión instalada"],- "BhMWIs": ["Lee los conflictos sin resolver entre ediciones"],"BiVBP9": ["No se pudieron leer los idiomas de la corrección ortográfica."],"BjitBo": ["Descargar ", ["0"]],"BkGtRl": [@@ -2698,6 +2696,11 @@"Pw5PTU": ["Origen externo"],"PxZCNM": ["Fuera de lo que confirma Open Knowledge."],"Q-DKvr": ["Instalar desde ", ["source"]],+ "Q-a_4h": [+ "Ayúdame a entender el conflicto en ",+ ["filePath"],+ ". Explica qué debo comparar en la vista de conflictos de OpenKnowledge; yo elegiré y aplicaré la resolución allí."+ ],"Q1mtyd": ["Ocultar la barra lateral"],"Q5fqMz": ["Error de conexión: inténtalo de nuevo"],"Q6hhn8": ["Preferencias"],@@ -3776,7 +3779,6 @@"Copia de solo lectura de un bloque MirrorSource de otro documento. Edítalo en el origen y se actualiza en vivo."],"_XWY2J": ["Terminal desactivada"],- "_YWqV2": ["OpenKnowledge resolvió un conflicto"],"_ayOfA": ["Una base de conocimiento que sigue el Open Knowledge Format de Google, una forma común de organizar lo que sabes. Elige esto si quieres que tus notas funcionen bien con otras herramientas que entienden el formato."],@@ -4796,7 +4798,6 @@"i3f2kh": ["Ningún comando coincide."],"i6o7XB": ["Buscar idiomas"],"i92eAT": ["Crearemos un repositorio y empezaremos a sincronizar; no hace falta terminal."],- "i94lQe": ["OpenKnowledge buscó conflictos"],"i9OyGp": ["Deshacer o rehacer"],"i9TPUi": ["Este ",@@ -5583,9 +5584,6 @@" porque contiene una carpeta .git"],"pZAs1T": ["No se pudieron cargar los enlaces salientes"],- "pZaMLc": [- "Este archivo contiene líneas que parecen marcadores de conflicto, por lo que los límites del conflicto no se pueden leer de forma fiable. Resuélvelo a mano o con Preguntar a la IA."- ],"paCw0z": ["todo lo que hay en las carpetas ", ["0"], "/ dentro de ", ["1"], "/"],"pajIrl": ["No se pudo desactivar la terminal: ", ["0"]],"pbwTg6": ["hace ", ["seconds"], " s"],@@ -6179,7 +6177,6 @@}]],- "uhYnaD": ["Resuelve un conflicto eligiendo qué contenido conservar"],"uksqrP": ["No se encontró el repositorio. Puede que lo hayan renombrado, eliminado o movido."],"ul1Atu": ["Convirtiendo..."],"um-es7": ["Publica el editor con un"],@@ -6509,6 +6506,9 @@"xtJgSe": ["Este origen incluye varias habilidades: elige cuál importar."],"xvv5gL": ["Vista previa de la captura"],"xxRpzT": ["Slidev encontrado en tu sistema."],+ "xxxG_a": [+ "Este archivo contiene líneas que parecen marcadores de conflicto, por lo que no se pueden identificar con fiabilidad los límites de los conflictos. Resuelve los marcadores del archivo manualmente."+ ],"xzAmL_": ["Aprobado automáticamente"],"xzktOa": ["Editar el enlace wiki"],"y-LQPF": ["No se puede resolver la imagen ", ["identity"], ". Ir a la referencia."],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 678c1cd32..9a1032a0c 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -7107,6 +7107,10 @@ msgstr "¡Hola, mundo!"msgid "Help"msgstr "Ayuda"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "Ayúdame a entender el conflicto en {filePath}. Explica qué debo comparar en la vista de conflictos de OpenKnowledge; yo elegiré y aplicaré la resolución allí."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge revisó {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge buscó conflictos"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge revisó el proyecto"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge leyó la configuración del proyecto"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge leyó la configuración {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge resolvió un conflicto"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge resolvió un conflicto en {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge restauró una versión anterior"@@ -11545,10 +11537,6 @@ msgstr "Lee el historial de versiones de un documento o habilidad, o la actividamsgid "Reads this project's OpenKnowledge settings"msgstr "Lee la configuración de OpenKnowledge de este proyecto"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "Lee los conflictos sin resolver entre ediciones"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "Listo"@@ -12209,10 +12197,6 @@ msgstr "Resuelve el conflicto en {files} y en {overflow} más antes de eliminar.msgid "Resolved"msgstr "Resuelto"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "Resuelve un conflicto eligiendo qué contenido conservar"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "Resolviendo la ubicación por defecto"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "Este archivo no se puede abrir en el editor de texto."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "Este archivo contiene líneas que parecen marcadores de conflicto, por lo que los límites del conflicto no se pueden leer de forma fiable. Resuélvelo a mano o con Preguntar a la IA."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "Este archivo contiene líneas que parecen marcadores de conflicto, por lo que no se pueden identificar con fiabilidad los límites de los conflictos. Resuelve los marcadores del archivo manualmente."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 8786ab415..616b7d63d 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -1181,7 +1181,6 @@"AddR83": ["Impossible de créer le projet. Réessayez ou choisissez un autre emplacement."],"AdjDox": ["Brouillon"],"AeHuzT": ["# Un motif par ligne.\n# Exemples :\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge a résolu un conflit dans ", ["subject"]],"AeORtB": ["Sélection : ",["innermostLabel"],@@ -1293,7 +1292,6 @@"BgV29F": ["Champ de recherche de l'éditeur visuel actif"],"Bgaa_U": ["Échec de la mise à jour du paramètre de performance — ", ["detail"]],"BhLPRk": ["« ", ["name"], " » ramené à la version installée"],- "BhMWIs": ["Lit les conflits non résolus entre modifications"],"BiVBP9": ["Impossible de lire les langues de la correction orthographique."],"BjitBo": ["Télécharger ", ["0"]],"BkGtRl": [@@ -2742,6 +2740,11 @@"Pw5PTU": ["Origine externe"],"PxZCNM": ["En dehors de ce que valide Open Knowledge."],"Q-DKvr": ["Installer depuis ", ["source"]],+ "Q-a_4h": [+ "Aide-moi à comprendre le conflit dans ",+ ["filePath"],+ ". Explique ce que je dois comparer dans la vue des conflits d’OpenKnowledge ; je choisirai et appliquerai la résolution là-bas."+ ],"Q1mtyd": ["Masquer la barre latérale"],"Q5fqMz": ["Erreur de connexion — réessayez"],"Q6hhn8": ["Préférences"],@@ -3827,7 +3830,6 @@"Copie en lecture seule d'un bloc MirrorSource d'un autre document. Modifiez à la source et la copie se met à jour en direct."],"_XWY2J": ["Terminal désactivé"],- "_YWqV2": ["OpenKnowledge a résolu un conflit"],"_ayOfA": ["Une base de connaissances qui suit l'Open Knowledge Format de Google, une manière commune d'organiser ce que vous savez. Choisissez ceci si vous voulez que vos notes fonctionnent bien avec les autres outils qui comprennent ce format."],@@ -4837,7 +4839,6 @@"i92eAT": ["Nous allons créer un dépôt et démarrer la synchronisation — aucun terminal nécessaire."],- "i94lQe": ["OpenKnowledge a recherché des conflits"],"i9OyGp": ["Annuler ou rétablir"],"i9TPUi": ["Ce ",@@ -5630,9 +5631,6 @@" a été ouvert, car il contient un dossier .git"],"pZAs1T": ["Échec du chargement des liens sortants"],- "pZaMLc": [- "Ce fichier contient des lignes qui ressemblent à des marqueurs de conflit, si bien que les limites du conflit ne peuvent pas être lues de façon fiable. Résolvez-le à la main ou avec Demander à l'IA."- ],"paCw0z": ["tout ce qui se trouve sous les dossiers ",["0"],@@ -6251,7 +6249,6 @@}]],- "uhYnaD": ["Résout un conflit en choisissant le contenu à conserver"],"uksqrP": ["Dépôt introuvable. Il a peut-être été renommé, supprimé ou déplacé."],"ul1Atu": ["Conversion…"],"um-es7": ["Livrez l'éditeur avec un"],@@ -6591,6 +6588,9 @@"xtJgSe": ["Cette source regroupe plusieurs compétences — choisissez celle à importer."],"xvv5gL": ["Aperçu de la capture d’écran"],"xxRpzT": ["Slidev trouvé sur votre système."],+ "xxxG_a": [+ "Ce fichier contient des lignes qui ressemblent à des marqueurs de conflit ; les limites des conflits ne peuvent donc pas être déterminées de façon fiable. Résolvez manuellement les marqueurs dans le fichier."+ ],"xzAmL_": ["Approuvé automatiquement"],"xzktOa": ["Modifier le lien wiki"],"y-LQPF": ["Image ", ["identity"], " impossible à résoudre. Accéder à la référence."],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 14cc139a7..46a6a4042 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -7107,6 +7107,10 @@ msgstr "Bonjour, tout le monde !"msgid "Help"msgstr "Aide"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "Aide-moi à comprendre le conflit dans {filePath}. Explique ce que je dois comparer dans la vue des conflits d’OpenKnowledge ; je choisirai et appliquerai la résolution là-bas."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge a vérifié {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge a recherché des conflits"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge a vérifié le projet"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge a lu les paramètres du projet"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge a lu le paramètre {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge a résolu un conflit"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge a résolu un conflit dans {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge a restauré une version antérieure"@@ -11545,10 +11537,6 @@ msgstr "Lit l'historique des versions d'un document ou d'une compétence, ou l'amsgid "Reads this project's OpenKnowledge settings"msgstr "Lit les paramètres OpenKnowledge de ce projet"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "Lit les conflits non résolus entre modifications"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "Prêt"@@ -12209,10 +12197,6 @@ msgstr "Résolvez le conflit sur {files} et {overflow} autres fichiers avant demsgid "Resolved"msgstr "Résolu"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "Résout un conflit en choisissant le contenu à conserver"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "Détermination de l'emplacement par défaut"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "Ce fichier ne peut pas être ouvert dans l'éditeur de texte."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "Ce fichier contient des lignes qui ressemblent à des marqueurs de conflit, si bien que les limites du conflit ne peuvent pas être lues de façon fiable. Résolvez-le à la main ou avec Demander à l'IA."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "Ce fichier contient des lignes qui ressemblent à des marqueurs de conflit ; les limites des conflits ne peuvent donc pas être déterminées de façon fiable. Résolvez manuellement les marqueurs dans le fichier."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 583b0b49b..9ab00e52f 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -960,7 +960,6 @@"AddR83": ["प्रोजेक्ट नहीं बनाया जा सका। फिर कोशिश करें या कोई दूसरा स्थान चुनें।"],"AdjDox": ["ड्राफ़्ट"],"AeHuzT": ["# प्रति पंक्ति एक पैटर्न।\\n# उदाहरण:\\n# drafts/\\n# *.draft.md\\n# !keep.md"],- "AeLo3p": ["OpenKnowledge ने ", ["subject"], " में एक विरोध हल किया"],"AeORtB": ["चुना गया: ",["innermostLabel"],@@ -1052,7 +1051,6 @@"BgV29F": ["दृश्य संपादक का खोज इनपुट फ़ोकस में"],"Bgaa_U": ["प्रदर्शन सेटिंग अपडेट करने में विफल — ", ["detail"]],"BhLPRk": ["\"", ["name"], "\" को इंस्टॉल किए गए संस्करण पर वापस ले लिया गया"],- "BhMWIs": ["संपादनों के बीच अनसुलझे टकराव पढ़ता है"],"BiVBP9": ["वर्तनी जाँच की भाषाएँ नहीं पढ़ी जा सकीं।"],"BjitBo": [["0"], " डाउनलोड करें"],"BkGtRl": [@@ -2270,6 +2268,10 @@"Pw5PTU": ["बाहरी origin"],"PxZCNM": ["Open Knowledge जो कमिट करता है उसके दायरे से बाहर।"],"Q-DKvr": [["source"], " से इंस्टॉल करें"],+ "Q-a_4h": [+ ["filePath"],+ " में हुए कॉन्फ़्लिक्ट को समझने में मेरी मदद करें। बताएं कि OpenKnowledge के कॉन्फ़्लिक्ट दृश्य में मुझे क्या तुलना करनी चाहिए; मैं वहीं समाधान चुनकर लागू करूंगा।"+ ],"Q1mtyd": ["साइडबार छिपाएँ"],"Q5fqMz": ["कनेक्शन त्रुटि — फिर कोशिश करें"],"Q6hhn8": ["वरीयताएँ"],@@ -3168,7 +3170,6 @@"किसी दूसरे दस्तावेज़ के MirrorSource ब्लॉक की केवल-पढ़ने योग्य प्रति। स्रोत पर संपादित करें और यह तुरंत अद्यतित हो जाती है।"],"_XWY2J": ["टर्मिनल अक्षम"],- "_YWqV2": ["OpenKnowledge ने एक विरोध हल किया"],"_ayOfA": ["एक ज्ञान आधार जो Google के Open Knowledge Format का पालन करता है, जो आपकी जानकारी को व्यवस्थित करने का एक साझा तरीका है। इसे चुनें यदि आप चाहते हैं कि आपके नोट उन दूसरे टूल के साथ अच्छी तरह काम करें जो इस फ़ॉर्मेट को समझते हैं।"],@@ -3985,7 +3986,6 @@"i3f2kh": ["कोई मेल खाता कमांड नहीं।"],"i6o7XB": ["भाषाएँ खोजें"],"i92eAT": ["हम एक रिपॉज़िटरी बनाकर सिंक शुरू कर देंगे — किसी टर्मिनल की ज़रूरत नहीं।"],- "i94lQe": ["OpenKnowledge ने विरोधों की जाँच की"],"i9OyGp": ["पूर्ववत या फिर से करें"],"i9TPUi": ["यह ",@@ -4677,9 +4677,6 @@" का मूल फ़ोल्डर खोला गया, क्योंकि उसमें .git फ़ोल्डर है"],"pZAs1T": ["बाहर जाने वाले लिंक लोड करने में विफल"],- "pZaMLc": [- "इस फ़ाइल में ऐसी पंक्तियाँ हैं जो कॉन्फ़्लिक्ट मार्कर जैसी दिखती हैं, इसलिए कॉन्फ़्लिक्ट की सीमाएँ भरोसे से नहीं पढ़ी जा सकतीं। इसे स्वयं हल करें या AI से पूछें का उपयोग करें।"- ],"paCw0z": [["1"], "/ के भीतर मौजूद ", ["0"], "/ फ़ोल्डरों के अंतर्गत सब कुछ"],"pajIrl": ["टर्मिनल बंद नहीं किया जा सका: ", ["0"]],"pbwTg6": [["seconds"], " सेकंड पहले"],@@ -5174,7 +5171,6 @@"uhJEA2": [["count", "plural", { "one": ["#", " और प्रतिभागी"], "other": ["#", " और प्रतिभागी"] }]],- "uhYnaD": ["कौन-सी सामग्री रखनी है यह चुनकर टकराव सुलझाता है"],"uksqrP": ["रिपॉज़िटरी नहीं मिली। शायद इसका नाम बदला गया, इसे हटाया गया, या हिलाया गया।"],"ul1Atu": ["बदला जा रहा है…"],"um-es7": ["संपादक को इसके साथ भेजें"],@@ -5448,6 +5444,9 @@"xtJgSe": ["इस स्रोत में कई स्किल हैं — आयात करने के लिए एक चुनें।"],"xvv5gL": ["स्क्रीनशॉट पूर्वावलोकन"],"xxRpzT": ["आपके सिस्टम पर Slidev मिला।"],+ "xxxG_a": [+ "इस फ़ाइल में ऐसी पंक्तियां हैं जो कॉन्फ़्लिक्ट मार्कर जैसी दिखती हैं, इसलिए कॉन्फ़्लिक्ट की सीमाएं भरोसेमंद ढंग से पहचानी नहीं जा सकतीं। फ़ाइल में मार्करों का समाधान हाथ से करें।"+ ],"xzAmL_": ["स्वत: स्वीकृत"],"xzktOa": ["विकी लिंक संपादित करें"],"y-LQPF": ["हल न की जा सकने वाला चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex c979e909a..6744e4aec 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -7103,6 +7103,10 @@ msgstr "नमस्ते, दुनिया!"msgid "Help"msgstr "सहायता"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "{filePath} में हुए कॉन्फ़्लिक्ट को समझने में मेरी मदद करें। बताएं कि OpenKnowledge के कॉन्फ़्लिक्ट दृश्य में मुझे क्या तुलना करनी चाहिए; मैं वहीं समाधान चुनकर लागू करूंगा।"+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10370,10 +10374,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge ने {subject} की जाँच की"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge ने विरोधों की जाँच की"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge ने प्रोजेक्ट की जाँच की"@@ -10555,14 +10555,6 @@ msgstr "OpenKnowledge ने प्रोजेक्ट सेटिंग्msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge ने सेटिंग {key} पढ़ी"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge ने एक विरोध हल किया"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge ने {subject} में एक विरोध हल किया"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge ने पिछला संस्करण पुनर्स्थापित किया"@@ -11541,10 +11533,6 @@ msgstr "किसी दस्तावेज़ या स्किल काmsgid "Reads this project's OpenKnowledge settings"msgstr "इस प्रोजेक्ट की OpenKnowledge सेटिंग पढ़ता है"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "संपादनों के बीच अनसुलझे टकराव पढ़ता है"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "तैयार"@@ -12205,10 +12193,6 @@ msgstr "हटाने से पहले {files} और {overflow} अन्msgid "Resolved"msgstr "सुलझ गया"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "कौन-सी सामग्री रखनी है यह चुनकर टकराव सुलझाता है"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "डिफ़ॉल्ट स्थान तय किया जा रहा है"@@ -15151,8 +15135,8 @@ msgid "This file can't be opened in the text editor."msgstr "यह फ़ाइल पाठ संपादक में नहीं खोली जा सकती।"#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "इस फ़ाइल में ऐसी पंक्तियाँ हैं जो कॉन्फ़्लिक्ट मार्कर जैसी दिखती हैं, इसलिए कॉन्फ़्लिक्ट की सीमाएँ भरोसे से नहीं पढ़ी जा सकतीं। इसे स्वयं हल करें या AI से पूछें का उपयोग करें।"+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "इस फ़ाइल में ऐसी पंक्तियां हैं जो कॉन्फ़्लिक्ट मार्कर जैसी दिखती हैं, इसलिए कॉन्फ़्लिक्ट की सीमाएं भरोसेमंद ढंग से पहचानी नहीं जा सकतीं। फ़ाइल में मार्करों का समाधान हाथ से करें।"#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex d5c8ebb24..23484d14d 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -991,7 +991,6 @@"AddR83": ["Proyek tidak dapat dibuat. Coba lagi atau pilih lokasi lain."],"AdjDox": ["Draf"],"AeHuzT": ["# Satu pola per baris.\\n# Contoh:\\n# drafts/\\n# *.draft.md\\n# !keep.md"],- "AeLo3p": ["OpenKnowledge menyelesaikan konflik di ", ["subject"]],"AeORtB": ["Dipilih: ",["innermostLabel"],@@ -1077,7 +1076,6 @@"BgV29F": ["Bidang pencarian penyunting visual sedang difokus"],"Bgaa_U": ["Gagal memperbarui pengaturan performa — ", ["detail"]],"BhLPRk": ["\"", ["name"], "\" dikembalikan ke versi yang terpasang"],- "BhMWIs": ["Membaca konflik yang belum terselesaikan antar suntingan"],"BiVBP9": ["Tidak dapat membaca bahasa pemeriksaan ejaan."],"BjitBo": ["Unduh ", ["0"]],"BkGtRl": [@@ -2351,6 +2349,11 @@"Pw5PTU": ["Origin eksternal"],"PxZCNM": ["Di luar cakupan commit Open Knowledge."],"Q-DKvr": ["Pasang dari ", ["source"]],+ "Q-a_4h": [+ "Bantu saya memahami konflik dalam ",+ ["filePath"],+ ". Jelaskan apa yang perlu saya bandingkan di tampilan konflik OpenKnowledge; saya akan memilih dan menerapkan penyelesaiannya di sana."+ ],"Q1mtyd": ["Sembunyikan bilah sisi"],"Q5fqMz": ["Galat koneksi — coba lagi"],"Q6hhn8": ["Preferensi"],@@ -3275,7 +3278,6 @@"Salinan hanya-baca dari blok MirrorSource di dokumen lain. Sunting di sumbernya dan salinan ini diperbarui langsung."],"_XWY2J": ["Terminal dinonaktifkan"],- "_YWqV2": ["OpenKnowledge menyelesaikan sebuah konflik"],"_ayOfA": ["Basis pengetahuan yang mengikuti Open Knowledge Format dari Google, cara bersama untuk menata apa yang Anda tahu. Pilih ini jika Anda ingin catatan Anda bekerja baik dengan alat lain yang memahami format tersebut."],@@ -4135,7 +4137,6 @@"i92eAT": ["Kami akan membuat sebuah repositori dan mulai menyinkronkan — tanpa perlu terminal."],- "i94lQe": ["OpenKnowledge memeriksa konflik"],"i9OyGp": ["Batalkan atau ulangi"],"i9TPUi": [["targetNoun"],@@ -4860,9 +4861,6 @@" dibuka karena berisi folder .git"],"pZAs1T": ["Gagal memuat tautan keluar"],- "pZaMLc": [- "File ini berisi baris yang menyerupai penanda konflik, sehingga batas konflik tidak dapat dibaca dengan andal. Selesaikan secara manual atau dengan Tanya AI."- ],"paCw0z": ["semua yang ada di folder ", ["0"], "/ di dalam ", ["1"], "/"],"pajIrl": ["Terminal tidak dapat dimatikan: ", ["0"]],"pbwTg6": [["seconds"], " dtk lalu"],@@ -5379,7 +5377,6 @@],"ugoTXs": ["folder"],"uhJEA2": [["count", "plural", { "other": ["#", " peserta lagi"] }]],- "uhYnaD": ["Menyelesaikan konflik dengan memilih isi yang dipertahankan"],"uksqrP": ["Repositori tidak ditemukan. Mungkin ia sudah diganti nama, dihapus, atau dipindahkan."],@@ -5661,6 +5658,9 @@"xtJgSe": ["Sumber ini memuat beberapa keterampilan — pilih yang akan diimpor."],"xvv5gL": ["Pratinjau tangkapan layar"],"xxRpzT": ["Slidev ditemukan di sistem Anda."],+ "xxxG_a": [+ "File ini berisi baris yang tampak seperti penanda konflik, sehingga batas konfliknya tidak dapat dibaca dengan andal. Selesaikan penanda di file secara manual."+ ],"xzAmL_": ["Disetujui otomatis"],"xzktOa": ["Sunting tautan wiki"],"y-LQPF": ["Gambar ", ["identity"], " tidak dapat ditentukan. Buka referensi."],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex ba128b408..003124804 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -7103,6 +7103,10 @@ msgstr "Halo, dunia!"msgid "Help"msgstr "Bantuan"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "Bantu saya memahami konflik dalam {filePath}. Jelaskan apa yang perlu saya bandingkan di tampilan konflik OpenKnowledge; saya akan memilih dan menerapkan penyelesaiannya di sana."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10370,10 +10374,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge memeriksa {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge memeriksa konflik"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge memeriksa proyek"@@ -10555,14 +10555,6 @@ msgstr "OpenKnowledge membaca pengaturan proyek"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge membaca pengaturan {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge menyelesaikan sebuah konflik"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge menyelesaikan konflik di {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge memulihkan versi sebelumnya"@@ -11541,10 +11533,6 @@ msgstr "Membaca riwayat versi dokumen atau keterampilan, atau aktivitas folder"msgid "Reads this project's OpenKnowledge settings"msgstr "Membaca pengaturan OpenKnowledge proyek ini"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "Membaca konflik yang belum terselesaikan antar suntingan"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "Siap"@@ -12205,10 +12193,6 @@ msgstr "Selesaikan konflik pada {files} dan {overflow} berkas lainnya sebelum memsgid "Resolved"msgstr "Selesai"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "Menyelesaikan konflik dengan memilih isi yang dipertahankan"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "Menentukan lokasi bawaan"@@ -15151,8 +15135,8 @@ msgid "This file can't be opened in the text editor."msgstr "Berkas ini tidak bisa dibuka di penyunting teks."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "File ini berisi baris yang menyerupai penanda konflik, sehingga batas konflik tidak dapat dibaca dengan andal. Selesaikan secara manual atau dengan Tanya AI."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "File ini berisi baris yang tampak seperti penanda konflik, sehingga batas konfliknya tidak dapat dibaca dengan andal. Selesaikan penanda di file secara manual."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 65df31ba0..f9405d942 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -960,7 +960,6 @@"AeHuzT": ["# 줄마다 패턴 하나를 작성합니다.\n# 예시:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge에서 ", ["subject"], " 충돌 해결"],"AeORtB": ["선택됨: ",["innermostLabel"],@@ -1045,7 +1044,6 @@"BgV29F": ["비주얼 편집기 찾기 입력 필드에 포커스가 있습니다."],"Bgaa_U": ["성능 설정을 업데이트하지 못했습니다: ", ["detail"]],"BhLPRk": ["\"", ["name"], "\"을 설치된 버전으로 되돌렸습니다"],- "BhMWIs": ["편집 간의 미해결 충돌을 읽습니다"],"BiVBP9": ["맞춤법 검사 언어를 읽지 못했습니다."],"BjitBo": [["0"], " 다운로드"],"BkGtRl": [@@ -2259,6 +2257,10 @@"Pw5PTU": ["외부 오리진"],"PxZCNM": ["Open Knowledge가 커밋하는 범위 밖입니다."],"Q-DKvr": [["source"], "에서 설치"],+ "Q-a_4h": [+ ["filePath"],+ "의 충돌을 이해할 수 있도록 도와주세요. OpenKnowledge 충돌 보기에서 무엇을 비교해야 하는지 설명해 주세요. 해결 방법은 제가 그곳에서 선택하고 적용하겠습니다."+ ],"Q1mtyd": ["사이드바 가리기"],"Q5fqMz": ["연결 오류. 다시 시도하세요."],"Q6hhn8": ["환경설정"],@@ -3141,7 +3143,6 @@"다른 문서의 MirrorSource 블록을 읽기 전용으로 복사한 내용입니다. 소스에서 편집하면 실시간으로 업데이트됩니다."],"_XWY2J": ["터미널 비활성화됨"],- "_YWqV2": ["OpenKnowledge에서 충돌 해결"],"_ayOfA": ["Google의 Open Knowledge Format을 따르는 지식 베이스입니다. 알고 있는 정보를 정리하는 공유 방식입니다. 형식을 이해하는 다른 도구에서도 노트를 잘 활용하려면 이것을 선택하세요."],@@ -3955,7 +3956,6 @@"i3f2kh": ["일치하는 명령이 없습니다."],"i6o7XB": ["언어 검색"],"i92eAT": ["저장소를 만들고 동기화를 시작합니다. 터미널은 필요하지 않습니다."],- "i94lQe": ["OpenKnowledge에서 충돌 확인"],"i9OyGp": ["실행 취소 또는 다시 실행"],"i9TPUi": ["<0>",@@ -4646,9 +4646,6 @@"의 상위 폴더를 열었습니다"],"pZAs1T": ["나가는 링크 불러오기 실패"],- "pZaMLc": [- "이 파일에는 충돌 마커처럼 보이는 줄이 있어 충돌 경계를 정확히 읽을 수 없습니다. 직접 해결하거나 AI에게 묻기를 사용하세요."- ],"paCw0z": [["0"], "/ 폴더가 ", ["1"], "/ 안에 있는 모든 항목"],"pajIrl": ["터미널을 끄지 못했습니다: ", ["0"]],"pbwTg6": [["seconds"], "초 전"],@@ -5140,7 +5137,6 @@"ugbD36": [["count", "plural", { "other": ["다음 파일 ", "#", "개를 삭제하시겠습니까?"] }]],"ugoTXs": ["폴더"],"uhJEA2": [["count", "plural", { "other": ["참여자 ", "#", "명 더"] }]],- "uhYnaD": ["유지할 내용을 골라 충돌을 해결합니다"],"uksqrP": ["저장소 검색 실패. 이름 변경, 삭제 또는 이동됐을 수 있습니다."],"ul1Atu": ["변환 중…"],"um-es7": ["편집기를 다음과 함께 제공"],@@ -5410,6 +5406,9 @@"xtJgSe": ["이 소스에는 여러 스킬이 들어 있습니다. 가져올 항목을 선택하세요."],"xvv5gL": ["스크린샷 미리 보기"],"xxRpzT": ["시스템에서 Slidev를 찾았습니다."],+ "xxxG_a": [+ "이 파일에는 충돌 표시처럼 보이는 줄이 있어 충돌 경계를 정확히 읽을 수 없습니다. 파일의 표시를 수동으로 해결하세요."+ ],"xzAmL_": ["자동 승인됨"],"xzktOa": ["위키 링크 편집"],"y-LQPF": ["해결할 수 없는 이미지 ", ["identity"], ". 참조로 이동합니다."],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex ff8c8dea4..975219df0 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -7107,6 +7107,10 @@ msgstr "안녕하세요, 여러분!"msgid "Help"msgstr "도움말"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "{filePath}의 충돌을 이해할 수 있도록 도와주세요. OpenKnowledge 충돌 보기에서 무엇을 비교해야 하는지 설명해 주세요. 해결 방법은 제가 그곳에서 선택하고 적용하겠습니다."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge에서 {subject} 확인"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge에서 충돌 확인"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge에서 프로젝트 확인"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge에서 프로젝트 설정 조회"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge에서 설정 조회: {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge에서 충돌 해결"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge에서 {subject} 충돌 해결"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge에서 이전 버전 복원"@@ -11545,10 +11537,6 @@ msgstr "문서나 스킬의 버전 기록, 또는 폴더의 활동을 읽습니msgid "Reads this project's OpenKnowledge settings"msgstr "이 프로젝트의 OpenKnowledge 설정을 읽습니다"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "편집 간의 미해결 충돌을 읽습니다"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "준비됨"@@ -12209,10 +12197,6 @@ msgstr "삭제하기 전에 {files}의 충돌을 해결하고, +{overflow}개msgid "Resolved"msgstr "해결됨"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "유지할 내용을 골라 충돌을 해결합니다"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "기본 위치 확인 중"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "이 파일은 텍스트 편집기에서 열 수 없습니다."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "이 파일에는 충돌 마커처럼 보이는 줄이 있어 충돌 경계를 정확히 읽을 수 없습니다. 직접 해결하거나 AI에게 묻기를 사용하세요."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "이 파일에는 충돌 표시처럼 보이는 줄이 있어 충돌 경계를 정확히 읽을 수 없습니다. 파일의 표시를 수동으로 해결하세요."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex b84081e46..10a98f0fb 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -985,7 +985,6 @@"AddR83": ["Ćōũĺď ńōţ ćŕēàţē ƥŕōĴēćţ. Ţŕŷ àĝàĩń ōŕ ƥĩćķ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],"AdjDox": ["Ďŕàƒţ"],"AeHuzT": ["# Ōńē ƥàţţēŕń ƥēŕ ĺĩńē.\n# Ēxàḿƥĺēś:\n# ďŕàƒţś/\n# *.ďŕàƒţ.ḿď\n# !ķēēƥ.ḿď"],- "AeLo3p": ["ŌƥēńĶńōŵĺēďĝē ŕēśōĺvēď à ćōńƒĺĩćţ ĩń ", ["subject"]],"AeORtB": ["Śēĺēćţēď: ",["innermostLabel"],@@ -1083,7 +1082,6 @@"BgV29F": ["Vĩśũàĺ ēďĩţōŕ ƒĩńď ĩńƥũţ ƒōćũśēď"],"Bgaa_U": ["Ƒàĩĺēď ţō ũƥďàţē ƥēŕƒōŕḿàńćē śēţţĩńĝ — ", ["detail"]],"BhLPRk": ["Ŕēvēŕţēď \"", ["name"], "\" ţō ţĥē ĩńśţàĺĺēď vēŕśĩōń"],- "BhMWIs": ["Ŕēàďś ũńŕēśōĺvēď ćōńƒĺĩćţś ƀēţŵēēń ēďĩţś"],"BiVBP9": ["Ćōũĺďń'ţ ŕēàď ţĥē śƥēĺĺĩńĝ ĺàńĝũàĝēś."],"BjitBo": ["Ďōŵńĺōàď ", ["0"]],"BkGtRl": [@@ -2339,6 +2337,11 @@"Pw5PTU": ["Ēxţēŕńàĺ ōŕĩĝĩń"],"PxZCNM": ["Ōũţśĩďē ŵĥàţ Ōƥēń Ķńōŵĺēďĝē ćōḿḿĩţś."],"Q-DKvr": ["Ĩńśţàĺĺ ƒŕōḿ ", ["source"]],+ "Q-a_4h": [+ "Ĥēĺƥ ḿē ũńďēŕśţàńď ţĥē ćōńƒĺĩćţ ĩń ",+ ["filePath"],+ ". Ēxƥĺàĩń ŵĥàţ Ĩ śĥōũĺď ćōḿƥàŕē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē Ćōńƒĺĩćţ vĩēŵ; Ĩ ŵĩĺĺ ćĥōōśē àńď àƥƥĺŷ ţĥē ŕēśōĺũţĩōń ţĥēŕē."+ ],"Q1mtyd": ["Ĥĩďē śĩďēƀàŕ"],"Q5fqMz": ["Ćōńńēćţĩōń ēŕŕōŕ — ţŕŷ àĝàĩń"],"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],@@ -3262,7 +3265,6 @@"Ŕēàď-ōńĺŷ ćōƥŷ ōƒ à ḾĩŕŕōŕŚōũŕćē ƀĺōćķ ƒŕōḿ àńōţĥēŕ ďōć. Ēďĩţ àţ ţĥē śōũŕćē àńď ĩţ ũƥďàţēś ĺĩvē."],"_XWY2J": ["Ţēŕḿĩńàĺ ďĩśàƀĺēď"],- "_YWqV2": ["ŌƥēńĶńōŵĺēďĝē ŕēśōĺvēď à ćōńƒĺĩćţ"],"_ayOfA": ["À ķńōŵĺēďĝē ƀàśē ţĥàţ ƒōĺĺōŵś Ĝōōĝĺē'ś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ, à śĥàŕēď ŵàŷ ōƒ ōŕĝàńĩźĩńĝ ŵĥàţ ŷōũ ķńōŵ. Ƥĩćķ ţĥĩś ĩƒ ŷōũ ŵàńţ ŷōũŕ ńōţēś ţō ŵōŕķ ŵēĺĺ ŵĩţĥ ōţĥēŕ ţōōĺś ţĥàţ ũńďēŕśţàńď ţĥē ƒōŕḿàţ."],@@ -4124,7 +4126,6 @@"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],"i6o7XB": ["Śēàŕćĥ ĺàńĝũàĝēś"],"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],- "i94lQe": ["ŌƥēńĶńōŵĺēďĝē ćĥēćķēď ƒōŕ ćōńƒĺĩćţś"],"i9OyGp": ["Ũńďō ōŕ ŕēďō"],"i9TPUi": ["Ţĥĩś ",@@ -4842,9 +4843,6 @@" ƀēćàũśē ĩţ ćōńţàĩńś à .ĝĩţ ƒōĺďēŕ"],"pZAs1T": ["Ƒàĩĺēď ţō ĺōàď ōũţĝōĩńĝ ĺĩńķś"],- "pZaMLc": [- "Ţĥĩś ƒĩĺē ćōńţàĩńś ĺĩńēś ţĥàţ ĺōōķ ĺĩķē ćōńƒĺĩćţ ḿàŕķēŕś, śō ţĥē ćōńƒĺĩćţ ƀōũńďàŕĩēś ćàń'ţ ƀē ŕēàď ŕēĺĩàƀĺŷ. Ŕēśōĺvē ĩţ ƀŷ ĥàńď ōŕ ŵĩţĥ Àśķ ÀĨ."- ],"paCw0z": ["ēvēŕŷţĥĩńĝ ũńďēŕ ", ["0"], "/ ƒōĺďēŕś ĩńśĩďē ", ["1"], "/"],"pajIrl": ["Ćōũĺď ńōţ ţũŕń ōƒƒ ţĥē ţēŕḿĩńàĺ: ", ["0"]],"pbwTg6": [["seconds"], "ś àĝō"],@@ -5378,7 +5376,6 @@{ "one": ["#", " ḿōŕē ƥàŕţĩćĩƥàńţ"], "other": ["#", " ḿōŕē ƥàŕţĩćĩƥàńţś"] }]],- "uhYnaD": ["Ŕēśōĺvēś à ćōńƒĺĩćţ ƀŷ ćĥōōśĩńĝ ŵĥĩćĥ ćōńţēńţ ţō ķēēƥ"],"uksqrP": ["Ŕēƥōśĩţōŕŷ ńōţ ƒōũńď. Ĩţ ḿàŷ ĥàvē ƀēēń ŕēńàḿēď, ďēĺēţēď, ōŕ ḿōvēď."],"ul1Atu": ["Ćōńvēŕţĩńĝ..."],"um-es7": ["Śĥĩƥ ţĥē ēďĩţōŕ ŵĩţĥ à"],@@ -5661,6 +5658,9 @@"xtJgSe": ["Ţĥĩś śōũŕćē ƀũńďĺēś śēvēŕàĺ śķĩĺĺś — ćĥōōśē ţĥē ōńē ţō ĩḿƥōŕţ."],"xvv5gL": ["Śćŕēēńśĥōţ ƥŕēvĩēŵ"],"xxRpzT": ["Śĺĩďēv ƒōũńď ōń ŷōũŕ śŷśţēḿ."],+ "xxxG_a": [+ "Ţĥĩś ƒĩĺē ćōńţàĩńś ĺĩńēś ţĥàţ ĺōōķ ĺĩķē ćōńƒĺĩćţ ḿàŕķēŕś, śō ţĥē ćōńƒĺĩćţ ƀōũńďàŕĩēś ćàń'ţ ƀē ŕēàď ŕēĺĩàƀĺŷ. Ŕēśōĺvē ţĥē ḿàŕķēŕś ĩń ţĥē ƒĩĺē ƀŷ ĥàńď."+ ],"xzAmL_": ["Àũţō-àƥƥŕōvēď"],"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],"y-LQPF": ["Ũńŕēśōĺvàƀĺē ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex a7a111622..8f4044bd1 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -7103,6 +7103,10 @@ msgstr ""msgid "Help"msgstr ""+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr ""+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10370,10 +10374,6 @@ msgstr ""msgid "OpenKnowledge checked {subject}"msgstr ""-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr ""-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr ""@@ -10555,14 +10555,6 @@ msgstr ""msgid "OpenKnowledge read the setting {key}"msgstr ""-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr ""--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr ""-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr ""@@ -11541,10 +11533,6 @@ msgstr ""msgid "Reads this project's OpenKnowledge settings"msgstr ""-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr ""-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr ""@@ -12205,10 +12193,6 @@ msgstr ""msgid "Resolved"msgstr ""-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr ""-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr ""@@ -15151,7 +15135,7 @@ msgid "This file can't be opened in the text editor."msgstr ""#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."msgstr ""#: src/components/use-viewer-text.tsdiff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 056ae8473..e87df7182 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -1140,7 +1140,6 @@"AeHuzT": ["# Um padrão por linha.\\n# Exemplos:\\n# drafts/\\n# *.draft.md\\n# !keep.md"],- "AeLo3p": ["OpenKnowledge resolveu um conflito em ", ["subject"]],"AeORtB": ["Selecionado: ",["innermostLabel"],@@ -1246,7 +1245,6 @@"BgV29F": ["Campo de busca do editor visual em foco"],"Bgaa_U": ["Falha ao atualizar a configuração de desempenho — ", ["detail"]],"BhLPRk": ["\"", ["name"], "\" revertido para a versão instalada"],- "BhMWIs": ["Lê conflitos não resolvidos entre edições"],"BiVBP9": ["Não foi possível ler os idiomas da verificação ortográfica."],"BjitBo": ["Baixar ", ["0"]],"BkGtRl": [@@ -2663,6 +2661,11 @@"Pw5PTU": ["Origem externa"],"PxZCNM": ["Fora do que o Open Knowledge faz commit."],"Q-DKvr": ["Instalar a partir de ", ["source"]],+ "Q-a_4h": [+ "Ajude-me a entender o conflito em ",+ ["filePath"],+ ". Explique o que devo comparar na visualização de conflitos do OpenKnowledge; vou escolher e aplicar a resolução lá."+ ],"Q1mtyd": ["Ocultar a barra lateral"],"Q5fqMz": ["Erro de conexão — tente de novo"],"Q6hhn8": ["Preferências"],@@ -3706,7 +3709,6 @@"Cópia somente leitura de um bloco MirrorSource de outro documento. Edite na fonte e ela se atualiza ao vivo."],"_XWY2J": ["Terminal desativado"],- "_YWqV2": ["OpenKnowledge resolveu um conflito"],"_ayOfA": ["Uma base de conhecimento que segue o Open Knowledge Format do Google, uma forma comum de organizar o que você sabe. Escolha isto se quiser que suas notas funcionem bem com outras ferramentas que entendem o formato."],@@ -4700,7 +4702,6 @@"i3f2kh": ["Nenhum comando corresponde."],"i6o7XB": ["Pesquisar idiomas"],"i92eAT": ["Vamos criar um repositório e começar a sincronizar — sem precisar de terminal."],- "i94lQe": ["OpenKnowledge verificou se há conflitos"],"i9OyGp": ["Desfazer ou refazer"],"i9TPUi": ["Este ",@@ -5471,9 +5472,6 @@" foi aberta porque contém uma pasta .git"],"pZAs1T": ["Falha ao carregar os links de saída"],- "pZaMLc": [- "Este arquivo contém linhas que parecem marcadores de conflito, então os limites do conflito não podem ser lidos de forma confiável. Resolva-o manualmente ou com Perguntar à IA."- ],"paCw0z": ["tudo dentro das pastas ", ["0"], "/ que estão em ", ["1"], "/"],"pajIrl": ["Não foi possível desligar o terminal: ", ["0"]],"pbwTg6": ["há ", ["seconds"], " s"],@@ -6065,7 +6063,6 @@}]],- "uhYnaD": ["Resolve um conflito escolhendo qual conteúdo manter"],"uksqrP": ["Repositório não encontrado. Ele pode ter sido renomeado, excluído ou movido."],"ul1Atu": ["Convertendo..."],"um-es7": ["Publique o editor com um"],@@ -6385,6 +6382,9 @@"xtJgSe": ["Esta fonte traz várias habilidades — escolha qual importar."],"xvv5gL": ["Prévia da captura de tela"],"xxRpzT": ["Slidev encontrado no seu sistema."],+ "xxxG_a": [+ "Este arquivo contém linhas que parecem marcadores de conflito, então não é possível identificar os limites dos conflitos com segurança. Resolva os marcadores no arquivo manualmente."+ ],"xzAmL_": ["Aprovado automaticamente"],"xzktOa": ["Editar o link wiki"],"y-LQPF": ["Não foi possível resolver a imagem ", ["identity"], ". Ir para a referência."],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 03c024a54..49351db98 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -7103,6 +7103,10 @@ msgstr "Olá, mundo!"msgid "Help"msgstr "Ajuda"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "Ajude-me a entender o conflito em {filePath}. Explique o que devo comparar na visualização de conflitos do OpenKnowledge; vou escolher e aplicar a resolução lá."+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10370,10 +10374,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge verificou {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge verificou se há conflitos"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge verificou o projeto"@@ -10555,14 +10555,6 @@ msgstr "OpenKnowledge leu as configurações do projeto"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge leu a configuração {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge resolveu um conflito"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge resolveu um conflito em {subject}"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge restaurou uma versão anterior"@@ -11541,10 +11533,6 @@ msgstr "Lê o histórico de versões de um documento ou habilidade, ou a atividamsgid "Reads this project's OpenKnowledge settings"msgstr "Lê as configurações do OpenKnowledge deste projeto"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "Lê conflitos não resolvidos entre edições"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "Pronto"@@ -12205,10 +12193,6 @@ msgstr "Resolva o conflito em {files} e em mais {overflow} antes de excluir."msgid "Resolved"msgstr "Resolvido"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "Resolve um conflito escolhendo qual conteúdo manter"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "Resolvendo o local padrão"@@ -15151,8 +15135,8 @@ msgid "This file can't be opened in the text editor."msgstr "Não dá para abrir este arquivo no editor de texto."#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "Este arquivo contém linhas que parecem marcadores de conflito, então os limites do conflito não podem ser lidos de forma confiável. Resolva-o manualmente ou com Perguntar à IA."+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "Este arquivo contém linhas que parecem marcadores de conflito, então não é possível identificar os limites dos conflitos com segurança. Resolva os marcadores no arquivo manualmente."#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex ed18158fe..e1ea7477c 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -999,7 +999,6 @@"AddR83": ["پروجیکٹ نہیں بنایا جا سکا۔ دوبارہ کوشش کریں یا کوئی مختلف مقام منتخب کریں۔"],"AdjDox": ["مسودہ"],"AeHuzT": ["# ہر سطر پر ایک پیٹرن۔\n# مثالیں:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge نے ", ["subject"], " میں ایک تنازع حل کیا"],"AeORtB": ["منتخب: ",["innermostLabel"],@@ -1093,7 +1092,6 @@"BgV29F": ["بصری ایڈیٹر کا تلاش اِن پٹ فوکس میں ہے"],"Bgaa_U": ["کارکردگی کی ترتیب تازہ نہیں ہو سکی — ", ["detail"]],"BhLPRk": ["«", ["name"], "» کو نصب شدہ ورژن پر واپس پلٹا دیا گیا"],- "BhMWIs": ["ترامیم کے درمیان حل نہ ہونے والے تنازعات پڑھتا ہے"],"BiVBP9": ["املا کی جانچ کی زبانیں پڑھی نہیں جا سکیں۔"],"BjitBo": [["0"], " ڈاؤن لوڈ کریں"],"BkGtRl": [@@ -2384,6 +2382,10 @@"Pw5PTU": ["بیرونی اوریجن"],"PxZCNM": ["اس دائرے سے باہر جسے Open Knowledge کمٹ کرتا ہے۔"],"Q-DKvr": [["source"], " سے نصب کریں"],+ "Q-a_4h": [+ ["filePath"],+ " میں موجود کنفلکٹ کو سمجھنے میں میری مدد کریں۔ بتائیں کہ OpenKnowledge کے کنفلکٹ کے منظر میں مجھے کن چیزوں کا موازنہ کرنا چاہیے؛ میں وہیں حل منتخب کر کے نافذ کروں گا۔"+ ],"Q1mtyd": ["سائیڈ بار چھپائیں"],"Q5fqMz": ["کنکشن کی خرابی — دوبارہ کوشش کریں"],"Q6hhn8": ["ترجیحات"],@@ -3330,7 +3332,6 @@"کسی دوسری دستاویز کے MirrorSource بلاک کی صرف پڑھنے والی نقل۔ ماخذ پر ترمیم کریں اور یہ براہِ راست تازہ ہو جاتی ہے۔"],"_XWY2J": ["ٹرمینل بند"],- "_YWqV2": ["OpenKnowledge نے ایک تنازع حل کیا"],"_ayOfA": ["ایک نالج بیس جو Google کے Open Knowledge Format کی پیروی کرتا ہے، جو آپ کی معلومات کو منظم کرنے کا ایک مشترکہ طریقہ ہے۔ اگر آپ چاہتے ہیں کہ آپ کے نوٹس اس فارمیٹ کو سمجھنے والے دیگر ٹولز کے ساتھ اچھی طرح کام کریں تو یہ منتخب کریں۔"],@@ -4208,7 +4209,6 @@"i3f2kh": ["کوئی مماثل کمانڈ نہیں۔"],"i6o7XB": ["زبانیں تلاش کریں"],"i92eAT": ["ہم ایک ریپازٹری بنا کر مطابقت پذیری شروع کر دیں گے — کسی ٹرمینل کی ضرورت نہیں۔"],- "i94lQe": ["OpenKnowledge نے تنازعات کی جانچ کی"],"i9OyGp": ["واپسی یا دوبارہ"],"i9TPUi": ["یہ ",@@ -4937,9 +4937,6 @@" کا اوپر والا فولڈر کھولا گیا، کیونکہ اس میں .git فولڈر موجود ہے"],"pZAs1T": ["باہر جانے والے لنکس لوڈ نہیں ہو سکے"],- "pZaMLc": [- "اس فائل میں ایسی سطریں ہیں جو کنفلکٹ مارکرز جیسی لگتی ہیں، اس لیے کنفلکٹ کی حدود بھروسے سے نہیں پڑھی جا سکتیں۔ اسے خود حل کریں یا AI سے پوچھیں استعمال کریں۔"- ],"paCw0z": [["1"], "/ کے اندر ", ["0"], "/ فولڈرز کے تحت سب کچھ"],"pajIrl": ["ٹرمینل بند نہیں ہو سکا: ", ["0"]],"pbwTg6": [["seconds"], " سیکنڈ پہلے"],@@ -5455,7 +5452,6 @@],"ugoTXs": ["فولڈر"],"uhJEA2": [["count", "plural", { "one": ["#", " مزید شریک"], "other": ["#", " مزید شرکاء"] }]],- "uhYnaD": ["کون سا مواد رکھنا ہے یہ چن کر تنازع حل کرتا ہے"],"uksqrP": ["ریپازٹری نہیں ملی۔ ہو سکتا ہے اس کا نام بدل گیا ہو، حذف ہو گئی ہو، یا منتقل ہو گئی ہو۔"],@@ -5748,6 +5744,9 @@"xtJgSe": ["یہ ماخذ کئی مہارتیں سمیٹے ہوئے ہے — درآمد کے لیے ایک منتخب کریں۔"],"xvv5gL": ["اسکرین شاٹ کا پیش منظر"],"xxRpzT": ["آپ کے سسٹم پر Slidev مل گیا۔"],+ "xxxG_a": [+ "اس فائل میں کچھ سطریں کنفلکٹ مارکرز جیسی لگتی ہیں، اس لیے کنفلکٹ کی حدود قابلِ اعتماد طریقے سے پڑھی نہیں جا سکتیں۔ فائل میں ان مارکرز کو دستی طور پر حل کریں۔"+ ],"xzAmL_": ["خودکار منظور شدہ"],"xzktOa": ["وکی لنک میں ترمیم کریں"],"y-LQPF": ["ناقابلِ حل تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 4ea0b0d9e..2d5695a40 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -7107,6 +7107,10 @@ msgstr "سلام، دنیا!"msgid "Help"msgstr "مدد"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "{filePath} میں موجود کنفلکٹ کو سمجھنے میں میری مدد کریں۔ بتائیں کہ OpenKnowledge کے کنفلکٹ کے منظر میں مجھے کن چیزوں کا موازنہ کرنا چاہیے؛ میں وہیں حل منتخب کر کے نافذ کروں گا۔"+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge نے {subject} کی جانچ کی"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge نے تنازعات کی جانچ کی"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge نے پروجیکٹ کی جانچ کی"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge نے پروجیکٹ کی ترتیبات پڑھیں"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge نے ترتیب {key} پڑھی"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge نے ایک تنازع حل کیا"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge نے {subject} میں ایک تنازع حل کیا"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge نے پچھلا ورژن بحال کیا"@@ -11545,10 +11537,6 @@ msgstr "کسی دستاویز یا اسکل کی ورژن ہسٹری، یا فوmsgid "Reads this project's OpenKnowledge settings"msgstr "اس پروجیکٹ کی OpenKnowledge ترتیبات پڑھتا ہے"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "ترامیم کے درمیان حل نہ ہونے والے تنازعات پڑھتا ہے"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "تیار"@@ -12209,10 +12197,6 @@ msgstr "حذف کرنے سے پہلے {files} اور مزید {overflow} فائmsgid "Resolved"msgstr "حل شدہ"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "کون سا مواد رکھنا ہے یہ چن کر تنازع حل کرتا ہے"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "طے شدہ مقام معلوم کیا جا رہا ہے"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "یہ فائل ٹیکسٹ ایڈیٹر میں نہیں کھل سکتی۔"#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "اس فائل میں ایسی سطریں ہیں جو کنفلکٹ مارکرز جیسی لگتی ہیں، اس لیے کنفلکٹ کی حدود بھروسے سے نہیں پڑھی جا سکتیں۔ اسے خود حل کریں یا AI سے پوچھیں استعمال کریں۔"+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "اس فائل میں کچھ سطریں کنفلکٹ مارکرز جیسی لگتی ہیں، اس لیے کنفلکٹ کی حدود قابلِ اعتماد طریقے سے پڑھی نہیں جا سکتیں۔ فائل میں ان مارکرز کو دستی طور پر حل کریں۔"#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 252f30702..dc9a6e19e 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -865,7 +865,6 @@"AddR83": ["无法创建项目。请重试或换一个位置。"],"AdjDox": ["草稿"],"AeHuzT": ["# 每行一个模式。\n# 示例:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge 解决了 ", ["subject"], " 中的冲突"],"AeORtB": ["已选择:",["innermostLabel"],@@ -944,7 +943,6 @@"BgV29F": ["可视化编辑器查找输入框已聚焦"],"Bgaa_U": ["更新性能设置失败——", ["detail"]],"BhLPRk": ["已把“", ["name"], "”还原到已安装的版本"],- "BhMWIs": ["读取编辑之间未解决的冲突"],"BiVBP9": ["无法读取拼写检查语言。"],"BjitBo": ["下载 ", ["0"]],"BkGtRl": ["在「编辑源码」面板或代码类属性字段中撤销、重做,或逐步回溯选区变化。"],@@ -2041,6 +2039,11 @@"Pw5PTU": ["外部来源"],"PxZCNM": ["不在 Open Knowledge 的提交范围内。"],"Q-DKvr": ["从 ", ["source"], " 安装"],+ "Q-a_4h": [+ "帮我理解 ",+ ["filePath"],+ " 中的冲突。说明我应该在 OpenKnowledge 的冲突视图中比较哪些内容;我会在那里选择并应用解决方案。"+ ],"Q1mtyd": ["隐藏侧边栏"],"Q5fqMz": ["连接出错——请重试"],"Q6hhn8": ["偏好设置"],@@ -2861,7 +2864,6 @@"_W-elG": ["(内联)"],"_WPP7e": ["来自另一个文档的 MirrorSource 块的只读副本。在来源处编辑,这里会实时更新。"],"_XWY2J": ["终端已禁用"],- "_YWqV2": ["OpenKnowledge 解决了一个冲突"],"_ayOfA": ["遵循 Google Open Knowledge Format 的知识库,一种整理知识的通用方式。如果你希望自己的笔记能与理解该格式的其他工具良好协作,请选这个。"],@@ -3592,7 +3594,6 @@"i3f2kh": ["没有匹配的命令。"],"i6o7XB": ["搜索语言"],"i92eAT": ["我们会创建一个仓库并开始同步——不需要用终端。"],- "i94lQe": ["OpenKnowledge 检查了冲突"],"i9OyGp": ["撤销或重做"],"i9TPUi": ["这个", ["targetNoun"], "不在 <0>", ["branch"], "</0> 分支上。它可能还没有被推送。"],"i9toLO": ["智能体配置文件"],@@ -4217,9 +4218,6 @@" 的上级文件夹,因为其中包含 .git 文件夹"],"pZAs1T": ["加载出链失败"],- "pZaMLc": [- "此文件包含看起来像冲突标记的行,因此无法可靠地识别冲突边界。请手动解决,或使用“问 AI”。"- ],"paCw0z": [["1"], "/ 中各个 ", ["0"], "/ 文件夹下的所有内容"],"pajIrl": ["无法关闭终端:", ["0"]],"pbwTg6": [["seconds"], " 秒前"],@@ -4665,7 +4663,6 @@"ugbD36": [["count", "plural", { "other": ["确定要删除以下 ", "#", " 个文件吗?"] }]],"ugoTXs": ["文件夹"],"uhJEA2": [["count", "plural", { "other": ["另有 ", "#", " 位参与者"] }]],- "uhYnaD": ["通过选择保留的内容来解决冲突"],"uksqrP": ["找不到仓库。它可能已被重命名、删除或移动。"],"ul1Atu": ["正在转换…"],"um-es7": ["让编辑器带上"],@@ -4908,6 +4905,9 @@"xtJgSe": ["这个来源包含多个技能——请选择要导入的那一个。"],"xvv5gL": ["屏幕截图预览"],"xxRpzT": ["在你的系统中找到 Slidev。"],+ "xxxG_a": [+ "此文件包含看起来像冲突标记的行,因此无法可靠地识别冲突边界。请手动处理文件中的标记。"+ ],"xzAmL_": ["已自动批准"],"xzktOa": ["编辑维基链接"],"y-LQPF": ["无法解析图片 ", ["identity"], "。转到引用位置。"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex fead1ccab..e380c71e4 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -7107,6 +7107,10 @@ msgstr "你好,世界!"msgid "Help"msgstr "帮助"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "帮我理解 {filePath} 中的冲突。说明我应该在 OpenKnowledge 的冲突视图中比较哪些内容;我会在那里选择并应用解决方案。"+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge 检查了 {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge 检查了冲突"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge 检查了项目"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge 读取了项目设置"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge 读取了设置 {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge 解决了一个冲突"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge 解决了 {subject} 中的冲突"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge 恢复了较早的版本"@@ -11545,10 +11537,6 @@ msgstr "读取文档或技能的版本历史,或文件夹的活动"msgid "Reads this project's OpenKnowledge settings"msgstr "读取此项目的 OpenKnowledge 设置"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "读取编辑之间未解决的冲突"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "就绪"@@ -12209,10 +12197,6 @@ msgstr "删除前请先解决 {files} 以及另外 {overflow} 个文件上的冲msgid "Resolved"msgstr "已解决"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "通过选择保留的内容来解决冲突"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "正在确定默认位置"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "这个文件无法在文本编辑器中打开。"#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "此文件包含看起来像冲突标记的行,因此无法可靠地识别冲突边界。请手动解决,或使用“问 AI”。"+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "此文件包含看起来像冲突标记的行,因此无法可靠地识别冲突边界。请手动处理文件中的标记。"#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 49511738c..202af7f91 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -865,7 +865,6 @@"AddR83": ["無法建立專案。請再試一次,或換一個位置。"],"AdjDox": ["草稿"],"AeHuzT": ["# 每行一個模式。\n# 範例:\n# drafts/\n# *.draft.md\n# !keep.md"],- "AeLo3p": ["OpenKnowledge 解決了 ", ["subject"], " 中的衝突"],"AeORtB": ["已選取:",["innermostLabel"],@@ -944,7 +943,6 @@"BgV29F": ["視覺化編輯器尋找輸入框已聚焦"],"Bgaa_U": ["更新效能設定失敗——", ["detail"]],"BhLPRk": ["已把「", ["name"], "」回復成已安裝的版本"],- "BhMWIs": ["讀取編輯之間尚未解決的衝突"],"BiVBP9": ["無法讀取拼字檢查語言。"],"BjitBo": ["下載 ", ["0"]],"BkGtRl": ["在「編輯原始碼」窗格或程式碼類屬性欄位中復原、重做,或逐步回溯選取範圍的變化。"],@@ -2059,6 +2057,11 @@"Pw5PTU": ["外部來源"],"PxZCNM": ["不在 Open Knowledge 的提交範圍內。"],"Q-DKvr": ["從 ", ["source"], " 安裝"],+ "Q-a_4h": [+ "幫我理解 ",+ ["filePath"],+ " 中的衝突。說明我應該在 OpenKnowledge 的衝突檢視中比較哪些內容;我會在那裡選擇並套用解決方案。"+ ],"Q1mtyd": ["隱藏側邊欄"],"Q5fqMz": ["連線出錯——請再試一次"],"Q6hhn8": ["偏好設定"],@@ -2877,7 +2880,6 @@"_W-elG": ["(行內)"],"_WPP7e": ["來自另一份文件的 MirrorSource 區塊的唯讀副本。在來源處編輯,這裡會即時更新。"],"_XWY2J": ["終端機已停用"],- "_YWqV2": ["OpenKnowledge 解決了一個衝突"],"_ayOfA": ["遵循 Google Open Knowledge Format 的知識庫,一種整理知識的共通做法。如果你希望自己的筆記能和看得懂這個格式的其他工具好好搭配,請選這個。"],@@ -3608,7 +3610,6 @@"i3f2kh": ["沒有相符的指令。"],"i6o7XB": ["搜尋語言"],"i92eAT": ["我們會建立一個儲存庫並開始同步——不必用終端機。"],- "i94lQe": ["OpenKnowledge 檢查了衝突"],"i9OyGp": ["復原或重做"],"i9TPUi": ["這個", ["targetNoun"], "不在 <0>", ["branch"], "</0> 分支上。它可能還沒有被推送。"],"i9toLO": ["代理設定檔"],@@ -4235,9 +4236,6 @@" 的上層資料夾,因為其中含有 .git 資料夾"],"pZAs1T": ["載入外連連結失敗"],- "pZaMLc": [- "此檔案包含看起來像衝突標記的行,因此無法可靠地辨識衝突邊界。請手動解決,或使用「問 AI」。"- ],"paCw0z": [["1"], "/ 裡各個 ", ["0"], "/ 資料夾底下的所有內容"],"pajIrl": ["無法關閉終端機:", ["0"]],"pbwTg6": [["seconds"], " 秒前"],@@ -4685,7 +4683,6 @@"ugbD36": [["count", "plural", { "other": ["確定要刪除以下 ", "#", " 個檔案嗎?"] }]],"ugoTXs": ["資料夾"],"uhJEA2": [["count", "plural", { "other": ["另有 ", "#", " 位參與者"] }]],- "uhYnaD": ["透過選擇要保留的內容來解決衝突"],"uksqrP": ["找不到儲存庫。它可能已被重新命名、刪除或移動。"],"ul1Atu": ["正在轉換…"],"um-es7": ["讓編輯器帶上"],@@ -4930,6 +4927,9 @@"xtJgSe": ["這個來源包含好幾個技能——請選要匯入的那一個。"],"xvv5gL": ["螢幕截圖預覽"],"xxRpzT": ["在你的系統中找到 Slidev。"],+ "xxxG_a": [+ "此檔案包含看起來像衝突標記的行,因此無法可靠地辨識衝突邊界。請手動處理檔案中的標記。"+ ],"xzAmL_": ["已自動核准"],"xzktOa": ["編輯維基連結"],"y-LQPF": ["無法解析圖片 ", ["identity"], "。前往引用位置。"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 92af471e3..312aa9797 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -7107,6 +7107,10 @@ msgstr "你好,世界!"msgid "Help"msgstr "說明"+#: src/lib/conflict-resolve-draft.ts+msgid "Help me understand the conflict in {filePath}. Explain what I should compare in the OpenKnowledge Conflict view; I will choose and apply the resolution there."+msgstr "幫我理解 {filePath} 中的衝突。說明我應該在 OpenKnowledge 的衝突檢視中比較哪些內容;我會在那裡選擇並套用解決方案。"+#. Subtext under the discovery-skill checkbox#: src/components/McpConsentDialogBody.tsx#: src/components/settings/AgentConnectionDialogs.tsx@@ -10374,10 +10378,6 @@ msgstr "OpenKnowledge"msgid "OpenKnowledge checked {subject}"msgstr "OpenKnowledge 檢查了 {subject}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge checked for conflicts"-msgstr "OpenKnowledge 檢查了衝突"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge 檢查了專案"@@ -10559,14 +10559,6 @@ msgstr "OpenKnowledge 讀取了專案設定"msgid "OpenKnowledge read the setting {key}"msgstr "OpenKnowledge 讀取了設定 {key}"-#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict"-msgstr "OpenKnowledge 解決了一個衝突"--#: src/lib/acp/tool-call-display.ts-msgid "OpenKnowledge resolved a conflict in {subject}"-msgstr "OpenKnowledge 解決了 {subject} 中的衝突"-#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge restored an earlier version"msgstr "OpenKnowledge 還原了較早的版本"@@ -11545,10 +11537,6 @@ msgstr "讀取文件或技能的版本記錄,或資料夾的活動"msgid "Reads this project's OpenKnowledge settings"msgstr "讀取此專案的 OpenKnowledge 設定"-#: src/lib/acp/tool-call-display.ts-msgid "Reads unresolved conflicts between edits"-msgstr "讀取編輯之間尚未解決的衝突"-#: src/components/SessionsHost.tsxmsgid "Ready"msgstr "就緒"@@ -12209,10 +12197,6 @@ msgstr "刪除前請先解決 {files} 以及另外 {overflow} 個檔案上的衝msgid "Resolved"msgstr "已解決"-#: src/lib/acp/tool-call-display.ts-msgid "Resolves a conflict by choosing which content to keep"-msgstr "透過選擇要保留的內容來解決衝突"-#: src/components/CreateProjectDialog.tsxmsgid "Resolving default location"msgstr "正在決定預設位置"@@ -15155,8 +15139,8 @@ msgid "This file can't be opened in the text editor."msgstr "這個檔案無法在文字編輯器中開啟。"#: src/components/ConflictView.tsx-msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve it by hand or with Ask AI."-msgstr "此檔案包含看起來像衝突標記的行,因此無法可靠地辨識衝突邊界。請手動解決,或使用「問 AI」。"+msgid "This file contains lines that look like conflict markers, so the conflict boundaries can't be read reliably. Resolve the markers in the file by hand."+msgstr "此檔案包含看起來像衝突標記的行,因此無法可靠地辨識衝突邊界。請手動處理檔案中的標記。"#: src/components/use-viewer-text.tsmsgid "This file could not be found."diff --git a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.tsindex 98f08c8b0..eeb450fb3 100644--- a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts+++ b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts@@ -99,6 +99,8 @@ describe('sync-resolve-conflict envelope (RFC 9457)', () => {expect(parsed.success).toBe(true);if (parsed.success) {expect(parsed.data.type).toBe('urn:ok:error:no-conflict-tracked');+ expect(parsed.data.detail).toContain('Refresh the conflict list in the OpenKnowledge app');+ expect(parsed.data.detail).not.toContain('conflicts(');}});diff --git a/packages/app/tests/integration/audit-http.test.ts b/packages/app/tests/integration/audit-http.test.tsindex 2d01ef5dd..9fafb5506 100644--- a/packages/app/tests/integration/audit-http.test.ts+++ b/packages/app/tests/integration/audit-http.test.ts@@ -1,6 +1,8 @@+import { randomUUID } from 'node:crypto';import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import {+ DeadLinksSuccessSchema,type ValidationAuditCountsResponse,ValidationAuditCountsResponseSchema,type ValidationAuditResponse,@@ -8,7 +10,12 @@ import {} 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';+import {+ awaitBacklinkIndexed,+ awaitFileWatcherIndexed,+ createTestServer,+ type TestServer,+} from './test-harness.ts';let server: TestServer;@@ -254,3 +261,48 @@ describe('GET /api/audit', () => {HARNESS_BOOT_TIMEOUT_MS,);});++test(+ 'audit and dead-link output accept explicit Markdown wiki targets',+ async () => {+ const uid = randomUUID().slice(0, 8);+ const folder = `audit-suffix-${uid}`;+ const beta = `beta-${uid}`;+ const source = `${folder}/source`;+ mkdirSync(join(server.contentDir, folder, 'reports'), { recursive: true });+ try {+ for (const target of [+ `${folder}/${beta}`,+ `${folder}/dotted.md`,+ `${folder}/reports/index`,+ ]) {+ writeFileSync(join(server.contentDir, `${target}.md`), '# Target\n\nBody.\n');+ await awaitFileWatcherIndexed(server, target);+ }+ const missing = `${folder}/missing.md`;+ writeFileSync(+ join(server.contentDir, `${source}.md`),+ `# Source\n\n[[${folder}/${beta}.md]] [[${beta}.MDX#body|Alias]] [[${folder}/dotted.md.md]] [[${folder}/reports.md]] [[${missing}]].\n`,+ );+ await awaitBacklinkIndexed(server, missing, source);+ await awaitBacklinkIndexed(server, `${folder}/reports/index`, source);+ const response = await fetch(api(`/api/audit?path=${encodeURIComponent(`${source}.md`)}`));+ expect(response.status).toBe(200);+ const audit = ValidationAuditResponseSchema.parse(await response.json());+ const linkFindings = audit.files+ .flatMap((file) => file.diagnostics)+ .filter((finding) => finding.source === 'links');+ expect(linkFindings.map((finding) => finding.linkTarget)).toEqual([missing]);++ const deadResponse = await fetch(+ api(`/api/dead-links?sourceDocName=${encodeURIComponent(source)}`),+ );+ expect(deadResponse.status).toBe(200);+ const dead = DeadLinksSuccessSchema.parse(await deadResponse.json());+ expect(dead.deadLinks.map((link) => link.target)).toEqual([missing]);+ } finally {+ rmSync(join(server.contentDir, folder), { recursive: true, force: true });+ }+ },+ BACKLINK_SEED_TIMEOUT_MS,+);diff --git a/packages/app/tests/integration/audit-scope-http.test.ts b/packages/app/tests/integration/audit-scope-http.test.tsnew file mode 100644index 000000000..069da49ba--- /dev/null+++ b/packages/app/tests/integration/audit-scope-http.test.ts@@ -0,0 +1,407 @@+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { ProblemDetailsSchema, ValidationAuditResponseSchema } from '@inkeep/open-knowledge-core';+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';+import {+ AUDIT_EMPTY_SCOPE_WARNING,+ auditScopeNotFoundTitle,+} from '../../../server/src/lint/audit-scope.ts';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';+import * as singleFlight from '../../../server/src/single-flight.ts';+import {+ awaitBacklinkIndexed,+ createTestServer,+ HARNESS_BOOT_TIMEOUT_MS,+ type TestServer,+} from './test-harness.ts';++let server: TestServer;+let outsideDir: string;+let client: Awaited<ReturnType<typeof connectMcpTestClient>>;+let auditGate: Promise<void> | undefined;+const observedFlights: boolean[] = [];+let executedFlights = 0;+const createSingleFlight = singleFlight.createSingleFlight;+const flightObserver = vi.spyOn(singleFlight, 'createSingleFlight').mockImplementation(<T>() => {+ const flight = createSingleFlight<T>();+ const run = flight.run;+ flight.run = (key, fn) => {+ const gate = auditGate;+ const result = run(key, () => {+ if (gate !== undefined) executedFlights++;+ return gate === undefined ? fn() : gate.then(fn);+ });+ if (gate !== undefined) observedFlights.push(result.coalesced);+ return result;+ };+ return flight;+});++beforeAll(async () => {+ const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-scope-http-')));+ const seeds = {+ '.ok/config.yml':+ 'contentRules:\n markdownlint:\n enabled: true\n okf:\n enabled: true\n',+ '.gitignore': 'ignored/\nparity/ignored.txt\n',+ 'guides/solo.md': '# Solo\n\nA\ttab.\n\nSee [[scope-solo-ghost]].\n',+ 'guides/second.mdx': '# Second\n\nA\ttab.\n\nSee [[scope-second-ghost]].\n',+ 'guides/dual.md': '# MD\n\nA\ttab.\n\nSee [[scope-md-ghost]].\n',+ 'guides/dual.mdx': '# MDX\n\nA\ttab.\n\nSee [[scope-mdx-ghost]].\n',+ 'folder.md/child.md': '# Child\n\nA\ttab.\n\nSee [[scope-child-ghost]].\n',+ 'folder.md.mdx': '# Sibling\n\n\tA sibling.\n',+ 'choice/child.md': '# Child\n\n\tA child.\n',+ 'choice.mdx': '# Sibling\n\n\tA sibling.\n',+ plain: '# Plain\n\n\tA plain file.\n',+ 'plain.mdx': '# Sibling\n\n\tA sibling.\n',+ 'ignored/document.md': '# Ignored\n\n\tA tab.\n',+ '.hidden.md': '# Hidden\n\n\tA tab.\n',+ 'live/dual.md': '# MD\n\nDisk\ttab.\n',+ 'live/dual.mdx': '# MDX\n\nCanonical\tdisk tab.\n',+ 'clean.md': '---\ntype: article\n---\n\n# Clean\n\nA clean paragraph.\n',+ };+ for (const [path, body] of Object.entries(seeds)) {+ mkdirSync(dirname(join(contentDir, path)), { recursive: true });+ writeFileSync(join(contentDir, path), body);+ }+ mkdirSync(join(contentDir, 'empty'));+ outsideDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-scope-outside-')));+ writeFileSync(join(outsideDir, 'secret.txt'), 'Private fixture.\n');+ symlinkSync(outsideDir, join(contentDir, 'escape'));+ symlinkSync(join(contentDir, 'loop'), join(contentDir, 'loop'));+ const parityBody = [+ '# Parity',+ '',+ '[[target]] [[parity-ghost]]',+ '[doc](./target.md) [missing doc](./missing.md)',+ '[file](./exists.txt) [missing file](./missing.txt)',+ '[ignored file](./ignored.txt) [ignored directory](../ignored/)',+ '[outside](./outside.txt) [folder](./folder/) [anchor](#parity)',+ '[escape](../../outside.txt)',+ '',+ ].join('\n');+ const paritySeeds = {+ 'parity/plain.md': parityBody,+ 'parity/dual.md': parityBody,+ 'parity/dual.mdx': '# Canonical sibling\n',+ 'parity/target.md': '# Target\n',+ 'parity/exists.txt': 'Existing file.\n',+ 'parity/ignored.txt': 'Ignored file.\n',+ 'parity/folder/child.md': '# Child\n',+ };+ for (const [path, body] of Object.entries(paritySeeds)) {+ mkdirSync(dirname(join(contentDir, path)), { recursive: true });+ writeFileSync(join(contentDir, path), body);+ }+ symlinkSync(join(outsideDir, 'secret.txt'), join(contentDir, 'parity/outside.txt'));+ symlinkSync(join(contentDir, 'missing'), join(contentDir, 'dangling'));+ server = await createTestServer({ contentDir, debounce: 60_000, maxDebounce: 60_000 });+ client = await connectMcpTestClient(`${server.baseUrl}/mcp`);+ await awaitBacklinkIndexed(server, 'scope-solo-ghost', 'guides/solo', 5_000);+ await awaitBacklinkIndexed(server, 'scope-second-ghost', 'guides/second', 5_000);+ await awaitBacklinkIndexed(server, 'scope-child-ghost', 'folder.md/child', 5_000);+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await client?.close();+ await server?.cleanup();+ flightObserver.mockRestore();+ if (outsideDir) rmSync(outsideDir, { recursive: true, force: true });+});++async function httpAudit(endpoint: string, path: string) {+ const response = await fetch(`${server.baseUrl}${endpoint}?path=${encodeURIComponent(path)}`);+ expect(response.status).toBe(200);+ return ValidationAuditResponseSchema.parse(await response.json());+}++function resultText(result: Awaited<ReturnType<typeof client.callTool>>): string {+ return result.content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\n');+}++describe('scope parity through HTTP and registered MCP tools', () => {+ test('concurrent physical and extensionless paths share one real audit flight', async () => {+ let release: () => void = () => {};+ auditGate = new Promise<void>((resolve) => {+ release = resolve;+ });+ observedFlights.length = 0;+ executedFlights = 0;+ const requests = [+ httpAudit('/api/audit', 'guides/second.mdx'),+ httpAudit('/api/audit', 'guides/second'),+ ];+ try {+ await expect.poll(() => observedFlights.length).toBe(2);+ expect(executedFlights).toBe(1);+ expect(observedFlights).toEqual([false, true]);+ } finally {+ auditGate = undefined;+ release();+ const [explicit, extensionless] = await Promise.all(requests);+ expect(explicit).toEqual(extensionless);+ expect(explicit.files.map((file) => file.file)).toEqual(['guides/second.mdx']);+ }+ });++ test.each([+ ['guides/solo', 'guides/solo.md'],+ ['guides/second', 'guides/second.mdx'],+ ['guides/dual', 'guides/dual.mdx'],+ ])('resolves %s to %s across all selected validators', async (extensionless, explicit) => {+ for (const [name, endpoint] of [+ ['audit', '/api/audit'],+ ['lint', '/api/lint/audit'],+ ] as const) {+ const [short, full] = await Promise.all([+ httpAudit(endpoint, extensionless),+ httpAudit(endpoint, explicit),+ ]);+ expect(short).toEqual(full);+ expect(full.fileCount).toBe(1);+ if (name === 'audit' && explicit === 'guides/dual.mdx')+ expect(+ full.files[0]?.diagnostics.filter((d) => d.source === 'links').map((d) => d.linkTarget),+ ).toContain('scope-mdx-ghost');+ expect(full.files.map((file) => file.file)).toEqual([explicit]);+ expect(full.ran).toEqual(+ name === 'audit' ? ['markdownlint', 'okf', 'links'] : ['markdownlint', 'okf'],+ );+ expect(full.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010')).toBe(+ true,+ );+ if (name === 'audit')+ expect(full.files[0]?.diagnostics.some((diagnostic) => diagnostic.source === 'links')).toBe(+ true,+ );+ for (const path of [extensionless, explicit]) {+ const result = await client.callTool({ name, arguments: { path } });+ expect(result.isError).toBeUndefined();+ expect(+ ValidationAuditResponseSchema.parse({ warnings: [], ...result.structuredContent }),+ ).toEqual(full);+ }+ }+ if (explicit === 'guides/dual.mdx') {+ const md = await httpAudit('/api/audit', 'guides/dual.md');+ expect(md.files.map((file) => file.file)).toEqual(['guides/dual.md']);+ expect(+ md.files[0]?.diagnostics.filter((d) => d.source === 'links').map((d) => d.linkTarget),+ ).toEqual(['scope-md-ghost']);+ }+ });++ test.each(['folder.md', 'choice', 'plain'])(+ 'keeps the existing scope %s ahead of suffix candidates',+ async (path) => {+ for (const endpoint of ['/api/audit', '/api/lint/audit']) {+ const result = await httpAudit(endpoint, path);+ expect(result.fileCount).toBe(1);+ expect(result.files.map((file) => file.file)).toEqual([+ path === 'plain' ? path : `${path}/child.md`,+ ]);+ if (endpoint === '/api/audit' && path === 'folder.md') {+ expect(+ result.files[0]?.diagnostics.some((diagnostic) => diagnostic.source === 'links'),+ ).toBe(true);+ }+ }+ },+ );++ test.each(['missing', 'guides/second.md', 'dangling', 'plain/child'])(+ 'returns a teaching not-found problem for %s through HTTP and MCP',+ async (path) => {+ for (const [name, endpoint] of [+ ['audit', '/api/audit'],+ ['lint', '/api/lint/audit'],+ ] as const) {+ const response = await fetch(+ `${server.baseUrl}${endpoint}?path=${encodeURIComponent(path)}`,+ );+ expect(response.status).toBe(404);+ expect(ProblemDetailsSchema.parse(await response.json())).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: auditScopeNotFoundTitle(path),+ });+ const result = await client.callTool({ name, arguments: { path } });+ expect(result.isError).toBe(true);+ expect(resultText(result)).toContain(auditScopeNotFoundTitle(path));+ }+ },+ );++ test.each(['empty', 'ignored'])(+ 'reports informational zero coverage for %s without degradation wording',+ async (path) => {+ for (const [name, endpoint] of [+ ['audit', '/api/audit'],+ ['lint', '/api/lint/audit'],+ ] as const) {+ const body = await httpAudit(endpoint, path);+ expect(body).toMatchObject({+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [AUDIT_EMPTY_SCOPE_WARNING],+ });+ const result = await client.callTool({ name, arguments: { path } });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject(body);+ expect(resultText(result)).toContain('No documents were checked');+ expect(resultText(result)).not.toContain('could not fully complete');+ expect(resultText(result)).not.toContain('degraded');+ }+ },+ );++ test('preserves hidden, escape, invalid-path admission and the app doc fallback', async () => {+ for (const endpoint of ['/api/audit', '/api/lint/audit']) {+ for (const [path, warning] of [+ ['.hidden', 'hidden path segment'],+ ['.missing', 'hidden path segment'],+ ['.missing/leaf', 'hidden path segment'],+ ['escape', 'symlink-escape'],+ ['escape/secret.txt', 'symlink-escape'],+ ['escape/missing.txt', 'symlink-escape'],+ ['escape/missing/descendant.txt', 'symlink-escape'],+ ]) {+ const body = await httpAudit(endpoint, path);+ expect(body.fileCount).toBe(0);+ expect(body.files).toEqual([]);+ expect(body.errorCount).toBe(0);+ expect(body.warningCount).toBe(0);+ expect(body.ran).toEqual(endpoint === '/api/audit' ? ['links', 'okf'] : []);+ expect(body.warnings).toEqual([expect.stringContaining(warning)]);+ }+ const response = await fetch(`${server.baseUrl}${endpoint}?path=..%2Foutside`);+ expect(response.status).toBe(400);+ }+ const fallback = await fetch(`${server.baseUrl}/api/audit?doc=missing-app-document`);+ expect(fallback.status).toBe(200);+ expect(+ ValidationAuditResponseSchema.parse(await fallback.json()).warnings.length,+ ).toBeGreaterThan(0);+ });++ test.each(['overlong segment', 'symlink loop'])(+ 'returns a teaching not-found problem for a %s through HTTP and MCP',+ async (kind) => {+ const path = kind === 'overlong segment' ? 'x'.repeat(300) : 'loop';+ for (const [name, endpoint] of [+ ['audit', '/api/audit'],+ ['lint', '/api/lint/audit'],+ ] as const) {+ const response = await fetch(+ `${server.baseUrl}${endpoint}?path=${encodeURIComponent(path)}`,+ );+ expect(response.status).toBe(404);+ expect(ProblemDetailsSchema.parse(await response.json())).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: auditScopeNotFoundTitle(path),+ });+ const result = await client.callTool({ name, arguments: { path } });+ expect(result.isError).toBe(true);+ expect(resultText(result)).toContain(auditScopeNotFoundTitle(path));+ }+ },+ );++ test('checks an explicitly requested ignored file through HTTP and MCP', async () => {+ for (const [name, endpoint] of [+ ['audit', '/api/audit'],+ ['lint', '/api/lint/audit'],+ ] as const) {+ const path = 'ignored/document.md';+ const body = await httpAudit(endpoint, path);+ expect(body.fileCount).toBe(1);+ expect(body.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010')).toBe(+ true,+ );+ expect(body.warnings).toEqual([]);+ const result = await client.callTool({ name, arguments: { path } });+ expect(result.isError).toBeUndefined();+ expect(+ ValidationAuditResponseSchema.parse({ warnings: [], ...result.structuredContent }),+ ).toEqual(body);+ }+ });++ test('physical sibling and indexed sources agree on link target admission', async () => {+ await awaitBacklinkIndexed(server, 'parity-ghost', 'parity/plain', 5_000);+ const indexed = await httpAudit('/api/audit', 'parity/plain.md');+ const physical = await httpAudit('/api/audit', 'parity/dual.md');+ const links = (body: typeof indexed) =>+ body.files.flatMap((file) =>+ file.diagnostics.filter((diagnostic) => diagnostic.source === 'links'),+ );+ expect(links(physical)).toEqual(links(indexed));+ const findings = JSON.stringify(links(physical));+ for (const target of ['parity-ghost', 'missing', 'ignored.txt', 'ignored/', 'outside.txt']) {+ expect(findings).toContain(target);+ }+ expect(findings).not.toContain('exists.txt');+ expect(findings).not.toContain('target.md');+ expect(findings).not.toContain('folder/');+ });++ test('lint and audit keep canonical live text separate from the alternate disk sibling', async () => {+ const connection = await server.instance.hocuspocus.openDirectConnection('live/dual');+ const live = '# Live\n\nClean unsaved text.\n';+ const mdPath = join(server.contentDir, 'live/dual.md');+ const mdxPath = join(server.contentDir, 'live/dual.mdx');+ const mdBefore = readFileSync(mdPath, 'utf8');+ const mdxBefore = readFileSync(mdxPath, 'utf8');+ try {+ await connection.transact((doc) => {+ const source = doc.getText('source');+ source.delete(0, source.length);+ source.insert(0, live);+ });+ for (const endpoint of ['/api/audit', '/api/lint/audit']) {+ const canonical = await httpAudit(endpoint, 'live/dual.mdx');+ const alternate = await httpAudit(endpoint, 'live/dual.md');+ expect(canonical.fileCount).toBe(1);+ expect(+ canonical.files.flatMap((file) => file.diagnostics).some((d) => d.code === 'MD010'),+ ).toBe(false);+ expect(alternate.fileCount).toBe(1);+ expect(+ alternate.files+ .find((file) => file.file === 'live/dual.md')+ ?.diagnostics.some((d) => d.code === 'MD010'),+ ).toBe(true);+ expect(readFileSync(mdPath, 'utf8')).toBe(mdBefore);+ expect(readFileSync(mdxPath, 'utf8')).toBe(mdxBefore);+ }+ } finally {+ await connection.disconnect();+ }+ });++ test('keeps clean nonempty scopes distinct from zero coverage', async () => {+ for (const name of ['audit', 'lint']) {+ const result = await client.callTool({ name, arguments: { path: 'clean.md' } });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ files: [],+ fileCount: 1,+ errorCount: 0,+ warningCount: 0,+ });+ expect(resultText(result)).toContain('No problems across 1 document');+ expect(resultText(result)).not.toContain('No documents were checked');+ }+ });+});diff --git a/packages/app/tests/integration/concurrent-replace-refusal.test.ts b/packages/app/tests/integration/concurrent-replace-refusal.test.tsindex ffb8a8455..47a40ebc8 100644--- a/packages/app/tests/integration/concurrent-replace-refusal.test.ts+++ b/packages/app/tests/integration/concurrent-replace-refusal.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { describe, expect, test } from 'vitest';import * as Y from 'yjs';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';import {createTestClient,createTestServer,@@ -74,6 +75,69 @@ async function expectHumanWriteRefused(}describe('concurrent whole-document replace refusal', () => {+ test('two MCP sessions receive edit recovery while HTTP keeps its positional advice', async () => {+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });+ const clients: Awaited<ReturnType<typeof connectMcpTestClient>>[] = [];+ try {+ const first = await connectMcpTestClient(`${server.baseUrl}/mcp`, { name: 'writer-a' });+ clients.push(first);+ const second = await connectMcpTestClient(`${server.baseUrl}/mcp`, { name: 'writer-b' });+ clients.push(second);+ const docName = `mcp-race-${crypto.randomUUID()}`;+ expect(+ (+ await first.callTool({+ name: 'write',+ arguments: { document: { path: docName, content: '# From A\n\nAlpha.\n' } },+ })+ ).isError,+ ).toBeUndefined();+ const refused = await second.callTool({+ name: 'write',+ arguments: { document: { path: docName, content: '# From B\n', position: 'replace' } },+ });+ expect(refused.isError).toBe(true);+ expect(refused.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: 'text', text: expect.stringContaining('or use edit') }),+ ]),+ );+ expect(refused.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: 'text',+ text: expect.stringContaining('Retry after 3s.'),+ }),+ ]),+ );+ const http = await write(server, {+ docName,+ markdown: '# HTTP replacement\n',+ position: 'replace',+ agentId: 'http-writer',+ });+ expect(http.status).toBe(409);+ expect(await http.json()).toMatchObject({+ detail:+ 'Another writer changed this document recently. Wait a few seconds and retry. A write with position append or prepend is not refused.',+ });+ expect(+ (+ await second.callTool({+ name: 'edit',+ arguments: { document: { path: docName, find: 'Alpha.', replace: 'Targeted edit.' } },+ })+ ).isError,+ ).toBeUndefined();+ expect(+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),+ ).toContain('Targeted edit.');+ } finally {+ await Promise.all(clients.map((client) => client.close()));+ await server.cleanup();+ }+ });+test('two identified agents cannot replace the same document concurrently', async () => {const server = await createTestServer({ debounce: 50, maxDebounce: 200 });try {diff --git a/packages/app/tests/integration/link-authoring-contract.test.ts b/packages/app/tests/integration/link-authoring-contract.test.tsindex f8cb162c9..1db13b426 100644--- a/packages/app/tests/integration/link-authoring-contract.test.ts+++ b/packages/app/tests/integration/link-authoring-contract.test.ts@@ -404,3 +404,45 @@ test('bare-name wiki links are validated the way the editor navigates them', asy{ href: `[[nowhere-${suffix}]]`, resolvedTo: `nowhere-${suffix}`, reason: 'no-such-doc' },]);});++test('write-time wiki validation accepts explicit Markdown suffixes and keeps true misses', async () => {+ const session = await openMcpSession(server.port);+ const suffix = randomUUID().slice(0, 8);+ const folder = `suffix-${suffix}`;+ const sourceDoc = `${folder}/source`;+ const beta = `beta-${suffix}`;+ mkdirSync(join(server.contentDir, folder), { recursive: true });+ for (const target of [`${folder}/${beta}`, `${folder}/dotted.md`, `${folder}/reports/index`]) {+ if (target.endsWith('.md')) {+ writeFileSync(join(server.contentDir, `${target}.md`), '# Target\n\nBody.\n');+ await awaitFileWatcherIndexed(server, target);+ continue;+ }+ await callTool(+ server.port,+ session,+ 'write',+ { document: { path: `${target}.md`, content: '# Target\n\nBody.\n', position: 'replace' } },+ server.contentDir,+ );+ await awaitFileWatcherIndexed(server, target);+ }+ const missing = `${folder}/missing.md`;+ const result = await callTool(+ server.port,+ session,+ 'write',+ {+ document: {+ path: sourceDoc,+ content: `# Source\n\n[[${folder}/${beta}.md]] [[${beta}.mdx#body|Alias]] [[${folder}/dotted.md.md]] [[${folder}/reports.md]] [[${missing}]].\n`,+ position: 'replace',+ },+ },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);+ expect(docResult(result.structuredContent).brokenLinks).toEqual([+ { href: `[[${missing}]]`, resolvedTo: missing, reason: 'no-such-doc' },+ ]);+});diff --git a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts b/packages/app/tests/integration/managed-rename-loaded-doc.test.tsindex 4f89f7563..895b0fd6a 100644--- a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts+++ b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts@@ -67,14 +67,13 @@ describe('Managed rename — loaded-Y.Doc rewrite path (QA-040 / QA-008)', () =>expect(body.renamed).toHaveLength(1);expect(body.rewrittenDocs.length).toBeGreaterThan(0);- await pollUntil(() => ytext.toString().includes('[[new]]'), 5000, 25);- expect(ytext.toString()).toContain('[[new]]');+ await pollUntil(() => ytext.toString().includes('[[new|old]]'), 5000, 25);+ expect(ytext.toString()).toContain('Link: [[new|old]]');expect(ytext.toString()).not.toContain('[[old]]');await wait(800);const hostDisk = readFileSync(join(server.contentDir, 'host.md'), 'utf-8');- expect(hostDisk).toContain('[[new]]');- expect(hostDisk).not.toContain('[[old]]');+ expect(hostDisk).toBe('# Host doc\n\nLink: [[new|old]]\n');const fragmentText = fragment.toString();expect(fragmentText).toContain('new');diff --git a/packages/app/tests/integration/mcp-http.test.ts b/packages/app/tests/integration/mcp-http.test.tsindex 198cf1733..3d288b275 100644--- a/packages/app/tests/integration/mcp-http.test.ts+++ b/packages/app/tests/integration/mcp-http.test.ts@@ -73,7 +73,8 @@ test('POST /mcp serves MCP JSON-RPC over Streamable HTTP', async () => {expect(toolNames).toContain('links');expect(toolNames).toContain('checkpoint');expect(toolNames).toContain('restore_version');- expect(toolNames).toContain('conflicts');+ expect(toolNames).not.toContain('conflicts');+ expect(toolNames).not.toContain('resolve_conflict');expect(toolNames).toContain('palette');expect(toolNames).not.toContain('read_document');expect(toolNames).not.toContain('write_document');diff --git a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts b/packages/app/tests/integration/mcp-move-real-roundtrip.test.tsindex 374ec18b1..da902ed1c 100644--- a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts+++ b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts@@ -104,8 +104,7 @@ describe('MCP move tool — real roundtrip against live OK server (QA-004 / QA-0expect(existsSync(join(server.contentDir, 'articles', 'a.md'))).toBe(false);expect(existsSync(join(server.contentDir, 'articles'))).toBe(false);const indexBody = readFileSync(join(server.contentDir, 'index.md'), 'utf-8');- expect(indexBody).toContain('[[essays/a]]');- expect(indexBody).not.toContain('[[articles/a]]');+ expect(indexBody).toBe('# Index\n\nLink: [[essays/a|articles/a]]\n');}, 60_000);test('QA-005: move (document) posts to live /api/rename-path with kind:file → backlinks rewrite', async () => {@@ -154,7 +153,6 @@ describe('MCP move tool — real roundtrip against live OK server (QA-004 / QA-0expect(existsSync(join(server.contentDir, 'sso.md'))).toBe(true);expect(existsSync(join(server.contentDir, 'auth.md'))).toBe(false);const indexBody = readFileSync(join(server.contentDir, 'index.md'), 'utf-8');- expect(indexBody).toContain('[[sso]]');- expect(indexBody).not.toContain('[[auth]]');+ expect(indexBody).toBe('# Index\n\nLink: [[sso|auth]]\n');}, 60_000);});diff --git a/packages/app/tests/integration/rename-write-amplification.test.ts b/packages/app/tests/integration/rename-write-amplification.test.tsindex 27e8998d8..a10f462e6 100644--- a/packages/app/tests/integration/rename-write-amplification.test.ts+++ b/packages/app/tests/integration/rename-write-amplification.test.ts@@ -153,8 +153,7 @@ describe('rename write-amplification — no-content-change rename writes destinaconst bravoFinal = readFileSync(join(server.contentDir, 'bravo.md'), 'utf-8');console.log('[content-change] final bravo.md =', JSON.stringify(bravoFinal));- expect(bravoFinal).toContain('[[bravo]]');- expect(bravoFinal).not.toContain('[[alpha]]');+ expect(bravoFinal).toBe('# Self\n\nlink to [[bravo|alpha]]\n');} finally {await client?.cleanup();await server.cleanup();@@ -186,8 +185,8 @@ describe('rename write-amplification — no-content-change rename writes destina);expect(renamedWrites.length).toBe(1);- expect(readFileSync(join(server.contentDir, 'referrer.md'), 'utf-8')).toContain(- '[[renamed]]',+ expect(readFileSync(join(server.contentDir, 'referrer.md'), 'utf-8')).toBe(+ '# Ref\n\nsee [[renamed|target]]\n',);} finally {await server.cleanup();diff --git a/packages/app/tests/integration/skill-mcp-move.test.ts b/packages/app/tests/integration/skill-mcp-move.test.tsindex 44edb533d..309c2371e 100644--- a/packages/app/tests/integration/skill-mcp-move.test.ts+++ b/packages/app/tests/integration/skill-mcp-move.test.ts@@ -13,6 +13,7 @@ import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import { withFsCopyCompletionObserver } from '../../../server/src/fs-copy-observer.test-helper.ts';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';import { moveSkillCrossScope } from '../../../server/src/mcp/tools/skill-target.ts';import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from './test-harness.ts';@@ -52,6 +53,75 @@ afterAll(async () => {});describe('MCP cross-scope move', () => {+ test('MCP names a pre-copy refusal and teaches safe retry after addressing it', async () => {+ const client = await connectMcpTestClient(`${server.baseUrl}/mcp`);+ try {+ const result = await client.callTool({+ name: 'move',+ arguments: {+ skill: { from: 'mcp-absent-source', to: 'mcp-absent-source', toScope: 'global' },+ },+ });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ moveState: 'nothing-written' });+ expect(result.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ text: expect.stringContaining('safe to retry once the refusal is addressed'),+ }),+ ]),+ );+ expect(existsSync(join(fixtureRoot, 'home/.claude/skills/mcp-absent-source'))).toBe(false);+ } finally {+ await client.close();+ }+ });++ test('MCP reports removed destination recovery and the recommended retry succeeds', async () => {+ const fromName = 'mcp-cleanup-source';+ const toName = 'mcp-cleanup-destination';+ const original = seedSkill(server.contentDir, fromName);+ const source = join(server.contentDir, '.claude/skills', fromName);+ const destination = join(fixtureRoot, 'home/.claude/skills', toName);+ const client = await connectMcpTestClient(`${server.baseUrl}/mcp`);+ const request = {+ name: 'move',+ arguments: { skill: { from: fromName, to: toName, toScope: 'global' } },+ };+ try {+ const result = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', toName)),+ () => {+ const copied = join(destination, 'SKILL.md');+ rmSync(copied);+ mkdirSync(copied);+ writeFileSync(join(copied, 'occupant.txt'), 'Not a skill file.');+ },+ () => client.callTool(request),+ );+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ moveState: 'destination-removed' });+ expect(result.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ text: expect.stringContaining('moveState: destination-removed'),+ }),+ expect.objectContaining({ text: expect.stringContaining('safe to retry') }),+ ]),+ );+ expect(existsSync(destination)).toBe(false);+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ const retried = await client.callTool(request);+ expect(retried.isError).toBeUndefined();+ expect(existsSync(source)).toBe(false);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(+ original.replace(`name: ${fromName}`, `name: ${toName}`),+ );+ } finally {+ await client.close();+ }+ });+test('preserves binary bundles, provenance and installed editors', async () => {const name = 'complete-bundle';const source = join(fixtureRoot, 'source', name);@@ -178,6 +248,11 @@ describe('MCP cross-scope move', () => {expect(result.isError).toBe(true);expect(result.structuredContent?.moveState).toBe('nothing-written');+ expect(result.content[0]?.text).toContain('moveState: nothing-written');+ expect(result.structuredContent).not.toHaveProperty('retentionLedger');+ expect(result.content[0]?.text).toContain('This call changed neither location.');+ expect(result.content[0]?.text).toContain('safe to retry once the refusal is addressed');+ expect(result.content[0]?.text).not.toContain('unverified');expect(result.content[0]?.text).toContain('Delete or rename it first');expect(readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),diff --git a/packages/app/tests/stress/link-authoring-apex.e2e.ts b/packages/app/tests/stress/link-authoring-apex.e2e.tsindex 11d819f18..38f5fdcbc 100644--- a/packages/app/tests/stress/link-authoring-apex.e2e.ts+++ b/packages/app/tests/stress/link-authoring-apex.e2e.ts@@ -283,3 +283,58 @@ test.describe('apex — clipboard pre-fill under real permission denial', () =>}});});++for (const exactDottedIdentity of [false, true]) {+ test(`Markdown wiki targets preserve ${exactDottedIdentity ? 'exact dotted' : 'suffix-stripped'} identity in both editor modes`, async ({+ page,+ api,+ }) => {+ const folder = `wiki-suffix-${randomUUID().slice(0, 8)}`;+ const source = `${folder}/source`;+ const base = `${folder}/beta`;+ const target = `${base}.md`;+ const expected = exactDottedIdentity ? target : base;+ const marker = `Intended document ${folder}`;+ const missing = `${folder}/missing.md`;+ const docs = [+ { name: base, markdown: `# Beta\n\n${exactDottedIdentity ? 'Other document' : marker}\n` },+ { name: `${base}-md`, markdown: '# Fuzzy collision\n\nWrong destination\n' },+ { name: source, markdown: `# Source\n\n[[${target}#beta|Open target]]\n\n[[${missing}]]\n` },+ ];+ if (exactDottedIdentity) docs.push({ name: `${target}.md`, markdown: `# Beta\n\n${marker}\n` });+ await api.seedDocs(docs);+ await page.goto(`/#/${source}`);+ await waitForActiveProviderSynced(page);++ const chip = page.locator(`${EDITOR} [data-wiki-link][data-target="${target}"]`);+ await expect(chip).toHaveText('Open target');+ await expect(chip).toHaveAttribute('data-resolution-state', 'resolved');+ await chip.click();+ await expect.poll(() => new URL(page.url()).hash).toBe(`#/${expected}#beta`);+ await expect(page.locator(EDITOR)).toContainText(marker);++ await page.goto(`/#/${source}`);+ await waitForActiveProviderSynced(page);+ await page.getByRole('radio', { name: 'Markdown source' }).click();+ const sourceLink = page.locator('.cm-content .cm-wiki-link').filter({ hasText: target });+ await expect(+ page.locator('.cm-content .cm-wiki-link').filter({ hasText: missing }),+ ).toHaveClass(/cm-wiki-link-broken/);+ await expect(sourceLink).toHaveText(`[[${target}#beta|Open target]]`);+ await expect(sourceLink).not.toHaveClass(/cm-wiki-link-broken/);+ const openedPage = page.context().waitForEvent('page');+ await sourceLink.click({ modifiers: ['ControlOrMeta'] });+ const destination = await openedPage;+ try {+ await expect.poll(() => new URL(destination.url()).hash).toBe(`#/${expected}#beta`);+ await waitForActiveProviderSynced(destination);+ await expect(+ destination+ .locator('.cm-content, .ProseMirror:not(.composer-prosemirror)')+ .filter({ visible: true }),+ ).toContainText(marker);+ } finally {+ await destination.close();+ }+ });+}diff --git a/packages/app/tests/stress/qa019-suffix-precedence.e2e.ts b/packages/app/tests/stress/qa019-suffix-precedence.e2e.tsnew file mode 100644index 000000000..5113a30eb--- /dev/null+++ b/packages/app/tests/stress/qa019-suffix-precedence.e2e.ts@@ -0,0 +1,277 @@+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import { expect, test, toggleMode, waitForActiveProviderSynced } from './_helpers';++const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';++async function json<T>(url: string): Promise<T> {+ const r = await fetch(url);+ if (!r.ok) throw new Error(`${url} -> ${r.status}`);+ return (await r.json()) as T;+}++async function pageNames(baseURL: string): Promise<string[]> {+ const body = await json<{ pages: Array<{ docName: string }> }>(`${baseURL}/api/pages`);+ return body.pages.map((p) => p.docName).sort();+}++async function docContent(baseURL: string, docName: string): Promise<string> {+ const body = await json<{ content: string }>(+ `${baseURL}/api/document?docName=${encodeURIComponent(docName)}`,+ );+ return body.content;+}++async function readDoc(+ baseURL: string,+ docName: string,+): Promise<{ status: number; content: string | null }> {+ const r = await fetch(`${baseURL}/api/document?docName=${encodeURIComponent(docName)}`);+ if (!r.ok) return { status: r.status, content: null };+ const body = (await r.json()) as { content: string };+ return { status: r.status, content: body.content };+}++async function forwardTargets(baseURL: string, docName: string): Promise<string[]> {+ const body = await json<{ forwardLinks: Array<{ kind: string; docName?: string }> }>(+ `${baseURL}/api/forward-links?docName=${encodeURIComponent(docName)}`,+ );+ return body.forwardLinks+ .filter((l) => l.kind === 'doc' && typeof l.docName === 'string')+ .map((l) => l.docName as string)+ .sort();+}++async function backlinkSources(baseURL: string, docName: string): Promise<string[]> {+ const body = await json<{ backlinks: Array<{ source: string }> }>(+ `${baseURL}/api/backlinks?docName=${encodeURIComponent(docName)}`,+ );+ return body.backlinks.map((b) => b.source).sort();+}++async function expectExactHash(page: Page, docName: string, label: string): Promise<void> {+ await page+ .waitForFunction(+ (d) => {+ const h = decodeURIComponent(window.location.hash);+ return h === `#/${d}` || h.startsWith(`#/${d}#`);+ },+ docName,+ { timeout: 20_000 },+ )+ .catch(async () => {+ throw new Error(+ `${label}: expected hash #/${docName}, got ${decodeURIComponent(page.url().split('#').slice(1).join('#') ? `#${page.url().split('#').slice(1).join('#')}` : '')}`,+ );+ });+}++async function openDoc(page: Page, docName: string): Promise<void> {+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await page.waitForSelector(WYSIWYG);+ await page.keyboard.press('Escape');+ await page.locator(`${WYSIWYG} h1`).first().click();+}++test('QA-019: exact / one-suffix-stripped / original-fuzzy precedence agrees across every channel', async ({+ page,+ api,+ baseURL,+ workerServer,+}) => {+ test.setTimeout(240_000);+ const K = randomUUID().slice(0, 8);+ const SRC = `src-${K}`;+ const PLAIN = `d1-${K}/x`;+ const DOTTED = `d1-${K}/x.md`;+ const BETA = `notes-${K}/beta`;+ const DECOY = `notes-${K}/beta-md`;+ const FUZZ = `sub-${K}/q.md`;+ const MDX = `mx-${K}/page`;+ const INDEX = `idx-${K}/index`;+ const MISS = `missing-${K}`;++ const corpus = [+ `[[${DOTTED}]]`,+ `[[${DOTTED}.md]]`,+ `[[${PLAIN}]]`,+ `[[${BETA}.md]]`,+ `[[${BETA}.md#intro|Beta Alias]]`,+ '[[q.md]]',+ `[[${MDX}.mdx]]`,+ `[[idx-${K}]]`,+ '[[BETA]]',+ `[[${MISS}]]`,+ ];++ await api.seedDocs([+ { name: `${PLAIN}.md`, markdown: `# X Plain\n\nmarker MKPLAIN${K}\n` },+ {+ name: `${BETA}.md`,+ markdown: `# Beta\n\nmarker MKBETA${K}\n\n## intro\n\nIntro body.\n`,+ },+ { name: `${DECOY}.md`, markdown: `# Beta Decoy\n\nmarker MKBETAMD${K}\n` },+ { name: `${MDX}.mdx`, markdown: `# Page Mdx\n\nmarker MKMDX${K}\n` },+ { name: `${INDEX}.md`, markdown: `# Index\n\nmarker MKINDEX${K}\n` },+ {+ name: `${SRC}.md`,+ markdown: `# Source\n\n${corpus.map((l, i) => `L${i + 1} ${l}`).join('\n\n')}\n`,+ },+ ]);++ const dottedFiles: Array<[string, string]> = [+ [`d1-${K}/x.md.md`, `# X Dotted\n\nmarker MKDOTTED${K}\n`],+ [`sub-${K}/q.md.md`, `# Q Dotted\n\nmarker MKFUZZ${K}\n`],+ ];+ for (const [rel, markdown] of dottedFiles) {+ const full = join(workerServer.contentDir, rel);+ mkdirSync(join(full, '..'), { recursive: true });+ writeFileSync(full, markdown, 'utf-8');+ }+ expect(existsSync(join(workerServer.contentDir, `sub-${K}/q.md`))).toBe(false);+ const rescan = await fetch(`${baseURL}/api/test-rescan-files`, { method: 'POST' });+ expect(rescan.ok).toBe(true);+ const backlinkRescan = await fetch(`${baseURL}/api/test-rescan-backlinks`, { method: 'POST' });+ expect(backlinkRescan.ok).toBe(true);++ await expect+ .poll(() => pageNames(baseURL), { timeout: 30_000 })+ .toEqual(expect.arrayContaining([SRC, PLAIN, DOTTED, BETA, DECOY, FUZZ, MDX, INDEX]));+ const names = await pageNames(baseURL);+ expect(names).not.toContain('q');+ expect(names).not.toContain(`sub-${K}/q`);+ expect(await docContent(baseURL, PLAIN)).toContain(`MKPLAIN${K}`);+ const dottedReadBack = await readDoc(baseURL, DOTTED);+ const fuzzReadBack = await readDoc(baseURL, FUZZ);+ expect(dottedReadBack.status).toBe(200);+ expect(dottedReadBack.content).toContain(`MKDOTTED${K}`);+ expect(dottedReadBack.content).not.toContain(`MKPLAIN${K}`);+ expect(fuzzReadBack.status).toBe(200);+ expect(fuzzReadBack.content).toContain(`MKFUZZ${K}`);+ expect(await docContent(baseURL, `${DOTTED}.md`)).toContain(`MKDOTTED${K}`);++ const expectedTargets = [PLAIN, DOTTED, BETA, FUZZ, MDX, INDEX].sort();+ await expect+ .poll(() => forwardTargets(baseURL, SRC), { timeout: 30_000 })+ .toEqual(expect.arrayContaining(expectedTargets));+ const actualTargets = await forwardTargets(baseURL, SRC);+ expect(actualTargets.filter((t) => !expectedTargets.includes(t)).sort()).toEqual(+ [MISS].filter((m) => actualTargets.includes(m)),+ );+ expect(actualTargets).not.toContain(DECOY);+ expect(await backlinkSources(baseURL, DECOY)).toEqual([]);+ for (const target of expectedTargets) {+ expect(await backlinkSources(baseURL, target), `backlinks of ${target}`).toEqual([SRC]);+ }++ const deadLinks = await json<{ deadLinks: Array<{ target: string }> }>(+ `${baseURL}/api/dead-links?sourceDocName=${encodeURIComponent(SRC)}`,+ );+ expect(deadLinks.deadLinks.map((d) => d.target).sort()).toEqual([MISS]);++ const writeTime = await fetch(`${baseURL}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ docName: SRC,+ markdown: `# Source\n\n${corpus.map((l, i) => `L${i + 1} ${l}`).join('\n\n')}\n`,+ position: 'replace',+ }),+ });+ const writeTimeBody = JSON.stringify(await writeTime.json());+ expect(writeTime.status).toBe(200);++ const richCases: Array<{ label: string; selector: string; doc: string; marker: string }> = [+ { label: 'L1 exact-dotted-beats-stripped', selector: DOTTED, doc: DOTTED, marker: 'MKDOTTED' },+ { label: 'L2 strip-exactly-one', selector: `${DOTTED}.md`, doc: DOTTED, marker: 'MKDOTTED' },+ { label: 'L3 plain-exact', selector: PLAIN, doc: PLAIN, marker: 'MKPLAIN' },+ { label: 'L4 suffix-strip-over-decoy', selector: `${BETA}.md`, doc: BETA, marker: 'MKBETA' },+ {+ label: 'L6 original-fuzzy-after-stripped-miss',+ selector: 'q.md',+ doc: FUZZ,+ marker: 'MKFUZZ',+ },+ { label: 'L7 mdx-strip', selector: `${MDX}.mdx`, doc: MDX, marker: 'MKMDX' },+ { label: 'L9 case-insensitive-basename', selector: 'BETA', doc: BETA, marker: 'MKBETA' },+ ];++ const observedHashes: Record<string, string> = {};+ for (const c of richCases) {+ await openDoc(page, SRC);+ const chip = page.locator(`${WYSIWYG} [data-wiki-link][data-target="${c.selector}"]`).first();+ await expect(chip, `${c.label}: chip present`).toBeVisible({ timeout: 20_000 });+ await chip.click();+ await expectExactHash(page, c.doc, c.label);+ await expect(page.locator(WYSIWYG), `${c.label}: landed marker`).toContainText(+ `${c.marker}${K}`,+ { timeout: 20_000 },+ );+ observedHashes[c.label] = await page.evaluate(() => decodeURIComponent(window.location.hash));+ }++ await openDoc(page, SRC);+ const folderChip = page.locator(`${WYSIWYG} [data-wiki-link][data-target="idx-${K}"]`).first();+ await expect(folderChip, 'L8 folder-index chip present').toBeVisible({ timeout: 20_000 });+ await folderChip.click();+ await expectExactHash(page, `idx-${K}`, 'L8 folder-index app click');+ observedHashes['L8 folder-index'] = await page.evaluate(() =>+ decodeURIComponent(window.location.hash),+ );+ await openDoc(page, INDEX);+ await expect(page.locator(WYSIWYG), 'L8 resolver target is a real document').toContainText(+ `MKINDEX${K}`,+ { timeout: 20_000 },+ );++ await openDoc(page, SRC);+ const aliasChip = page.locator(`${WYSIWYG} [data-wiki-link]`).filter({ hasText: 'Beta Alias' });+ await expect(aliasChip, 'L5 alias chip present').toBeVisible({ timeout: 20_000 });+ await aliasChip.click();+ await expectExactHash(page, BETA, 'L5 alias+heading');+ await expect(page.locator(WYSIWYG)).toContainText(`MKBETA${K}`, { timeout: 20_000 });+ const aliasHash = page.url();++ const missChip = page.locator(`${WYSIWYG} [data-wiki-link][data-target="${MISS}"]`);++ await openDoc(page, SRC);+ await expect(missChip).toBeVisible({ timeout: 20_000 });+ await toggleMode(page, 'source');+ const sourceLinks = page.locator('.cm-content .cm-wiki-link');+ await expect(sourceLinks).toHaveCount(corpus.length, { timeout: 20_000 });+ const brokenLinks = page.locator('.cm-content .cm-wiki-link-broken');+ await expect(brokenLinks).toHaveCount(1, { timeout: 20_000 });+ await expect(brokenLinks.first()).toContainText(MISS);++ const dottedSourceLink = page+ .locator('.cm-content .cm-wiki-link')+ .filter({ hasText: DOTTED })+ .first();+ await expect(dottedSourceLink).toBeVisible({ timeout: 20_000 });+ const openedPromise = page.context().waitForEvent('page', { timeout: 20_000 });+ await dottedSourceLink.click({ modifiers: ['ControlOrMeta'] });+ const opened = await openedPromise;+ await expectExactHash(opened, DOTTED, 'source ctrl-click on the exact dotted identity');+ await waitForActiveProviderSynced(opened);+ await toggleMode(opened, 'wysiwyg');+ await expect(opened.locator(WYSIWYG)).toContainText(`MKDOTTED${K}`, { timeout: 20_000 });+ await expect(opened.locator(WYSIWYG)).not.toContainText(`MKPLAIN${K}`);+ await opened.close();++ process.stdout.write(+ `QA019-OBSERVED ${JSON.stringify({+ K,+ forwardTargets: actualTargets,+ deadLinks: deadLinks.deadLinks.map((d) => d.target),+ aliasHash,+ observedHashes,+ dottedReadBack,+ fuzzReadBack,+ writeTimeBody: writeTimeBody.slice(0, 900),+ srcBytes: await docContent(baseURL, SRC),+ })}\n`,+ );+});diff --git a/packages/app/tests/stress/rename-consolidation.e2e.ts b/packages/app/tests/stress/rename-consolidation.e2e.tsindex bf3574f85..c5e2165e0 100644--- a/packages/app/tests/stress/rename-consolidation.e2e.ts+++ b/packages/app/tests/stress/rename-consolidation.e2e.ts@@ -52,7 +52,7 @@ test.describe('rename-consolidation — browser-fidelity outcomes', () => {}, baseURL);if (indexBytes.status === 200 && indexBytes.body) {- expect(indexBytes.body).toContain('[[sso]]');+ expect(indexBytes.body).toContain('Link: [[sso|auth]]');expect(indexBytes.body).not.toContain('[[auth]]');} else {void indexBytes;diff --git a/packages/cli/src/commands/audit-scope-composition.test.ts b/packages/cli/src/commands/audit-scope-composition.test.tsnew file mode 100644index 000000000..1f1332479--- /dev/null+++ b/packages/cli/src/commands/audit-scope-composition.test.ts@@ -0,0 +1,375 @@+import { spawn } from 'node:child_process';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { createServer } from 'node:http';+import { hostname, tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ ProblemDetailsSchema,+ type ValidationAuditResponse,+ ValidationAuditResponseSchema,+} from '@inkeep/open-knowledge-core';+import { ConfigSchema, readServerLock } from '@inkeep/open-knowledge-server';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from '../../../server/src/boot.ts';+import { bootCompositionRig } from '../../../server/src/composition-rig.test-helper.ts';+import {+ auditScopeNotFoundTitle,+ resolveAuditScope,+} from '../../../server/src/lint/audit-scope.ts';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';++const CLI_PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');+const CLI_ENTRY = join(CLI_PACKAGE_ROOT, 'src/cli.ts');+const CONFIG = 'contentRules:\n markdownlint:\n enabled: true\nvalidation:\n links: warning\n';+const TABBED = '# Guide\n\nA\ttab.\n\nSee [[scope-cli-missing-target]].\n';+let root: string;+let headless: string;+let server: BootedServer;+let client: Awaited<ReturnType<typeof connectMcpTestClient>>;++function seed(directory: string, path: string, body: string): void {+ mkdirSync(dirname(join(directory, path)), { recursive: true });+ writeFileSync(join(directory, path), body);+}++interface CliResult {+ code: number | null;+ stdout: string;+ stderr: string;+}++async function cli(cwd: string, args: string[]): Promise<CliResult> {+ const child = spawn(+ process.execPath,+ [+ '--import',+ 'tsx',+ '--conditions=development',+ CLI_ENTRY,+ '--cwd',+ cwd,+ '--log-level',+ 'silent',+ ...args,+ ],+ {+ cwd: CLI_PACKAGE_ROOT,+ env: { ...process.env, NO_COLOR: '1', OK_BUNDLE_PROXY: '0' },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {+ stdout += chunk;+ });+ child.stderr.setEncoding('utf8').on('data', (chunk: string) => {+ stderr += chunk;+ });+ return await new Promise((resolveResult, reject) => {+ const timer = setTimeout(() => child.kill('SIGKILL'), 25_000);+ child.on('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ child.on('close', (code) => {+ clearTimeout(timer);+ resolveResult({ code, stdout, stderr });+ });+ });+}++function lintPlane(output: string): ValidationAuditResponse {+ const result = ValidationAuditResponseSchema.parse(JSON.parse(output));+ return { ...result, files: result.files.filter((file) => file.diagnostics.length > 0) };+}++async function http(name: string, path: string): Promise<ValidationAuditResponse> {+ const endpoint = name === 'lint' ? '/api/lint/audit' : '/api/audit';+ const response = await fetch(+ `http://127.0.0.1:${server.port}${endpoint}?path=${encodeURIComponent(path)}`,+ );+ expect(response.status).toBe(200);+ return ValidationAuditResponseSchema.parse(await response.json());+}++beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-cli-scope-')));+ headless = realpathSync(mkdtempSync(join(tmpdir(), 'ok-headless-scope-')));+ for (const directory of [root, headless]) {+ seed(directory, '.ok/config.yml', CONFIG);+ seed(directory, 'guides/solo.md', TABBED);+ seed(directory, 'guides/dual.md', '# MD\n\n\tMD tab.\n');+ seed(directory, 'guides/dual.mdx', TABBED);+ seed(directory, 'guides/mdx-only.mdx', TABBED);+ seed(directory, 'guides/clean.md', '# Clean\n\nClean paragraph.\n');+ seed(directory, 'ignored/guide.md', TABBED);+ seed(directory, '.gitignore', 'ignored/\n');+ seed(directory, '.hidden.md', TABBED);+ seed(directory, 'parent', 'regular file');+ mkdirSync(join(directory, 'empty'));+ symlinkSync(join(directory, 'loop'), join(directory, 'loop'));+ }+ server = await bootCompositionRig(root, { config: ConfigSchema.parse({}) });+ seed(root, '.ok/config.yml', CONFIG);+ await server.ready;+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);+ expect(readServerLock(server.lockDir)?.port).toBe(server.port);+}, 60_000);++afterAll(async () => {+ await client?.close();+ await server?.destroy();+ if (root) rmSync(root, { recursive: true, force: true });+ if (headless) rmSync(headless, { recursive: true, force: true });+});++describe('CLI scope parity across real process, HTTP and MCP boundaries', () => {+ test('headless lint exits with a not-found problem when content.dir is missing', async () => {+ const project = realpathSync(mkdtempSync(join(tmpdir(), 'ok-missing-lint-content-')));+ try {+ seed(project, '.ok/config.yml', 'content:\n dir: missing-content\n');+ expect(existsSync(join(project, 'missing-content'))).toBe(false);+ expect(resolveAuditScope(undefined, join(project, 'missing-content')).ok).toBe(false);+ for (const args of [+ ['lint', '--json'],+ ['lint', '.', '--json'],+ ]) {+ const result = await cli(project, args);+ expect(existsSync(join(project, 'missing-content'))).toBe(false);+ expect(result.code, result.stderr).toBe(1);+ expect(ProblemDetailsSchema.parse(JSON.parse(result.stdout))).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: expect.stringContaining('Set content.dir to an existing directory.'),+ });+ }+ mkdirSync(join(project, 'missing-content'));+ seed(project, 'outside.md', '# Outside\n');+ const existing = await cli(project, ['lint', '.', '--json']);+ expect(existing.code, existing.stderr).toBe(0);+ expect(JSON.parse(existing.stdout)).toMatchObject({+ fileCount: 0,+ files: [],+ });+ const outerFile = await cli(project, ['lint', 'outside.md', '--json']);+ expect(outerFile.code, outerFile.stderr).toBe(0);+ expect(JSON.parse(outerFile.stdout)).toMatchObject({+ fileCount: 1,+ files: [{ file: '../outside.md' }],+ });+ } finally {+ rmSync(project, { recursive: true, force: true });+ }+ }, 60_000);++ test('audit exits with a not-found problem for a missing root through the HTTP boundary', async () => {+ const project = realpathSync(mkdtempSync(join(tmpdir(), 'ok-missing-audit-content-')));+ const contentDir = join(project, 'missing-content');+ const seenPaths: string[] = [];+ const httpServer = createServer((req, res) => {+ seenPaths.push(req.url ?? '');+ res.writeHead(404, { 'content-type': 'application/problem+json' });+ res.end(+ JSON.stringify({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: `Content directory ${JSON.stringify(contentDir)} was not found. Set content.dir to an existing directory.`,+ instance: 'urn:uuid:00000000-0000-4000-8000-000000000001',+ }),+ );+ });+ try {+ seed(project, '.ok/config.yml', 'content:\n dir: missing-content\n');+ await new Promise<void>((resolveListen) => httpServer.listen(0, '127.0.0.1', resolveListen));+ const address = httpServer.address();+ if (address === null || typeof address === 'string') throw new Error('Missing HTTP port');+ seed(+ project,+ '.ok/local/server.lock',+ JSON.stringify({ pid: process.pid, hostname: hostname(), port: address.port }),+ );+ for (const args of [+ ['audit', '--json'],+ ['audit', '.', '--json'],+ ]) {+ const result = await cli(project, args);+ expect(result.code, result.stderr).toBe(1);+ expect(ProblemDetailsSchema.parse(JSON.parse(result.stdout))).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: expect.stringContaining('Set content.dir to an existing directory.'),+ });+ }+ expect(seenPaths).toEqual(['/api/audit', '/api/audit']);+ } finally {+ await new Promise<void>((resolveClose) => httpServer.close(() => resolveClose()));+ rmSync(project, { recursive: true, force: true });+ }+ }, 60_000);++ test.each(['lint', 'audit'])(+ '%s explicit and extensionless paths select the same validation plane',+ async (name) => {+ await expect+ .poll(+ async () => {+ const result = await http('audit', 'guides/solo.md');+ return result.files+ .flatMap((file) => file.diagnostics)+ .some((diagnostic) => diagnostic.source === 'links');+ },+ { timeout: 20_000 },+ )+ .toBe(true);+ for (const [short, full] of [+ ['solo', 'solo.md'],+ ['dual', 'dual.mdx'],+ ]) {+ const planes: ValidationAuditResponse[] = [];+ for (const path of [short, full]) {+ const result = await cli(join(root, 'guides'), [name, path, '--json']);+ expect(result.code, result.stderr).toBe(1);+ expect(result.stdout.trim(), result.stderr).not.toBe('');+ const plane = lintPlane(result.stdout);+ expect(plane.fileCount).toBe(1);+ expect(plane.files.map((file) => file.file)).toEqual([`guides/${full}`]);+ planes.push(plane);+ const remote = await http(name, `guides/${path}`);+ expect(plane).toEqual(remote);+ const mcp = await client.callTool({ name, arguments: { path: `guides/${path}` } });+ expect(mcp.isError).toBeUndefined();+ expect(+ ValidationAuditResponseSchema.parse({ warnings: [], ...mcp.structuredContent }),+ ).toEqual(remote);+ }+ expect(planes[0]).toEqual(planes[1]);+ }+ },+ 120_000,+ );++ test.each(['lint', 'audit'])(+ '%s preserves not-found problems and teaches the original path',+ async (name) => {+ for (const path of ['unknown', 'guides/mdx-only.md', 'parent/child']) {+ const result = await cli(root, [+ name,+ path,+ '--json',+ ...(name === 'lint' ? ['--fix'] : []),+ ]);+ expect(result.code, result.stderr).toBe(1);+ expect(ProblemDetailsSchema.parse(JSON.parse(result.stdout))).toMatchObject({+ type: 'urn:ok:error:not-found',+ title: auditScopeNotFoundTitle(path),+ status: 404,+ });+ }+ const text = await cli(root, [name, 'unknown']);+ expect(text.code).toBe(1);+ expect(text.stderr).toContain(auditScopeNotFoundTitle('unknown'));+ expect(readFileSync(join(root, 'guides/mdx-only.mdx'), 'utf8')).toBe(TABBED);+ },+ 120_000,+ );++ test.each(['overlong segment', 'symlink loop'])(+ '%s produces a teaching ProblemDetails envelope from live and headless CLI processes',+ async (kind) => {+ const path = kind === 'overlong segment' ? 'x'.repeat(300) : 'loop';+ for (const [cwd, name] of [+ [root, 'lint'],+ [root, 'audit'],+ [headless, 'lint'],+ ]) {+ const result = await cli(cwd, [name, path, '--json']);+ expect(result.code, result.stderr).toBe(1);+ expect(result.stdout.trim(), result.stderr).not.toBe('');+ expect(ProblemDetailsSchema.parse(JSON.parse(result.stdout))).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: auditScopeNotFoundTitle(path),+ });+ expect(result.stderr).not.toContain(' at ');+ }+ },+ 120_000,+ );++ test.each(['lint', 'audit'])(+ '%s distinguishes ignored and empty scopes from nonempty clean checks',+ async (name) => {+ for (const path of ['empty', 'ignored']) {+ const result = await cli(root, [name, path, '--json']);+ expect(result.code, result.stderr).toBe(0);+ expect(lintPlane(result.stdout)).toMatchObject({+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [expect.stringContaining('No documents were checked')],+ });+ }+ const empty = await cli(root, [name, 'empty']);+ expect(empty.code, empty.stderr).toBe(0);+ expect(empty.stdout).toContain('No documents were checked.');+ expect(empty.stdout).not.toContain('No problems');+ const clean = await cli(root, [name, 'guides/clean']);+ expect(clean.code, clean.stderr).toBe(0);+ expect(clean.stdout).toContain('No problems in 1 file');+ },+ 150_000,+ );++ test.each(['lint', 'audit'])(+ '%s checks explicitly requested ignored files across CLI, HTTP and MCP',+ async (name) => {+ const path = 'ignored/guide.md';+ const result = await cli(root, [name, path, '--json']);+ expect(result.code, result.stderr).toBe(1);+ const plane = lintPlane(result.stdout);+ expect(plane.fileCount).toBe(1);+ expect(plane.files.map((file) => file.file)).toEqual([path]);+ expect(plane.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010')).toBe(+ true,+ );+ expect(plane.warnings).toEqual([]);+ expect(plane).toEqual(await http(name, path));+ const mcp = await client.callTool({ name, arguments: { path } });+ expect(mcp.isError).toBeUndefined();+ expect(+ ValidationAuditResponseSchema.parse({ warnings: [], ...mcp.structuredContent }),+ ).toEqual(plane);+ },+ 60_000,+ );++ test('headless lint retains hidden-file admission and resolves without a server', async () => {+ const hidden = await cli(headless, ['lint', '.hidden', '--json', '--errors-only']);+ expect(hidden.code, hidden.stderr).toBe(0);+ expect(lintPlane(hidden.stdout)).toMatchObject({+ fileCount: 1,+ files: [{ file: '.hidden.md' }],+ });+ const valid = await cli(join(headless, 'guides'), ['lint', 'solo', '--json', '--errors-only']);+ expect(valid.code, valid.stderr).toBe(0);+ expect(lintPlane(valid.stdout).fileCount).toBe(1);+ const missing = await cli(headless, ['lint', 'guides/mdx-only.md', '--fix', '--json']);+ expect(missing.code, missing.stderr).toBe(1);+ expect(ProblemDetailsSchema.parse(JSON.parse(missing.stdout)).title).toBe(+ auditScopeNotFoundTitle('guides/mdx-only.md'),+ );+ expect(readFileSync(join(headless, 'guides/mdx-only.mdx'), 'utf8')).toBe(TABBED);+ }, 90_000);+});diff --git a/packages/cli/src/commands/audit.test.ts b/packages/cli/src/commands/audit.test.tsindex 4bc95b616..eabf846cc 100644--- a/packages/cli/src/commands/audit.test.ts+++ b/packages/cli/src/commands/audit.test.ts@@ -312,6 +312,22 @@ describe('runAudit', () => {expect(err.join('\n')).toContain('outside the content directory');});+ test('preserves the full ProblemDetails object in JSON mode', async () => {+ const problem = {+ type: 'urn:ok:error:not-found',+ title: 'Audit scope "missing" was not found. Use an existing file or directory.',+ status: 404,+ instance: 'urn:uuid:ef975a9a-8229-4e36-82a8-2eae23141320',+ detail: 'Server detail survives.',+ recovery: { retryable: false },+ };+ stubFetch(problem, 404);+ const { io, out, err } = collectIo();+ expect(await runAudit('missing', { json: true }, minimalConfig, dir, dir, io)).toBe(1);+ expect(JSON.parse(out.join('\n'))).toEqual(problem);+ expect(err).toEqual([]);+ });+test('surfaces the problem+json title on a non-OK response', async () => {stubFetch({ title: 'Invalid path.' }, 400);const { io, err } = collectIo();diff --git a/packages/cli/src/commands/audit.ts b/packages/cli/src/commands/audit.tsindex 94c60db70..d8e80aab3 100644--- a/packages/cli/src/commands/audit.ts+++ b/packages/cli/src/commands/audit.ts@@ -1,6 +1,7 @@import { isAbsolute, relative, resolve, sep } from 'node:path';import {clientVersionHeaders,+ ProblemDetailsSchema,type ValidationAuditResponse,ValidationAuditResponseSchema,} from '@inkeep/open-knowledge-core';@@ -9,10 +10,12 @@ import {formatAuditBrokenLinkSuppressionLine,RUNTIME_VERSION,readServerLock,+ resolveAuditScope,resolveContentDir,resolveLockDir,} from '@inkeep/open-knowledge-server';import { Command } from 'commander';+import { z } from 'zod';import { getInvocationCwd } from '../project-anchor.ts';import { formatLintReport, type LintReportInput } from './lint.ts';@@ -31,6 +34,12 @@ const defaultIo: AuditIo = {err: (line) => process.stderr.write(`${line}\n`),};+const LegacyAuditErrorSchema = z.object({+ title: z.string().optional(),+ error: z.string().optional(),+ message: z.string().optional(),+});+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`.';@@ -66,10 +75,13 @@ export async function runAudit(if (path !== undefined) {const rel = toContentRelativeTarget(path, invocationCwd, contentDir);if (rel === null) {- io.err(`Path is outside the content directory (${contentDir}): ${path}`);- return 1;+ if (resolveAuditScope(undefined, contentDir).ok) {+ io.err(`Path is outside the content directory (${contentDir}): ${path}`);+ return 1;+ }+ } else {+ target = rel === '' ? undefined : rel;}- target = rel === '' ? undefined : rel;}const lock = readServerLock(resolveLockDir(projectDir));@@ -91,14 +103,18 @@ export async function runAudit(}if (!res.ok) {- 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}`}`,- );+ const body: unknown = await res.json().catch(() => null);+ const problem = ProblemDetailsSchema.safeParse(body);+ if (problem.success) {+ if (opts.json === true) io.out(JSON.stringify(problem.data, null, 2));+ else io.err(`Audit failed: ${problem.data.title}`);+ } else {+ const legacy = LegacyAuditErrorSchema.safeParse(body);+ const message = legacy.success+ ? (legacy.data.title ?? legacy.data.error ?? legacy.data.message)+ : undefined;+ io.err(`Audit failed: ${message ?? `server responded with ${res.status}`}`);+ }return 1;}diff --git a/packages/cli/src/commands/lint.test.ts b/packages/cli/src/commands/lint.test.tsindex 5aaa964b2..3a2872659 100644--- a/packages/cli/src/commands/lint.test.ts+++ b/packages/cli/src/commands/lint.test.ts@@ -1,4 +1,5 @@import { isAbsolute } from 'node:path';+import { AUDIT_EMPTY_SCOPE_WARNING } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import type { LintRunResult } from '../content/lint-runner.ts';import { formatLintReport, resolveTarget } from './lint.ts';@@ -24,6 +25,28 @@ describe('formatLintReport', () => {expect(out).toContain('Checks run: markdownlint.');});+ test('reports zero-document coverage without a clean-check claim', () => {+ const out = formatLintReport(+ result({+ warnings: ['No documents were checked: this scope contains no admitted documents.'],+ }),+ );+ expect(out).toContain('No documents were checked.');+ expect(out).toContain('Checks selected: markdownlint; no document checks ran.');+ expect(out).not.toContain('No problems');+ expect(out).not.toContain('could not fully complete');+ });++ test('renders known zero-coverage information neutrally while retaining other warnings', () => {+ const warning = 'No documents were checked: source could not be read.';+ const out = formatLintReport(result({ warnings: [AUDIT_EMPTY_SCOPE_WARNING, warning] }));+ expect(out).toContain(AUDIT_EMPTY_SCOPE_WARNING);+ expect(out).not.toContain(`! ${AUDIT_EMPTY_SCOPE_WARNING}`);+ expect(out).toContain(`! ${warning}`);+ expect(formatLintReport(result({ ran: [] }))).toContain('No document checks ran.');+ expect(formatLintReport(result({ ran: undefined }))).toContain('No document checks ran.');+ });+test('groups diagnostics under their file with a summary', async () => {const out = formatLintReport(result({@@ -82,9 +105,11 @@ describe('formatLintReport', () => {});test('distinguishes an explicit empty selection from an older response', () => {- expect(formatLintReport(result({ ran: [] }))).toContain('No checks ran.');- expect(formatLintReport(result({ ran: undefined }))).not.toContain('Checks run:');- expect(formatLintReport(result({ ran: undefined }))).not.toContain('No checks ran.');+ expect(formatLintReport(result({ fileCount: 1, ran: [] }))).toContain('No checks ran.');+ expect(formatLintReport(result({ fileCount: 1, ran: undefined }))).not.toContain('Checks run:');+ expect(formatLintReport(result({ fileCount: 1, ran: undefined }))).not.toContain(+ 'No checks ran.',+ );});});diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.tsindex d034e6625..de53a4f8a 100644--- a/packages/cli/src/commands/lint.ts+++ b/packages/cli/src/commands/lint.ts@@ -1,12 +1,20 @@+import { randomUUID } from 'node:crypto';import { resolve } from 'node:path';import {DEFAULT_LINTER_CONFIG,+ isAuditEmptyScopeWarning,type LinterConfig,type PersistedLinterConfig,+ type ProblemDetails,toEffectiveBase,validationCoverageLines,} from '@inkeep/open-knowledge-core';-import { type Config, resolveContentDir } from '@inkeep/open-knowledge-server';+import {+ auditScopeNotFoundTitle,+ type Config,+ resolveAuditScope,+ resolveContentDir,+} from '@inkeep/open-knowledge-server';import { Command } from 'commander';import { type LintRunResult, runLint } from '../content/lint-runner.ts';import { getInvocationCwd } from '../project-anchor.ts';@@ -33,6 +41,22 @@ export function lintCommand(getConfig: () => Config): Command {const projectDir = process.cwd();const contentDir = resolveContentDir(config, projectDir);const targetPath = path === undefined ? undefined : resolveTarget(path, getInvocationCwd());+ const resolution = resolveAuditScope(targetPath, contentDir);+ if (!resolution.ok) {+ const problem: ProblemDetails = {+ type: 'urn:ok:error:not-found',+ title:+ path === undefined || resolution.path === contentDir+ ? resolution.title+ : auditScopeNotFoundTitle(path),+ status: 404,+ instance: `urn:uuid:${randomUUID()}`,+ };+ if (opts.json === true) process.stdout.write(`${JSON.stringify(problem, null, 2)}\n`);+ else process.stderr.write(`${problem.title}\n`);+ process.exitCode = 1;+ return;+ }const persistedLinter = config.contentRules as PersistedLinterConfig | undefined;const baseConfig: LinterConfig = persistedLinter? toEffectiveBase(persistedLinter)@@ -43,6 +67,7 @@ export function lintCommand(getConfig: () => Config): Command {contentDir,baseConfig,targetPath,+ resolvedScope: resolution.scope,fix: opts.fix === true,});@@ -107,7 +132,9 @@ export function formatLintReport(result: LintReportInput): string {}const problemTotal = result.errorCount + result.warningCount;- if (problemTotal === 0) {+ if (result.fileCount === 0) {+ lines.push(dim('No documents were checked.'));+ } else if (problemTotal === 0) {lines.push(success(`✓ No problems in ${result.fileCount} file${result.fileCount === 1 ? '' : 's'}.`),);@@ -122,10 +149,13 @@ export function formatLintReport(result: LintReportInput): string {if (result.fixedCount > 0) {lines.push(dim(`Fixed ${result.fixedCount} file${result.fixedCount === 1 ? '' : 's'}.`));}- lines.push(...validationCoverageLines(result.ran).map((line) => dim(line)));+ const coverage = validationCoverageLines(result.ran, result.fileCount);+ lines.push(...coverage.map((line) => dim(line)));if (result.warnings.length > 0) {lines.push('');- for (const w of result.warnings) lines.push(yellow(`! ${w}`));+ for (const warning of result.warnings) {+ lines.push(isAuditEmptyScopeWarning(warning) ? dim(warning) : yellow(`! ${warning}`));+ }}return lines.join('\n');diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.tsindex 7553dcda1..9b901331e 100644--- a/packages/cli/src/commands/repair-skills.ts+++ b/packages/cli/src/commands/repair-skills.ts@@ -807,7 +807,7 @@ function formatRepairSkillsResult(result: RepairSkillsResult): string {export function repairSkillsCommand(): Command {return new Command('repair-skills').description(- 'Refresh bundled SKILL.md files for installed AI editors (project-local + user-global). Runs automatically during `ok start`; this command forces an explicit sweep.',+ 'Restore missing project skill copies and repair user-global bundles for installed AI editors. Existing project skills are preserved; run `ok init` to refresh them.',).option('-y, --yes',diff --git a/packages/cli/src/content/lint-runner.test.ts b/packages/cli/src/content/lint-runner.test.tsindex 7c615f327..d7ea1ead6 100644--- a/packages/cli/src/content/lint-runner.test.ts+++ b/packages/cli/src/content/lint-runner.test.ts@@ -1,7 +1,15 @@-import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { DEFAULT_LINTER_CONFIG } from '@inkeep/open-knowledge-core';+import { AUDIT_EMPTY_SCOPE_WARNING, DEFAULT_LINTER_CONFIG } from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { lintDoc } from '../../../server/src/lint/audit.ts';import { runLint } from './lint-runner.ts';@@ -113,6 +121,118 @@ describe('runLint — scope', () => {expect(result.files.map((f) => f.file)).toEqual([join('sub', 'b.md')]);});+ test('uses mdx-first extensionless resolution and preserves explicit suffixes', async () => {+ write('guide.md', '# MD\n\na\tb\n');+ write('guide.mdx', '# MDX\n\nc\td\n');+ const short = await run({ targetPath: join(root, 'guide') });+ expect(short).toEqual(await run({ targetPath: join(root, 'guide.mdx') }));+ expect(short.files.map((file) => file.file)).toEqual(['guide.mdx']);+ expect(+ (await run({ targetPath: join(root, 'guide.md') })).files.map((file) => file.file),+ ).toEqual(['guide.md']);+ });++ test('resolves a dotted document stem through the shared scope resolver', async () => {+ write('notes/v1.2.md', '# MD\n\na\tb\n');+ write('notes/v1.2.mdx', '# MDX\n\nc\td\n');+ const short = await run({ targetPath: join(root, 'notes/v1.2') });+ expect(short.files.map((file) => file.file)).toEqual(['notes/v1.2.mdx']);+ expect(short).toEqual(await run({ targetPath: join(root, 'notes/v1.2.mdx') }));+ });++ test('reports an ignored directory as zero coverage without fixing its files', async () => {+ write('.gitignore', 'ignored/\n');+ write('ignored/guide.md', '# Guide\n\na\tb\n');+ const result = await run({ targetPath: join(root, 'ignored'), fix: true });+ expect(result).toMatchObject({+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ fixedCount: 0,+ warnings: ['No documents were checked: this scope contains no admitted documents.'],+ });+ expect(readFileSync(join(root, 'ignored/guide.md'), 'utf8')).toContain('a\tb');+ });++ test('reports zero coverage alongside a schema warning', async () => {+ mkdirSync(join(root, 'empty'));+ const result = await run({+ targetPath: join(root, 'empty'),+ baseConfig: {+ ...DEFAULT_LINTER_CONFIG,+ plugins: {+ ...DEFAULT_LINTER_CONFIG.plugins,+ frontmatter: {+ enabled: true,+ schemas: [{ appliesTo: '**', file: '.ok/schemas/missing.json' }],+ },+ },+ },+ });+ expect(result.fileCount).toBe(0);+ expect(result.warnings).toEqual([+ expect.stringContaining('missing.json'),+ AUDIT_EMPTY_SCOPE_WARNING,+ ]);+ });++ test('does not classify an unreadable directory as an empty admitted scope', async () => {+ const result = await run({+ resolvedScope: { kind: 'dir', path: join(root, 'missing') },+ });+ expect(result.fileCount).toBe(0);+ expect(result.warnings).toEqual([expect.stringContaining('could not read directory missing')]);+ });++ test.each(['.gitignore', '.okignore'])(+ 'lints and fixes explicitly requested files excluded by %s',+ async (ignoreFile) => {+ write(ignoreFile, 'ignored/\n');+ for (const path of ['ignored/guide.md', 'ignored/guide.mdx', 'ignored/plain']) {+ write(path, '# Guide\n\na\tb\n');+ const linted = await run({ targetPath: join(root, path) });+ expect(linted.fileCount).toBe(1);+ expect(linted.files.map((file) => file.file)).toEqual([path]);+ expect(linted.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010')).toBe(+ true,+ );+ expect(linted.warnings).toEqual([]);+ const fixed = await run({ targetPath: join(root, path), fix: true });+ expect(fixed.fixedCount).toBe(1);+ expect(fixed.files[0]?.fixed).toBe(true);+ expect(readFileSync(join(root, path), 'utf8')).not.toContain('\t');+ }+ },+ );++ test('an unknown explicit suffix rejects before fixing an existing alternate suffix', async () => {+ write('guide.mdx', '# Guide\n\na\tb\n');+ await expect(run({ targetPath: join(root, 'guide.md'), fix: true })).rejects.toThrow(+ 'was not found',+ );+ expect(readFileSync(join(root, 'guide.mdx'), 'utf8')).toContain('a\tb');+ });++ test('a missing content directory fails without fixing a sibling document', async () => {+ write('content.md', '# Sibling\n\na\tb\n');+ await expect(run({ contentDir: join(root, 'content'), fix: true })).rejects.toThrow(+ 'Set content.dir to an existing directory.',+ );+ expect(readFileSync(join(root, 'content.md'), 'utf8')).toContain('a\tb');+ });++ test.each(['overlong segment', 'symlink loop'])(+ 'teaches how to repair a scope with a %s',+ async (kind) => {+ const target = kind === 'overlong segment' ? 'x'.repeat(300) : 'loop';+ if (kind === 'symlink loop') symlinkSync(join(root, target), join(root, target));+ await expect(run({ targetPath: join(root, target) })).rejects.toThrow(+ 'Use an existing file or directory',+ );+ },+ );+test('scopes to a single file', async () => {write('a.md', '# A\n\na\tb\n');write('b.md', '# B\n');diff --git a/packages/cli/src/content/lint-runner.ts b/packages/cli/src/content/lint-runner.tsindex 42958fd4a..f1d3c4f9d 100644--- a/packages/cli/src/content/lint-runner.ts+++ b/packages/cli/src/content/lint-runner.ts@@ -1,13 +1,7 @@+import { readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, sep } from 'node:path';import {- readdirSync,- readFileSync,- renameSync,- statSync,- unlinkSync,- writeFileSync,-} from 'node:fs';-import { dirname, isAbsolute, join, relative, resolve } from 'node:path';-import {+ AUDIT_EMPTY_SCOPE_WARNING,deriveValidationRunSources,fixDocument,type LintDiagnostic,@@ -20,9 +14,11 @@ import {} from '@inkeep/open-knowledge-core';import { atomicTempPath } from '@inkeep/open-knowledge-core/server';import {+ type AuditScope,composeEffectiveLinterConfig,composeFrontmatterSchemasConfig,createContentFilter,+ resolveAuditScope,resolveNativeConfigForDoc,} from '@inkeep/open-knowledge-server';@@ -48,12 +44,19 @@ export interface RunLintOptions {contentDir: string;baseConfig: LinterConfig;targetPath?: string;+ resolvedScope?: AuditScope;fix?: boolean;}export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {const { projectDir, contentDir, baseConfig, targetPath, fix = false } = opts;+ const resolution =+ opts.resolvedScope === undefined+ ? resolveAuditScope(targetPath, contentDir)+ : { ok: true as const, scope: opts.resolvedScope };+ if (!resolution.ok) throw new Error(resolution.title);+ const scope = resolution.scope;const warnings: string[] = [];const filter = createContentFilter({ projectDir, contentDir });@@ -83,10 +86,14 @@ export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {};const docFiles: string[] = [];- const scope = resolveScope(targetPath, contentDir);+ let scanIncomplete = false;+ const scopeRel = relative(contentDir, scope.path);+ const explicitHidden = scopeRel+ .split(sep)+ .some((segment) => segment.startsWith('.') && segment !== '..');if (scope.kind === 'file') {- docFiles.push(relative(contentDir, scope.path));- } else {+ docFiles.push(scopeRel);+ } else if (scopeRel === '' || explicitHidden || !filter.isDirExcluded(scopeRel)) {walk(scope.path);}@@ -95,6 +102,7 @@ export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {try {entries = readdirSync(absDir, { withFileTypes: true });} catch (e) {+ scanIncomplete = true;warnings.push(`could not read directory ${relative(contentDir, absDir) || '.'}: ${errMsg(e)}`,);@@ -116,6 +124,7 @@ export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {}docFiles.sort();+ if (docFiles.length === 0 && !scanIncomplete) warnings.push(AUDIT_EMPTY_SCOPE_WARNING);const files: FileLintResult[] = [];let errorCount = 0;@@ -175,17 +184,6 @@ export async function runLint(opts: RunLintOptions): Promise<LintRunResult> {};}-type Scope = { kind: 'dir' | 'file'; path: string };--function resolveScope(targetPath: string | undefined, contentDir: string): Scope {- if (targetPath === undefined || targetPath === '') return { kind: 'dir', path: contentDir };- const abs = isAbsolute(targetPath) ? targetPath : resolve(contentDir, targetPath);- try {- if (statSync(abs).isFile()) return { kind: 'file', path: abs };- } catch {}- return { kind: 'dir', path: abs };-}-function isDocFile(name: string): boolean {const lower = name.toLowerCase();return SUPPORTED_DOC_EXTENSIONS.some((ext) => lower.endsWith(ext));diff --git a/packages/cli/src/mcp/server.autostart.test.ts b/packages/cli/src/mcp/server.autostart.test.tsnew file mode 100644index 000000000..f76137899--- /dev/null+++ b/packages/cli/src/mcp/server.autostart.test.ts@@ -0,0 +1,90 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { expect, test } from 'vitest';++test.each(['disabled', 'failed-start'])(+ 'ok mcp teaches manual startup on a real tool call when autostart is %s',+ async (mode) => {+ const project = mkdtempSync(join(tmpdir(), 'ok-mcp-autostart-'));+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');+ mkdirSync(join(project, '.ok'));+ writeFileSync(join(project, '.ok/config.yml'), '{}\n');+ const launcher = join(project, 'launcher.mjs');+ writeFileSync(+ launcher,+ `if (process.argv[2] === 'start') { process.stderr.write('fixture startup failed\\n'); process.exitCode = 1; } else { await import(${JSON.stringify(pathToFileURL(join(packageRoot, 'src/cli.ts')).href)}); }\n`,+ );+ const client = new Client({ name: 'autostart-recovery-test', version: '1.0.0' });+ const transport = new StdioClientTransport({+ command: process.execPath,+ args: [+ '--import',+ 'tsx',+ '--conditions=development',+ launcher,+ '--cwd',+ project,+ '--log-level',+ 'silent',+ 'mcp',+ '--no-bundle-proxy',+ ],+ cwd: packageRoot,+ env: {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ (entry): entry is [string, string] => entry[1] !== undefined,+ ),+ ),+ OK_MCP_AUTOSTART: mode === 'disabled' ? '0' : '1',+ OK_MCP_SPAWN_TIMEOUT_MS: '5000',+ OK_BUNDLE_PROXY: '0',+ },+ stderr: 'pipe',+ });+ try {+ await client.connect(transport);+ const result = await client.callTool({+ name: 'write',+ arguments: { cwd: project, document: { path: 'draft', content: '# Draft\n' } },+ });+ expect(result.isError).toBe(true);+ expect(result.content).toEqual([+ expect.objectContaining({+ type: 'text',+ text: expect.stringContaining('Run `ok start` in the target project'),+ }),+ ]);+ expect(result.content).toEqual([+ expect.objectContaining({ text: expect.stringContaining('retry this tool') }),+ ]);+ expect(result.content).toEqual([+ expect.objectContaining({+ text: expect.stringContaining(+ 'Do not fall back to native file edits for OpenKnowledge content',+ ),+ }),+ ]);+ if (mode === 'failed-start') {+ expect(result.content).toEqual([+ expect.objectContaining({+ text: expect.stringContaining(+ 'server did not start within 5000ms stderr:\nfixture startup failed',+ ),+ }),+ ]);+ }+ expect(existsSync(join(project, 'draft.md'))).toBe(false);+ expect(existsSync(join(project, '.ok/local/server.lock'))).toBe(false);+ } finally {+ await client.close();+ await transport.close();+ rmSync(project, { recursive: true, force: true });+ }+ },+ 30_000,+);diff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.tsindex 0dbbebb2b..10c511011 100644--- a/packages/cli/src/mcp/shim.test.ts+++ b/packages/cli/src/mcp/shim.test.ts@@ -232,8 +232,31 @@ describe('MCP stdio shim server resolution', () => {}).catch((e: unknown) => e);expect(err).toBeInstanceOf(AutoStartDisabledError);expect((err as Error).message).toContain('OK_MCP_AUTOSTART=0');+ expect((err as Error).message).toContain('Run `ok start` in the target project');+ expect((err as Error).message).toContain('then retry this tool');+ expect((err as Error).message).toContain('native file edits for OpenKnowledge content');});+ test.each(['missing', 'overlong'])(+ 'native spawn failure for a %s working directory teaches recovery',+ async (kind) => {+ const err: unknown = await resolveMcpHttpUrl({+ lockDir,+ contentDir: resolve(tmp, kind === 'missing' ? 'missing' : 'x'.repeat(32768)),+ timeoutMs: 1000,+ pollIntervalMs: 1,+ }).catch((error: unknown) => error);++ expect(err).toBeInstanceOf(Error);+ expect(err).not.toBeInstanceOf(AutoStartDisabledError);+ expect((err as Error).message).toContain('spawn failed:');+ expect((err as Error).message).toMatch(/ENOENT|ENAMETOOLONG/);+ expect((err as Error).message).toContain('Run `ok start` in the target project');+ expect((err as Error).message).toContain('then retry this tool');+ expect((err as Error).message).toContain('native file edits for OpenKnowledge content');+ },+ );+test('valid port override bypasses discovery and targets the default loopback host', async () => {const url = await resolveMcpHttpUrl({lockDir,diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.tsindex 3109d7798..253441908 100644--- a/packages/cli/src/mcp/shim.ts+++ b/packages/cli/src/mcp/shim.ts@@ -29,6 +29,8 @@ import { resolveSelfSpawn } from '../commands/self-spawn.ts';const DEFAULT_SPAWN_TIMEOUT_MS = 5000;const DEFAULT_POLL_INTERVAL_MS = 100;const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;+const SERVER_START_RECOVERY =+ 'Run `ok start` in the target project, then retry this tool. Do not fall back to native file edits for OpenKnowledge content.';interface ShimTransport {onerror: ((err: Error) => void) | undefined;@@ -155,7 +157,7 @@ function readErrorLogDefault(path: string): string {function formatTimeoutMessage(timeoutMs: number, stderr: string): string {const stderrBlock = stderr ? ` stderr:\n${stderr}` : '';- return `server did not start within ${timeoutMs}ms${stderrBlock}`;+ return `server did not start within ${timeoutMs}ms${stderrBlock}\n${SERVER_START_RECOVERY}`;}function requestIdOf(message: JSONRPCMessage): RequestId | undefined {@@ -212,7 +214,7 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promiseif (opts.envAutoStart === '0') {throw new AutoStartDisabledError(- 'OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.',+ `OpenKnowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start. ${SERVER_START_RECOVERY}`,);}@@ -274,7 +276,7 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promiseif (asyncSpawnError) {const stderr = readErrorLog(stderrPath);const stderrBlock = stderr ? ` stderr:\n${stderr}` : '';- throw new Error(`spawn failed: ${asyncSpawnError}${stderrBlock}`);+ throw new Error(`spawn failed: ${asyncSpawnError}${stderrBlock}\n${SERVER_START_RECOVERY}`);}await sleep(pollIntervalMs);const base = liveBaseUrlFromLock(readLock(), isAlive);@@ -284,7 +286,7 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promiseif (asyncSpawnError) {const stderr = readErrorLog(stderrPath);const stderrBlock = stderr ? ` stderr:\n${stderr}` : '';- throw new Error(`spawn failed: ${asyncSpawnError}${stderrBlock}`);+ throw new Error(`spawn failed: ${asyncSpawnError}${stderrBlock}\n${SERVER_START_RECOVERY}`);}throw new Error(formatTimeoutMessage(timeoutMs, readErrorLog(stderrPath)));diff --git a/packages/cli/src/project-anchor.test.ts b/packages/cli/src/project-anchor.test.tsindex 5c08e0ef6..af08ad627 100644--- a/packages/cli/src/project-anchor.test.ts+++ b/packages/cli/src/project-anchor.test.ts@@ -35,6 +35,10 @@ describe('resolveProjectAnchor — command gating', () => {},);+ test.each(['lint', 'audit'])('anchors validation command %s', (name) => {+ expect(resolveProjectAnchor(name, '/proj/sub/dir', stubHit)).toBe('/proj');+ });+test('anchors the bare-`ok` dispatch (undefined command name)', () => {expect(resolveProjectAnchor(undefined, '/proj/sub/dir', stubHit)).toBe('/proj');});diff --git a/packages/cli/src/project-anchor.ts b/packages/cli/src/project-anchor.tsindex 0d0812787..b42287c04 100644--- a/packages/cli/src/project-anchor.ts+++ b/packages/cli/src/project-anchor.ts@@ -9,6 +9,7 @@ const PROJECT_ANCHORED_COMMANDS: ReadonlySet<string> = new Set(['mcp','preview','lint',+ 'audit','deinit','auth',]);diff --git a/packages/core/src/constants/mcp.ts b/packages/core/src/constants/mcp.tsindex 7c54e8f10..f70f6c718 100644--- a/packages/core/src/constants/mcp.ts+++ b/packages/core/src/constants/mcp.ts@@ -28,8 +28,6 @@ export const OPEN_KNOWLEDGE_MCP_TOOLS = ['import','checkpoint','restore_version',- 'conflicts',- 'resolve_conflict',] as const;export type OpenKnowledgeMcpTool = (typeof OPEN_KNOWLEDGE_MCP_TOOLS)[number];@@ -43,7 +41,6 @@ export const OPEN_KNOWLEDGE_MCP_WRITE_TOOLS = ['import','checkpoint','restore_version',- 'resolve_conflict',] as const satisfies ReadonlyArray<OpenKnowledgeMcpTool>;export const OK_HOSTED_AGENT_ENV = 'OK_HOSTED_AGENT';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 5b2178484..70d5a148d 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -902,6 +902,7 @@ export { MarkdownManager, type SerializeCallOptions } from './markdown/index.ts'export {type AppliesToPatternSummary,type AppliesToSummary,+ AUDIT_EMPTY_SCOPE_WARNING,applyFieldConstraint,applyTextEdits,assertNeverOkfRuleGroupId,@@ -935,6 +936,7 @@ export {fixMarkdownText,frontmatterSchemaCompileError,type GoverningFrontmatterSchema,+ isAuditEmptyScopeWarning,isFrontmatterSchemaAsset,isFrontmatterScoped,isMarkdownlintJsonConfig,@@ -1110,8 +1112,6 @@ export {getCanonicalDescriptors,projectFull,projectLite,- renderInventoryFooter,- renderInventoryList,} from './registry/projection.ts';export type {ClipboardHastContext,@@ -2127,6 +2127,7 @@ export { isVimeoUrl } from './utils/vimeo-embed.ts';export {buildPagesByBasenameIndex,buildPagesBySlugIndex,+ buildWikiLinkAssetTargetKeys,getWikiLinkResolutionCandidates,isResolvedWikiLinkTarget,resolveWikiLinkAssetTarget,diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex a205a28ce..8577e5ceb 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -242,7 +242,9 @@ export {ZERO_SOURCE_COUNTS,} from './validation-counts.ts';export {+ AUDIT_EMPTY_SCOPE_WARNING,deriveValidationRunSources,+ isAuditEmptyScopeWarning,type ValidationRunMode,validationCoverageLines,} from './validation-run-sources.ts';diff --git a/packages/core/src/markdown/lint/validation-run-sources.ts b/packages/core/src/markdown/lint/validation-run-sources.tsindex 0e527eebb..a78df85dd 100644--- a/packages/core/src/markdown/lint/validation-run-sources.ts+++ b/packages/core/src/markdown/lint/validation-run-sources.ts@@ -25,7 +25,22 @@ export function deriveValidationRunSources(return sources;}-export function validationCoverageLines(ran: readonly string[] | undefined): string[] {+export const AUDIT_EMPTY_SCOPE_WARNING =+ 'No documents were checked: this scope contains no admitted documents.';++export function isAuditEmptyScopeWarning(warning: string): boolean {+ return warning === AUDIT_EMPTY_SCOPE_WARNING;+}++export function validationCoverageLines(+ ran: readonly string[] | undefined,+ fileCount?: number,+): string[] {+ if (fileCount === 0) {+ return ran !== undefined && ran.length > 0+ ? [`Checks selected: ${ran.join(', ')}; no document checks ran.`]+ : ['No document checks ran.'];+ }if (ran === undefined) return [];if (ran.length === 0) return ['No checks ran.'];return [`Checks run: ${ran.join(', ')}.`];diff --git a/packages/core/src/registry/projection.test.ts b/packages/core/src/registry/projection.test.tsindex 98888da39..00ee9bc3d 100644--- a/packages/core/src/registry/projection.test.ts+++ b/packages/core/src/registry/projection.test.ts@@ -7,7 +7,6 @@ import {getCanonicalDescriptors,projectFull,projectLite,- renderInventoryFooter,} from './projection.ts';const PARSE_EXTENSIONS = [mdx()];@@ -145,42 +144,3 @@ describe('projectFull — example + form-aware params (FR-11)', () => {expect(full.example).toContain('</Tabs>');});});--describe('renderInventoryFooter (FR-1)', () => {- test('mentions every agent-facing canonical id', () => {- const text = renderInventoryFooter();- for (const d of getAgentCanonicalDescriptors()) {- expect(text).toContain(`\`${d.name}\``);- }- });-- test('does NOT list MermaidFence (fence-kind excluded from agent surface)', () => {- const text = renderInventoryFooter();- expect(text).not.toContain('`MermaidFence`');- });-- test('carries the look-up pointer to palette', () => {- const text = renderInventoryFooter();- expect(text).toContain('palette');- });-- test('mentions fenced code blocks as a separate authoring path (not a component)', () => {- const text = renderInventoryFooter();- expect(text).toContain('Fenced code blocks');- });-- test('carries the wildcard tolerance contract for no-canonical-fits authoring', () => {- const text = renderInventoryFooter();- expect(text).toContain('<TagName>');- });-- test('stays under 3.5KB at N=11 (NFR performance bound — extra ~600 bytes covers the fenced-code-block authoring guidance + the Embed→video-block steer for YouTube/Vimeo/Loom URLs added per PRD-7069)', () => {- const text = renderInventoryFooter();- expect(text.length).toBeLessThan(3584);- });-- test('mentions the `html preview` fence affordance for interactive content', () => {- const text = renderInventoryFooter();- expect(text).toContain('```html preview');- });-});diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.tsindex 8ba35ac7a..a0587b4ea 100644--- a/packages/core/src/registry/projection.ts+++ b/packages/core/src/registry/projection.ts@@ -186,22 +186,3 @@ export function projectFull(descriptor: JsxComponentMeta): ComponentEntryFull {params: projectParams(descriptor),};}--export function renderInventoryList(): string {- const lite = getAgentCanonicalDescriptors().map(projectLite);- const lines = lite.map((entry) => `- \`${entry.id}\` (${entry.kind}) — ${entry.description}`);- return [- '',- '**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below. For source syntax + parameter schemas, call `palette({ components: [ids] })`. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.',- '',- ...lines,- ].join('\n');-}--export function renderInventoryFooter(): string {- return [- renderInventoryList(),- '',- 'Fenced code blocks render naturally and don\'t need a fetch — including ` ```mermaid ` for diagrams (mermaid label text has sharp edges — `palette({ components: ["Mermaid"] })` lists them; parse failures come back as `warnings` entries on write/edit) and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader\'s light/dark theme.',- ].join('\n');-}diff --git a/packages/core/src/utils/wiki-link-resolve.test.ts b/packages/core/src/utils/wiki-link-resolve.test.tsindex 8651688ce..388136276 100644--- a/packages/core/src/utils/wiki-link-resolve.test.ts+++ b/packages/core/src/utils/wiki-link-resolve.test.ts@@ -4,6 +4,7 @@ import { toWikiLinkSlug } from './slug.ts';import {buildPagesByBasenameIndex,buildPagesBySlugIndex,+ buildWikiLinkAssetTargetKeys,isResolvedWikiLinkTarget,resolveWikiLinkAssetTarget,resolveWikiLinkTarget,@@ -178,11 +179,59 @@ describe('wiki-link resolution equivalence corpus', () => {});});+describe('indexed asset target keys', () => {+ test('answer every asset target exactly as the path scan does', () => {+ const assetPaths = new Set(['images/Cover.PNG', 'docs/guide.pdf']);+ const filePaths = new Set(['data/Table.csv']);+ const scanned: WikiLinkLookupIndex = {+ pages: new Set(['notes/a']),+ pagesBySlug: new Map(),+ pagesByBasename: new Map(),+ assetPaths,+ filePaths,+ };+ const keyed: WikiLinkLookupIndex = {+ ...scanned,+ assetTargetKeys: buildWikiLinkAssetTargetKeys(assetPaths, filePaths),+ };+ for (const [target, expected] of [+ ['Cover.PNG', true],+ ['cover.png', true],+ ['/images/cover.png?x#y', true],+ ['IMAGES/COVER.PNG', true],+ ['guide.pdf#page=2', true],+ ['table.csv', true],+ ['data/table.csv', true],+ ['missing.png', false],+ ['images/missing.png', false],+ ['other/cover.png', false],+ ] as const) {+ expect(isResolvedWikiLinkTarget(target, scanned), target).toBe(expected);+ expect(isResolvedWikiLinkTarget(target, keyed), target).toBe(expected);+ }+ });+});+describe('derived index construction', () => {- test('slug index keys the full docName and keeps the first entry on collision', () => {- const index = buildPagesBySlugIndex(new Set(['README', 'ReadMe']), toWikiLinkSlug);- expect(index.get('readme')).toBe('README');- expect(index.size).toBe(1);+ test('slug collisions choose the code-unit minimum regardless of inventory order', () => {+ for (const order of [+ ['a/b', 'a-b'],+ ['a-b', 'a/b'],+ ]) {+ const pages = new Set(order);+ const index: WikiLinkLookupIndex = {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ expect(index.pagesBySlug.get('a-b')).toBe('a-b');+ for (const input of [pages, index]) {+ for (const spelling of ['A B', 'A B.md', 'A B.mdx']) {+ expect(resolveWikiLinkTargetDocName(spelling, input)).toBe('a-b');+ }+ expect(resolveWikiLinkTargetDocName('a/b', input)).toBe('a/b');+ }+ }});test('basename index keys the leaf segment so a bare name finds a subfolder doc', () => {@@ -414,3 +463,36 @@ describe('composed wiki-link resolution', () => {});});});++describe('explicit Markdown suffix precedence', () => {+ test.each([+ ['x.md', ['x', 'x.md'], 'x.md'],+ ['x.md.md', ['x', 'x.md', 'x.md.md'], 'x.md.md'],+ ['x.md.md', ['x', 'x.md'], 'x.md'],+ ['x.md.md', ['x'], undefined],+ ['notes/beta.md', ['notes/beta', 'notes/beta-md'], 'notes/beta'],+ ['notes/beta.md', ['Notes/Beta', 'notes/beta-md'], 'Notes/Beta'],+ ['Beta Guide.MDX', ['notes/Beta Guide', 'beta-guide-mdx'], 'notes/Beta Guide'],+ ['reports.md', ['reports/index', 'reports-md'], 'reports/index'],+ ['reports.mdx', ['reports/reports', 'reports-mdx'], 'reports/reports'],+ ['beta.md', ['notes/beta', 'beta-md'], 'notes/beta'],+ ['notes/beta.md', ['notes/beta-md'], 'notes/beta-md'],+ ['beta.md', ['notes/beta-md'], 'notes/beta-md'],+ ['reports.md', ['reports.md/index'], 'reports.md/index'],+ ['missing.md', ['notes/exists'], undefined],+ ] satisfies Array<[string, string[], string | undefined]>)(+ '%s in %j resolves to %s',+ (target, docNames, expected) => {+ const pages = new Set(docNames);+ const index: WikiLinkLookupIndex = {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ for (const input of [pages, index]) {+ expect(resolveWikiLinkTargetDocName(target, input)).toBe(expected);+ expect(isResolvedWikiLinkTarget(target, input)).toBe(expected !== undefined);+ }+ },+ );+});diff --git a/packages/core/src/utils/wiki-link-resolve.ts b/packages/core/src/utils/wiki-link-resolve.tsindex 8e9706118..0c786bfc9 100644--- a/packages/core/src/utils/wiki-link-resolve.ts+++ b/packages/core/src/utils/wiki-link-resolve.ts@@ -11,6 +11,7 @@ export interface WikiLinkLookupIndex {readonly pagesBySlug: ReadonlyMap<string, string>;readonly pagesByBasename?: ReadonlyMap<string, string>;readonly assetPaths?: ReadonlySet<string>;+ readonly assetTargetKeys?: ReadonlySet<string>;readonly filePaths?: ReadonlySet<string>;}@@ -45,7 +46,10 @@ export function buildPagesBySlugIndex(const index = new Map<string, string>();for (const page of pages) {const key = slugFn(page);- if (key && !index.has(key)) index.set(key, page);+ const previous = index.get(key);+ if (key && (previous === undefined || compareDocNames(page, previous) < 0)) {+ index.set(key, page);+ }}return index;}@@ -71,10 +75,12 @@ function slugLookup(target: string, input: WikiLinkPagesInput): string | undefinif (isLookupIndex(input)) {return input.pagesBySlug.get(targetSlug);}+ let bestMatch: string | undefined;for (const page of input) {- if (toWikiLinkSlug(page) === targetSlug) return page;+ if (toWikiLinkSlug(page) !== targetSlug) continue;+ if (bestMatch === undefined || compareDocNames(page, bestMatch) < 0) bestMatch = page;}- return undefined;+ return bestMatch;}function basenameLookup(target: string, input: WikiLinkPagesInput): string | undefined {@@ -104,6 +110,22 @@ export function getWikiLinkResolutionCandidates(target: string): string[] {export function resolveWikiLinkTargetDocName(target: string,input: WikiLinkPagesInput,+): string | undefined {+ const trimmed = target.trim();+ if (!trimmed) return undefined;+ const pages = getPagesSet(input);+ if (pages.has(trimmed)) return trimmed;+ const withoutMarkdownSuffix = trimmed.replace(/\.(md|mdx)$/i, '');+ if (withoutMarkdownSuffix !== trimmed) {+ const strippedMatch = resolveWikiLinkDocNameWithoutSuffixFallback(withoutMarkdownSuffix, input);+ if (strippedMatch !== undefined) return strippedMatch;+ }+ return resolveWikiLinkDocNameWithoutSuffixFallback(trimmed, input);+}++function resolveWikiLinkDocNameWithoutSuffixFallback(+ target: string,+ input: WikiLinkPagesInput,): string | undefined {const trimmed = target.trim();if (!trimmed) return undefined;@@ -169,6 +191,20 @@ export function resolveWikiLinkAssetTarget(return matches.sort(compareDocNames)[0] ?? null;}+export function buildWikiLinkAssetTargetKeys(+ ...partitions: ReadonlyArray<Iterable<string>>+): ReadonlySet<string> {+ const keys = new Set<string>();+ for (const partition of partitions) {+ for (const path of partition) {+ const lower = path.toLowerCase();+ keys.add(`path:${lower}`);+ keys.add(`basename:${lower.slice(lower.lastIndexOf('/') + 1)}`);+ }+ }+ return keys;+}+export function isResolvedWikiLinkTarget(target: string,pages: WikiLinkPagesInput,@@ -177,7 +213,15 @@ export function isResolvedWikiLinkTarget(): boolean {const trimmed = target.trim();if (!trimmed) return false;- if (+ const normalizedAsset = normalizeAssetTarget(trimmed).toLowerCase();+ const indexedAsset = isLookupIndex(pages) ? pages.assetTargetKeys : undefined;+ if (indexedAsset !== undefined) {+ if (+ indexedAsset.has(`path:${normalizedAsset}`) ||+ (!normalizedAsset.includes('/') && indexedAsset.has(`basename:${normalizedAsset}`))+ )+ return true;+ } else if (resolveWikiLinkAssetTarget(trimmed,getAssetPathsSet(pages, assetPaths),@@ -187,18 +231,7 @@ export function isResolvedWikiLinkTarget(return true;}- const pagesSet = getPagesSet(pages);- if (pagesSet.has(trimmed)) return true;-- if (getWikiLinkResolutionCandidates(trimmed).some((candidate) => pagesSet.has(candidate))) {- return true;- }-- if (slugLookup(trimmed, pages) !== undefined) return true;-- if (resolveFolderIndexDocName(trimmed, pagesSet)) return true;-- return basenameLookup(trimmed, pages) !== undefined;+ return resolveWikiLinkTargetDocName(trimmed, pages) !== undefined;}export function resolveWikiLinkTarget(diff --git a/packages/server/assets/skills/packs/entity-vault/SKILL.md b/packages/server/assets/skills/packs/entity-vault/SKILL.mdindex 8d899ebc7..b27737820 100644--- a/packages/server/assets/skills/packs/entity-vault/SKILL.md+++ b/packages/server/assets/skills/packs/entity-vault/SKILL.md@@ -36,7 +36,7 @@ Per the platform skill, prefer **standard markdown links** for new dossiers, andTwo deltas from the platform default, both GBrain-specific:- **Don't use the leading-slash root-absolute form** (`[Alice](/people/alice-chen.md)`). OK resolves it fine, but GBrain reads a leading `/` as an absolute filesystem path and rejects it — use a relative path. (GBrain also accepts a bare `[Alice](people/alice-chen.md)`, but from a subfolder OK resolves that *source-dir-relative* — `meetings/people/alice-chen` — and reports it broken, so stick to the `../`-correct relative form, which both accept.)-- **Path-qualified wikilinks are first-class here**, not legacy: `[[people/alice-chen|Alice Chen]]` resolves vault-root from any folder (no `../` to count), is validated by `brokenLinks` like any link, and imports into GBrain. Keep them **extensionless** (`[[people/alice-chen]]`, never `[[people/alice-chen.md]]` — the `.md` makes it resolve to a nonexistent doc). A *bare* `[[note-name]]` with no folder is ambiguous (resolves only if GBrain's basename-globbing is on) — reserve it for Obsidian migration.+- **Path-qualified wikilinks are first-class here**, not legacy: `[[people/alice-chen|Alice Chen]]` resolves vault-root from any folder (no `../` to count), is validated by `brokenLinks` like any link, and imports into GBrain. Prefer **extensionless** targets (`[[people/alice-chen]]`) for a consistent wiki-link style; OK also resolves explicit `.md` and `.mdx` suffixes. A *bare* `[[note-name]]` with no folder is ambiguous (resolves only if GBrain's basename-globbing is on) — reserve it for Obsidian migration.## Agent behaviorsdiff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 38a539b99..ddcb510f1 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -19,15 +19,34 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th1. **Reads:** `exec("cat …")` for one doc, `exec("ls -A …")` for a directory (folder defaults + template menu), `exec("grep …")` for literal, `search` for ranked retrieval. Native `Read` / `Grep` only on source code (`.ts` / `.py` / …), never on in-scope `.md` / `.mdx`.2. **Writes:** `write({ document: { path, content } })` for a new or full-replace doc; `edit({ document: { path, find, replace } })` for a body find/replace; `edit({ document: { path, frontmatter } })` for a frontmatter merge-patch (`null` deletes a key). `delete({ document })` removes, `move({ from, to })` moves/renames. Body find/replace is body-only. Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write.3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Stop at first match: **`OK_DESKTOP_TERMINAL` or `OK_HOSTED_AGENT` set** → you're inside OpenKnowledge (desktop terminal / in-app agent panel) → `ok open <name>` (switches the window the user is already looking at); never paste a `localhost` URL into your reply here · in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url`, then open/navigate it to the doc · else plain CLI → `ok open <name>`. `ok open <name>` opens a doc or folder (auto-detected); `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.-4. **Knowledge layers:** capturing a source (ingest), synthesizing findings (research), promoting a decision (consolidate) — procedures, **not tool calls**; there is no `ingest` tool. Ingest ships here (`references/ingest-and-sources.md`); research + consolidate come with the `knowledge-base` pack. Layer model + packs: `references/starter-packs.md`.-5. **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/improve a skill", "turn this into a skill"): STOP and invoke **`/open-knowledge-write-skill`** for scope (project/global), contract, evaluation, and install. Author through `write({ skill })`, never a document path. Skills are real folders under editor `skills/` dirs (`.claude` · `.cursor` · `.codex` · `.github` · `.opencode` · `.pi` · `.agents`): one source plus managed copies/symlinks. **Read/edit via `skills` and `edit({ skill })` — they route to the source.** Never hand-edit a non-source copy: managed copies refresh from the source; editing one forks it and stops refresh.--## Tool index — 21 tools (router; the MCP tool descriptions carry each tool's full contract)--- **Reads** — `exec` (primary; `cat`/`ls`/`grep`/… on a read-only filesystem, plus frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (doc versions), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for one call), `skills` (search + read: `query` → skills.sh; omit `name` to LIST managed (Project + Global); `name` READs one — by `name`+`scope`, never path), `config` (resolved config), `palette` (authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors without a GitHub remote), `lint` (markdown-lint violations: `document` for one doc, omit for the project; `fix: true` with `document` auto-fixes fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`; caveats in `references/linking.md`). **Read `ran` on successful `lint`/`audit` results: a family absent from `ran` was not checked, and `[]` means no checks were selected.**-- **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: {…} })` authors a skill as a REAL folder at the project's default skill home — live immediately for that folder's agent), `edit` (body find/replace/frontmatter merge-patch; no asset), `delete`, `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global: history resets, only what the destination level can host re-projects; the rest is removed at source, returned as `droppedLocations` (success: re-add with `install`)). Output mirrors the input key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (WHERE a `skill` lives: `add`/`remove` locations additively — editor ids, `agents`, or custom roots; `mode` + `convert` re-form ONLY the locations named; `source` moves the real folder. The source folder IS the skill — no "uninstall everywhere"; a skill dies only via `delete`), `import` (acquire a skill-dir into `add`'s locations; scripts never run), `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.-- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution from that conflict's `resolutionOptions`; commits only for `merge-native`; destructive). See `references/conflict-resolution.md`.+4. **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`.+5. **Authoring or improving a skill** ("write/make/improve a skill", "turn this into a skill"): STOP and invoke **`/open-knowledge-write-skill`** for scope (project/global), contract, evaluation, and install. Author through `write({ skill })`, never a document path. Skills are real folders under editor `skills/` dirs (`.claude` · `.cursor` · `.codex` · `.github` · `.opencode` · `.pi` · `.agents`): one source plus managed copies/symlinks. **Read/edit via `skills` and `edit({ skill })` — they route to the source.** Never hand-edit a non-source copy: recorded, unedited copies refresh from the source when the skill watcher runs or the server starts, so a source edit can precede the refresh. Editing a copy directly forks it and stops refresh.++## Tool index — 19 tools (router; calling contracts live in tool descriptions and input schemas)++- `exec` — read files and directories with document context.+- `search` — retrieve ranked workspace matches.+- `links` — inspect link relationships and suggestions.+- `lint` — check content rules and apply automatic fixes.+- `audit` — validate content rules and internal links.+- `write` — create or replace content.+- `edit` — change content or metadata in place.+- `delete` — remove content.+- `move` — rename or relocate content through managed operations.+- `install` — manage skill source and editor locations.+- `import` — acquire a skill folder without running scripts.+- `history` — inspect document, folder or skill versions.+- `skills` — discover, list or read skills by name and scope.+- `checkpoint` — save a named version.+- `restore_version` — restore a document or skill version.+- `palette` — discover components and authoring forms.+- `config` — read resolved configuration.+- `preview_url` — get the browser preview URL.+- `share_link` — get a GitHub-backed sharing link.++**Read `ran`** on successful lint/audit results: a family absent from `ran` was not checked, and `[]` means no checks were selected. For link VALIDATION use audit; links reports relationships and raw dead-link state. Caveats: `references/linking.md`.++Skill placement is separate from skill content: the source folder IS the skill, and removing an installed copy does not delete the skill. For a Project↔Global move, history resets; only what the destination level can host re-projects; the rest is removed at source, returned as `droppedLocations` (success: re-add with install). Read the returned outcome before recovery. A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with.**Self-correcting on misuse:** constraints JSON Schema can't express ("exactly one target", "`find` needs a `replace`", body-XOR-frontmatter) return `isError: true` with a one-line corrective shape. Read it and retry with that shape; don't guess.@@ -50,13 +69,6 @@ Tools NOT in OK MCP (your host's): `preview_start`, `preview_screenshot`, `WebFe**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.-## Reads — examples--- Read a file: `exec("cat <path>.md")` — contents + full enrichment.-- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, the folder's own `title`/`description`/`tags` + `templates_available`. Prefer `-A` over plain `ls`.-- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.-- Ranked search: `search({ query })` — title boost + body BM25 + recency; use when picking the best doc, not when listing every occurrence.-## WritingCall `write` / `edit` as soon as you have content (route through MCP per the STOP rule).@@ -91,7 +103,7 @@ Every `.md` / `.mdx` needs YAML frontmatter — `title` + `description` required## Conflict-aware writes-`doc-in-conflict` freezes writes; `stale-external-write` means recovery missed disk. Detect both with `conflicts`, not `exec`; see `references/conflict-resolution.md`. `concurrent-overwrite-refused` is not conflict state: wait its bound and retry or use `append`/`prepend`/`edit`.+For a conflict refusal, follow the tool's recovery instructions and `references/conflict-resolution.md`; ask the user to resolve tracked conflicts in the app.## Anti-patterns — the top offenders@@ -131,10 +143,6 @@ OK does more than this skill describes, and it changes between releases. Not cov- **Docs** — <https://openknowledge.ai/docs>- **Source** — <https://github.com/inkeep/open-knowledge>-## Server lifecycle--If `write` / `edit` returns `"Hocuspocus server is not running"`, run `ok start` (via Bash) and retry. Never fall back to native `Edit` / `Write` for in-scope markdown.-## Scope recapOK looks for documents under the resolved `content.dir` (runtime: `config({ key: 'content.dir' })`); `.gitignore` and `.okignore` (at root or any folder depth) define exclusions. **Every `.md` / `.mdx` under `content.dir` not excluded is an OpenKnowledge document** — including under `specs/`, `reports/`, `docs/`. Folder metadata + templates live in nested `<folder>/.ok/`, not in `.ok/config.yml`. **Working in a git worktree?** Pass the worktree's absolute path as `cwd` on your OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree.diff --git a/packages/server/assets/skills/project/references/conflict-resolution.md b/packages/server/assets/skills/project/references/conflict-resolution.mdindex ceefc9059..ef774abe2 100644--- a/packages/server/assets/skills/project/references/conflict-resolution.md+++ b/packages/server/assets/skills/project/references/conflict-resolution.md@@ -1,13 +1,13 @@# Conflict-aware writes-A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OK's own reconciliation of the editor against disk. Reconciliation also protects an acknowledged edit when another app restores the exact older file version; that `stale-external-write` path works with GitHub sync disabled. `ConflictAuthority` tracks every kind, and the MCP server refuses a mutating call against a conflicted doc with a structured RFC 9457 response:+A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OK's own reconciliation of the editor against disk. Reconciliation also protects an acknowledged edit when another app restores the exact older file version; that `stale-external-write` path works with GitHub sync disabled. The MCP server refuses a mutating call against a conflicted doc with a structured RFC 9457 response:```json{"type": "urn:ok:error:doc-in-conflict","title": "Document is in conflict.","status": 409,- "detail": "The document is in a conflict state. Call conflicts({ kind: \"content\" }) + resolve_conflict before retrying.",+ "detail": "The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.","file": "notes/sso.md","conflict": { "kind": "reconcile", "reason": "disk-markers" },"resolutionOptions": ["mine", "content", "delete"]@@ -16,9 +16,9 @@ A doc can land in conflict through a Git merge, a pull that collides with a locaThe gate covers `write`, `edit`, `delete`, `move`, `restore_version`, and agent undo (the doc-CRDT write spine; template/folder ops are fs-direct). You cannot route around it by writing content that byte-matches one of the stages. The gate refuses on tracked state, not on body equality.-A write that first detects a stale file during its final disk flush returns `urn:ok:error:stale-external-write` (409). The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Resolve and re-read before deciding whether to repeat the operation; a retried append can duplicate content already retained in `ours`.+A write that first detects a stale file during its final disk flush returns `urn:ok:error:stale-external-write` (409). The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Ask the user to resolve it in the app, then re-read. Do not repeat the operation: a retried append can duplicate content already retained in the current version.-**Detect proactively.** Call `conflicts({ kind: 'list' })` before a batch of writes. An `exec` read carries no conflict flag, so the only other signal is the 409 above, which arrives after a write has already been refused.+**You cannot resolve a conflict over MCP.** There is no conflict tool, and `exec` is read-only. On either 409, stop writing to that file, tell the user which file is in conflict, and ask them to resolve it in the OpenKnowledge app. After they confirm, re-read the document. For `doc-in-conflict`, the operation was refused; retry only if it is still needed. For `stale-external-write`, the operation already reached collaborative state; do not repeat it. Compare the resolved document with the intended result and make only any remaining edit.## The three kinds@@ -30,17 +30,20 @@ A write that first detects a stale file during its final disk flush returns `urnA `reconcile` conflict carries a `reason`: `merged-with-markers` (the three-way merge produced markers), `refused-conflict-markers` (the disk bytes already carried markers), `refused-too-large` (the document is past the merge size cap), `disk-markers` (markers landed on disk under an open doc), or `stale-external-write` (an older displaced version returned on disk). The compatibility `conflictKind` field is `stale-external-write` for that last reason and `git` otherwise.-## Resolution flow+## What the user chooses-1. `conflicts({ kind: 'list' })` → every tracked conflict as `{ file, detectedAt, conflict, reason?, conflictKind?, docName }`.-2. `conflicts({ kind: 'content', file })` → `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }` (the result nests under the `content` kind key). `ours` reflects the live Y.Text when the doc is loaded and marker-free; otherwise it falls back to the pinned stage. For a stale external write, `ours` is the protected content and `theirs` is the rejected older save. On a `reconcile` conflict, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers. Send the reviewed bytes back as `content` when you mean to keep exactly what you were shown. Returns 404 `urn:ok:error:no-conflict-tracked` (title `No conflict is tracked for this path.`) when nothing is tracked for that path; re-read the list before retrying.-3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes. **Send a strategy from that conflict's `resolutionOptions`**, not the full set. A `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and `refused-too-large` offers only `mine`, `theirs`, and `delete`. An unoffered strategy returns a 422 with `refusal: "strategy-not-offered"`. Markers left in the content you submit return the same status with `refusal: "markers-in-content"`, and that field is what tells the two apart. A 404 (`urn:ok:error:no-conflict-tracked`) carries this detail verbatim: `This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Re-read conflicts({ kind: "list" }) before retrying.` It says nothing is tracked, not that your resolution was saved, so re-read the list.+The controls depend on the conflict's shape:-Per kind, `mine` / `theirs` mean different things. On `merge-native` they are `git checkout --ours` / `--theirs` (the committed stages 2 and 3), and `delete` is `git rm`. On `working-tree`, `mine` keeps your overlay verbatim and `theirs` restores the pinned origin blob. On `reconcile`, `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk bytes captured at detection. For a stale external write, these choices keep the current local content or accept the rejected save. `content` always writes the bytes you supply, including an explicit empty string, and `delete` removes the file.+| Shape | What the app shows | Controls |+| - | - | - |+| Conflict markers (`resolutionOptions` includes `content`) | The Conflict view, comparing both sides | **Accept current**, **Accept incoming** and, where available, **Accept both** for each conflict; the user then applies the resolution |+| Whole file, such as `refused-too-large` (no `content` option) | A preview of the user's version | **Keep my version**, plus **Use their version** and **Delete the file** when offered |+| Deleted locally, modified upstream | A preview of the upstream version | **Keep file deleted**, plus **Restore with remote changes** when offered |+| Modified locally, deleted upstream | A preview of the user's version | **Keep my version** or **Accept their deletion** |-`file` is a `.md` / `.mdx` path relative to the project dir (extension included) — mirrors the on-disk shape, not the extension-less `document` path used by other tools.+For a stale external write, Current is the version OpenKnowledge protected and Incoming is the restored older version. `resolutionOptions` lists the strategies the app offers for that file; no MCP tool accepts them, so never try to apply one yourself. Explain what each choice would keep, but leave the choice and application to the user.-Resolution is best-effort across disk, collaborative state, and indexes. A failed local resolution keeps its authority row and recovery snapshot for retry. For `merge-native`, `git checkout --ours/--theirs && git add` may succeed before `git commit --no-edit` fails; the ledger keeps the still-unmerged files. Re-read the conflict before retrying.+If applying a resolution fails, ask the user to inspect the remaining conflict in the app. OpenKnowledge retains unresolved conflict and recovery state. Wait for the user to finish, then re-read the document before deciding what work remains.A conflict can also close without you. Resolving a merge with raw git outside the app prunes the `merge-native` entry on the next disk change or HEAD move, and a `reconcile` conflict whose file comes back clean on disk dissolves on the next watcher pass.diff --git a/packages/server/assets/skills/project/references/ingest-and-sources.md b/packages/server/assets/skills/project/references/ingest-and-sources.mdindex b49ee8d5f..01b02b13b 100644--- a/packages/server/assets/skills/project/references/ingest-and-sources.md+++ b/packages/server/assets/skills/project/references/ingest-and-sources.md@@ -143,9 +143,9 @@ The body is just the wiki-embed reference. For images, video, and audio, the embWrite via `write` (NOT native `Write` — the CRDT path is mandatory for in-scope markdown).-## Step 2b: Save the text wrapper (only after Step 1c — text path or shell-less fallback)+## Step 2b: Save the text wrapper (fetched text, local text, or shell-less fallback)-Write a markdown wrapper at `external-sources/<slug>.md` with the text content preserved verbatim in the body. Strip obvious boilerplate (nav menus, cookie banners, ads, footer links, "related articles" widgets) but **do not summarize, paraphrase, or interpret**.+Write a markdown wrapper at `external-sources/<slug>.md`. For fetched pages, strip obvious boilerplate (nav menus, cookie banners, ads, footer links, "related articles" widgets), but do not summarize, paraphrase, or interpret. For a supplied local text file, preserve every line verbatim without boilerplate stripping. Set `source_url` to the supplied local path as plain text; do not leave it blank or fetch it as a URL.Frontmatter shape:@@ -158,7 +158,7 @@ source_url: https://example.com/articlemedia_type: text/htmldate_fetched: YYYY-MM-DDauthor: Original author if known-preservation: text-extracted # OR: text-only (a shell-less fallback for a binary source)+preservation: text-extracted# NOTE: no `source_path` — text wrappers ARE the content. `source_path` is meaningful only for# binary wrappers (Step 2a), where it points at the co-located binary sibling.tags:@@ -169,7 +169,7 @@ tags:---```-**If this is a shell-less fallback for a source that should have been binary** (you detected binary in Step 1a but your host couldn't `curl`), set `preservation: text-only` AND prepend a top-of-body admonition so a future agent (or you, on a different host) can detect and upgrade:+For a supplied local text file, always use `preservation: text-extracted`. Reserve `preservation: text-only` for a shell-less fallback for a source that should have been binary (you detected binary in Step 1a but your host couldn't `curl`). In that fallback, prepend a top-of-body admonition so a future agent (or you, on a different host) can detect and upgrade:```markdown> Binary not preserved — this is an extracted-text snapshot of a binary source.diff --git a/packages/server/assets/skills/write-skill/SKILL.md b/packages/server/assets/skills/write-skill/SKILL.mdindex ee85efdc3..88857685a 100644--- a/packages/server/assets/skills/write-skill/SKILL.md+++ b/packages/server/assets/skills/write-skill/SKILL.md@@ -211,8 +211,9 @@ Changing an existing location is `convert`, which leaves membership alone; passevery location to make them uniform.**What each form means.** A symlink points at the source, so it cannot drift. A-copy is its own folder and refreshes automatically from the source — until-someone hand-edits it, at which point it forks and is never overwritten again.+copy is its own folder. A recorded, unedited copy refreshes from the source+when the skill watcher runs or the server starts, so it may briefly lag a source+edit. A hand edit forks the copy and prevents further automatic overwrites.**Lifecycle.** Edit with `edit({ skill })`; it routes to the source and versionsin place. There is no "uninstall everywhere" — removing every other location@@ -226,7 +227,7 @@ on pull.## Reminders- Prefer ONE good skill over many overlapping ones; split only when triggers diverge. (The Stage 1 gate is where you ENFORCE this — don't leave overlap to discover later.)-- Scope is the only placement decision — don't fold harness/format/toolchain assumptions into it, and don't bake one into the scope question's wording. You are authoring an OpenKnowledge skill: create it with `write({ skill })` — it lands as a real folder at the project's default skill home with attribution and versioning — and fan it out with `install`; don't hand-scatter copies across editor dirs, because `install` owns fan-out and refreshes unedited copies from the source (a hand-edited copy forks and stops refreshing). If you load this flow, author through it.+- Scope is the only placement decision — don't fold harness/format/toolchain assumptions into it, and don't bake one into the scope question's wording. You are authoring an OpenKnowledge skill: create it with `write({ skill })` — it lands as a real folder at the project's default skill home with attribution and versioning — and fan it out with `install`; don't hand-scatter copies across editor dirs, because `install` owns fan-out; recorded, unedited copies refresh on watcher/startup sync (a hand-edited copy forks and stops refreshing). If you load this flow, author through it.- Ground claims about how skills behave (versioning, install targets, scope semantics) in this guide or the tool descriptions — don't assert system facts from assumption.- Avoid blanket ALWAYS/NEVER rules without a stated reason — they read as noise andget ignored. Explain the why.diff --git a/packages/server/src/api-document-suffix-identity.test.ts b/packages/server/src/api-document-suffix-identity.test.tsnew file mode 100644index 000000000..3d95f2216--- /dev/null+++ b/packages/server/src/api-document-suffix-identity.test.ts@@ -0,0 +1,99 @@+import { randomUUID } from 'node:crypto';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DocumentReadSuccessSchema } from '@inkeep/open-knowledge-core';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++const prefix = `suffix-${randomUUID()}`;+const documents = {+ 'x.md': '# Plain\n\nPLAIN\n',+ 'x.md.md': '# Dotted\n\nDOTTED\n',+ 'lone.md.md': '# Lone\n\nLONE\n',+ 'deep.md.md.MDX': '# Deep\n\nDEEP\n',+ 'pair.md': '# Shadowed\n\nSHADOWED\n',+ 'pair.mdx': '# Winner\n\nWINNER\n',+};+let contentDir: string;+let server: BootedServer;++beforeAll(async () => {+ contentDir = await mkdtemp(join(tmpdir(), 'ok-document-suffix-identity-'));+ await mkdir(join(contentDir, prefix));+ await Promise.all(+ Object.entries(documents).map(([file, content]) =>+ writeFile(join(contentDir, prefix, file), content),+ ),+ );+ server = await bootCompositionRig(contentDir);+ await server.ready;+}, 60_000);++afterAll(async () => {+ await server?.destroy();+ await rm(contentDir, { recursive: true, force: true });+});++const readCases = [+ ['x', 'x', documents['x.md']],+ ['x.md', 'x.md', documents['x.md.md']],+ ['x.md.md', 'x.md', documents['x.md.md']],+ ['lone.md', 'lone.md', documents['lone.md.md']],+ ['lone.md.md', 'lone.md', documents['lone.md.md']],+ ['deep.md.md', 'deep.md.md', documents['deep.md.md.MDX']],+ ['deep.md.md.MDX', 'deep.md.md', documents['deep.md.md.MDX']],+ ['pair', 'pair', documents['pair.mdx']],+ ['pair.mdx', 'pair', documents['pair.mdx']],+ ['pair.md', 'pair.md', documents['pair.md']],+] as const;++describe('dotted document identities over real serving boundaries', () => {+ test.each(readCases)(+ 'HTTP read of %s preserves identity %s and its bytes',+ async (input, name, content) => {+ const response = await fetch(+ `http://127.0.0.1:${server.port}/api/document?docName=${encodeURIComponent(`${prefix}/${input}`)}`,+ );+ expect(response.status).toBe(200);+ const body = DocumentReadSuccessSchema.parse(await response.json());+ expect(body.docName).toBe(`${prefix}/${name}`);+ expect(body.content).toBe(content);+ },+ );++ test.each(readCases)(+ 'direct connection for %s loads identity %s and its bytes',+ async (input, name, content) => {+ const connection = await server.serverInstance.hocuspocus.openDirectConnection(+ `${prefix}/${input}`,+ );+ try {+ expect(connection.document.name).toBe(`${prefix}/${name}`);+ expect(connection.document.getText('source').toString()).toBe(content);+ } finally {+ await connection.disconnect();+ }+ },+ );++ test('an agent write to the dotted identity persists only its own physical file', async () => {+ const replacement = '# Dotted updated\n\nUPDATED DOTTED\n';+ const response = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ docName: `${prefix}/x.md`,+ markdown: replacement,+ position: 'replace',+ agentId: `suffix-writer-${randomUUID()}`,+ }),+ });+ expect(response.status, await response.text()).toBe(200);+ await expect+ .poll(() => readFile(join(contentDir, prefix, 'x.md.md'), 'utf8'))+ .toBe(replacement);+ expect(await readFile(join(contentDir, prefix, 'x.md'), 'utf8')).toBe(documents['x.md']);+ });+});diff --git a/packages/server/src/api-extension.test-helper.ts b/packages/server/src/api-extension.test-helper.tsindex 5df0a4e17..c89983e78 100644--- a/packages/server/src/api-extension.test-helper.ts+++ b/packages/server/src/api-extension.test-helper.ts@@ -68,6 +68,9 @@ export function createDerivedDocumentIndexApiPortStub(async getIndexedDocNames() {return [];},+ async getRenameSourceInventory() {+ return [];+ },async getAllTags() {return [];},@@ -215,6 +218,9 @@ function createLegacyDerivedIndexPort(async getIndexedDocNames() {return backlinkIndex?.getIndexedDocNames() ?? [];},+ async getRenameSourceInventory() {+ return backlinkIndex?.getRenameSourceInventory() ?? [];+ },async getAllTags() {return tagIndex?.getAllTags() ?? [];},diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 870e2c456..c44db6303 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -143,6 +143,7 @@ import { findHubCandidates } from './hub-candidates.ts';import { recordSkillInstall, removeSkillInstall } from './installed-skills-marker.ts';import { collectDocFiles } from './lint/audit.ts';import { composeAuditGeneration } from './lint/audit-generation.ts';+import { isAbsentPathError } from './lint/audit-scope.ts';import { unmatchedAppliesToProblems } from './lint/frontmatter-schemas.ts';import { resolveEffectiveLinterConfig } from './lint/resolve-config.ts';import { createProjectValidators } from './lint/validation-audit.ts';@@ -191,7 +192,12 @@ import {} from './apply-managed-rename.ts';import { composeAndWriteRawBody } from './bridge-intake.ts';import type { BridgeDeriveLossReporter } from './bridge-loss-detector.ts';-import { isConfigDoc, isLinkIndexExcludedDoc, isSystemDoc } from './cc1-broadcast.ts';+import {+ isConfigDoc,+ isLinkIndexExcludedDoc,+ isPersistenceExcludedDoc,+ isSystemDoc,+} from './cc1-broadcast.ts';import {isReservedProjectStatePath,listManagedDocNamesUnderFolder,@@ -315,13 +321,20 @@ import {type ManagedRenameSnapshot,withManagedRenameRecovery,} from './managed-rename-journal.ts';-import { rewriteAssetReferencesForRename } from './managed-rename-rewrite.ts';+import {+ createWikiRenameContext,+ rewriteAssetReferencesForRename,+ rewriteWikiLinksForRenameMap,+ type WikiRenameContext,+ wikiLinkRenameDestination,+} from './managed-rename-rewrite.ts';import {incrementAgentWriteCalls,incrementSummariesProvided,incrementSummariesTruncated,} from './metrics.ts';import { isWithinDir, toPosix } from './path-utils.ts';+import { isValidRelativeContentPath } from './relative-content-path.ts';import {appendRenameLogEntry,getOrLoadRenameLogIndex,@@ -907,14 +920,6 @@ interface ManagedRenameRewriteSummary {rewrites: number;}-function isValidRelativeContentPath(path: string): boolean {- if (!path || path.startsWith('/') || path.includes('\\') || path.includes('\x00')) {- return false;- }-- return path.split('/').every((segment) => segment && segment !== '.' && segment !== '..');-}-function listAffectedDocNames(index: ReadonlyMap<string, FileIndexEntry>,kind: ContentEntryKind,@@ -1817,7 +1822,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {type: 'urn:ok:error:stale-external-write' as const,title: 'Edit retained; disk write blocked by a stale external-write conflict.',detail:- 'An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: inspect conflicts({ kind: "content" }) for this file and resolve_conflict, then re-read the document before making further changes.',+ 'An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: ask the user to resolve the conflict in the OpenKnowledge app, then re-read the document before making further changes.',file:durabilityState.getStaleExternalWrite(docName)?.file ??relative(projectDir ?? contentDir, safeContentPath(docName, contentDir)).replaceAll(@@ -2240,8 +2245,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {function applyManagedRenameMapToLoadedDocument(docName: string,- renameMap: ReadonlyMap<string, string>,- renamedAssets: readonly RenamedAssetMapping[] = [],+ renamedAssets: readonly RenamedAssetMapping[],+ wikiContext: WikiRenameContext,): ManagedRenameRewriteSummary {const document = hocuspocus.documents.get(docName);if (!document) {@@ -2254,9 +2259,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {result = applyRenameAndAssetReferenceRewrites(ytext.toString(),docName,- renameMap.get(docName) ?? docName,- renameMap,+ wikiContext.renames.get(docName) ?? docName,renamedAssets,+ wikiContext,);if (result.rewrites === 0) {return;@@ -2285,10 +2290,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {markdown: string,currentDocName: string,rewrittenDocName: string,- renameMap: ReadonlyMap<string, string>,renamedAssets: readonly RenamedAssetMapping[],+ wikiContext: WikiRenameContext,): ManagedRenameRewriteSummary {- const docRename = applyRenameMap(markdown, currentDocName, renameMap);+ const docRename = applyRenameMap(markdown, currentDocName, wikiContext);const assetRename = rewriteAssetReferencesForMappings(docRename.markdown,rewrittenDocName,@@ -2744,6 +2749,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {}const renameMap = buildRenameMap(affectedDocs);+ const wikiContext = createWikiRenameContext(+ new Set([+ ...getFileIndex().keys(),+ ...(await derivedDocumentIndex.getIndexedDocNames()),+ ...renameMap.keys(),+ ]),+ renameMap,+ );const renamed: RenamedDocMapping[] = affectedDocs.map(({ from, to }) => ({fromDocName: from,toDocName: to,@@ -2757,10 +2770,83 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {}}}- const backlinkSources = [...backlinkSourceSet].sort((a, b) => a.localeCompare(b));-const snapshotContents = new Map<string, string>();const rewriteDocNameSet = new Set<string>();+ const sourceInventory = await derivedDocumentIndex.getRenameSourceInventory();+ const indexedNames = new Set(sourceInventory.map(({ docName }) => docName));+ const discoveryCandidates = new Set<string>(hocuspocus.documents.keys());+ for (const docName of wikiContext.before.pages) {+ if (!indexedNames.has(docName)) discoveryCandidates.add(docName);+ }+ const mtimeChecks: Array<{ docName: string; indexedMtimeMs: number | undefined }> = [];+ for (const { docName, wikiTargets, indexedMtimeMs } of sourceInventory) {+ if (+ wikiTargets.some(+ (target) => wikiLinkRenameDestination(target, docName, wikiContext) !== null,+ )+ ) {+ discoveryCandidates.add(docName);+ }+ if (!discoveryCandidates.has(docName)) mtimeChecks.push({ docName, indexedMtimeMs });+ }+ for (let offset = 0; offset < mtimeChecks.length; offset += 128) {+ const checks = mtimeChecks.slice(offset, offset + 128);+ const checked = await Promise.allSettled(+ checks.map(async ({ docName, indexedMtimeMs }) => {+ try {+ const filePath = resolveContentEntryPath(contentDir, 'file', docName);+ return indexedMtimeMs !== (await stat(filePath)).mtimeMs ? docName : null;+ } catch (error) {+ if (isAbsentPathError(error)) return null;+ const code = error instanceof Error && 'code' in error ? error.code : 'unknown';+ throw new Error(`Rename discovery could not check ${docName} (${code})`, {+ cause: error,+ });+ }+ }),+ );+ for (const result of checked) {+ if (result.status === 'rejected') throw result.reason;+ if (result.value) discoveryCandidates.add(result.value);+ }+ }+ for (const docName of discoveryCandidates) {+ if (+ renameMap.has(docName) ||+ isPersistenceExcludedDoc(docName) ||+ isDocNameContentExcluded(docName)+ )+ continue;+ let candidatePath: string;+ try {+ candidatePath = resolveContentEntryPath(contentDir, 'file', docName);+ } catch (error) {+ if (isAbsentPathError(error)) continue;+ throw error;+ }+ if (!existsSync(candidatePath)) continue;+ reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,+ docName,+ contentDir,+ undefined,+ getBridgeLossReporter?.(),+ conflicts,+ );+ const content = readCurrentDocumentContent(docName);+ if (typeof content !== 'string') continue;+ if (+ rewriteWikiLinksForRenameMap(stripFrontmatter(content).body, docName, wikiContext)+ .rewrites > 0+ ) {+ backlinkSourceSet.add(docName);+ snapshotContents.set(docName, content);+ rewriteDocNameSet.add(docName);+ }+ }+ const backlinkSources = [...backlinkSourceSet].sort((a, b) => a.localeCompare(b));+const assetRewriteDocNameSet = new Set<string>();const missingBacklinkSources: string[] = [];@@ -2804,8 +2890,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {content,docName,renameMap.get(docName) ?? docName,- renameMap,renamedAssets,+ wikiContext,);if (rewritten.rewrites === 0) continue;if (!snapshotContents.has(docName)) {@@ -2844,13 +2930,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {for (const docName of rewriteDocNames) {const document = hocuspocus.documents.get(docName);const rewritten = document- ? applyManagedRenameMapToLoadedDocument(docName, renameMap, renamedAssets)+ ? applyManagedRenameMapToLoadedDocument(docName, renamedAssets, wikiContext): applyRenameAndAssetReferenceRewrites(snapshotContents.get(docName) ?? '',docName,docName,- renameMap,renamedAssets,+ wikiContext,);if (rewritten.rewrites > 0) {@@ -2990,8 +3076,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {sourceCurrentContent,fromDocName,toDocName,- renameMap,renamedAssets,+ wikiContext,);syncRenamedDocsToDisk(diff --git a/packages/server/src/api-file-ops.test.ts b/packages/server/src/api-file-ops.test.tsindex 1aecb61f5..d7cc0b275 100644--- a/packages/server/src/api-file-ops.test.ts+++ b/packages/server/src/api-file-ops.test.ts@@ -260,7 +260,7 @@ describe('file operation API routes', () => {expect(existsSync(join(dir, 'notes.md'))).toBe(false);expect(readFileSync(join(dir, 'renamed-notes.md'), 'utf-8')).toBe('# Notes\n');expect(readFileSync(join(dir, 'journal.md'), 'utf-8')).toBe(- '# Journal\n\nSee [[renamed-notes]] and [Notes](./renamed-notes.md).\n',+ '# Journal\n\nSee [[renamed-notes|notes]] and [Notes](./renamed-notes.md).\n',);expect(readFileSync(join(dir, 'nested/child.md'), 'utf-8')).toBe('# Child\n\nJump to [Notes](../renamed-notes.md#intro "Section").\n',@@ -427,9 +427,11 @@ describe('file operation API routes', () => {);expect(result.status).toBe(200);- expect(document.getText('source').toString()).toBe('# Journal\n\nSee [[renamed-notes]].\n');+ expect(document.getText('source').toString()).toBe(+ '# Journal\n\nSee [[renamed-notes|notes]].\n',+ );expect(readFileSync(join(dir, 'journal.md'), 'utf-8')).toBe(- '# Journal\n\nSee [[renamed-notes]].\n',+ '# Journal\n\nSee [[renamed-notes|notes]].\n',);} finally {await conn.disconnect();@@ -500,7 +502,7 @@ describe('file operation API routes', () => {expect(existsSync(join(dir, 'renamed-notes.md'))).toBe(true);expect(readFileSync(join(dir, 'journal.md'), 'utf-8')).toBe(- '# Journal\n\nSee [[renamed-notes]].\n',+ '# Journal\n\nSee [[renamed-notes|notes]].\n',);expect(existsSync(join(dir, 'phantom-doc.md'))).toBe(false);diff --git a/packages/server/src/api-folder-rename-disk-enum.test.ts b/packages/server/src/api-folder-rename-disk-enum.test.tsindex f811362f0..8338fd9f3 100644--- a/packages/server/src/api-folder-rename-disk-enum.test.ts+++ b/packages/server/src/api-folder-rename-disk-enum.test.ts@@ -1,12 +1,24 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';import type { IncomingMessage, ServerResponse } from 'node:http';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { Readable } from 'node:stream';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import * as core from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';import { createApiExtension } from './api-extension.test-helper.ts';import { BacklinkIndex } from './backlink-index.ts';import { _resetDocExtensionsForTests } from './doc-extensions.ts';+import type { FileIndexEntry } from './file-watcher.ts';interface CapturedResponse {status: number;@@ -44,13 +56,19 @@ async function renameFolder(contentDir: string,from: string,to: string,+ options: {+ documents?: Map<string, Y.Doc>;+ afterIndex?: () => void;+ fileIndex?: Map<string, FileIndexEntry>;+ } = {},): Promise<{ status: number; structured: Record<string, unknown> }> {const backlinkIndex = new BacklinkIndex({ projectDir: contentDir, contentDir });await backlinkIndex.rebuildFromDisk();+ options.afterIndex?.();const ext = createApiExtension({hocuspocus: {- documents: new Map(),+ documents: options.documents ?? new Map(),closeConnections() {},unloadDocument: async () => {},debouncer: { isDebounced: () => false, executeNow: async () => undefined },@@ -60,7 +78,7 @@ async function renameFolder(closeAllForDoc: async () => {},} as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],contentDir,- getFileIndex: () => new Map(),+ getFileIndex: () => options.fileIndex ?? new Map(),backlinkIndex,});@@ -108,9 +126,9 @@ describe('folder rename enumerates descendant docs from disk', () => {const rewrittenDocs = structured.rewrittenDocs as Array<{ docName: string }>;expect(rewrittenDocs.map((d) => d.docName)).toContain('src');const srcBody = readFileSync(join(contentDir, 'src.md'), 'utf-8');- expect(srcBody).toContain('[[fr-final/deep/leaf]]');- expect(srcBody).toContain('[[fr-final/note]]');- expect(srcBody).not.toContain('fr-nested');+ expect(srcBody).toContain('[[fr-final/deep/leaf|fr-nested/deep/leaf]]');+ expect(srcBody).toContain('[[fr-final/note|fr-nested/note]]');+ expect(srcBody).not.toContain('[[fr-nested/');});test('preserves a .mdx descendant extension (registerDocExtension path)', async () => {@@ -128,12 +146,12 @@ describe('folder rename enumerates descendant docs from disk', () => {expect(existsSync(join(contentDir, 'guides/page.md'))).toBe(false);const indexBody = readFileSync(join(contentDir, 'index.md'), 'utf-8');- expect(indexBody).toContain('[[guides/page]]');+ expect(indexBody).toContain('[[guides/page|docs/page]]');});});describe('folder rename rewrites every inbound link shape and preserves intra-folder links', () => {- test('rewrites nested `../` inbound links and leaves no stale folder references', async () => {+ test('rewrites nested `../` inbound links and preserves wiki display labels', async () => {seed(contentDir, 'foods/apple.md', '# Apple\n');seed(contentDir, 'foods/sub/banana.md', '# Banana\n');@@ -147,16 +165,10 @@ describe('folder rename rewrites every inbound link shape and preserves intra-foexpect(status).toBe(200);const read = (p: string) => readFileSync(join(contentDir, p), 'utf-8');- for (const p of [- 'top-wiki.md',- 'top-root.md',- 'top-dotrel.md',- 'one/note.md',- 'one/two/note.md',- ]) {+ for (const p of ['top-root.md', 'top-dotrel.md', 'one/note.md', 'one/two/note.md']) {expect(read(p)).not.toContain('foods');}- expect(read('top-wiki.md')).toContain('[[recipes/apple]]');+ expect(read('top-wiki.md')).toContain('[[recipes/apple|foods/apple]]');expect(read('top-root.md')).toContain('(/recipes/apple.md)');expect(read('top-dotrel.md')).toContain('(./recipes/apple.md)');expect(read('one/note.md')).toContain('(../recipes/apple.md)');@@ -195,3 +207,135 @@ describe('folder rename rewrites every inbound link shape and preserves intra-foexpect(existsSync(join(contentDir, 'veg/carrot.md'))).toBe(true);});});++describe('managed rename corpus discovery', () => {+ test('does not parse unrelated indexed document bodies', async () => {+ seed(contentDir, 'moving/target.md', '# Target\n');+ const names = Array.from({ length: 96 }, (_, i) => `work-${i}`);+ for (const name of names) seed(contentDir, `${name}.md`, `# Work source ${name}\n`);+ seed(contentDir, 'linked.md', '[[moving/target]]\n');+ const seen = new Set<string>();+ let active = false;+ const original = core.stripFrontmatter;+ const parse = vi.spyOn(core, 'stripFrontmatter').mockImplementation((body) => {+ if (active && body.startsWith('# Work source ')) seen.add(body);+ return original(body);+ });+ try {+ const result = await renameFolder(contentDir, 'moving', 'moved', {+ afterIndex: () => {+ active = true;+ },+ });+ expect(result.status).toBe(200);+ expect(seen.size).toBe(0);+ expect(readFileSync(join(contentDir, 'linked.md'), 'utf8')).toBe(+ '[[moved/target|moving/target]]\n',+ );+ } finally {+ parse.mockRestore();+ }+ });++ test('rewrites a link found only in loaded unsaved Y.Text', async () => {+ seed(contentDir, 'moving/target.md', '# Target\n');+ seed(contentDir, 'live.md', 'No link on disk.\n');+ const doc = new Y.Doc();+ doc.getText('source').insert(0, '[[moving/target]]\n');+ try {+ const result = await renameFolder(contentDir, 'moving', 'moved', {+ documents: new Map([['live', doc]]),+ });+ expect(result.status).toBe(200);+ expect(readFileSync(join(contentDir, 'live.md'), 'utf8')).toBe(+ '[[moved/target|moving/target]]\n',+ );+ } finally {+ doc.destroy();+ }+ });++ test('discovers a stale referrer and protects an unmoved target outside moved backlinks', async () => {+ seed(contentDir, 'notes/beta.md', '# Moving\n');+ seed(contentDir, 'm/beta.md', '# Intended\n');+ seed(contentDir, 'source.md', '[[beta|Original]]\n');+ seed(contentDir, 'stale.md', 'Unlinked when indexed.\n');+ const result = await renameFolder(contentDir, 'notes', 'archive', {+ afterIndex: () => {+ const path = join(contentDir, 'stale.md');+ const { atime, mtimeMs } = statSync(path);+ seed(contentDir, 'stale.md', '[[notes/beta|Added after indexing]]\n');+ utimesSync(path, atime, new Date(mtimeMs + 2_000));+ },+ });+ expect(result.status).toBe(200);+ expect(readFileSync(join(contentDir, 'source.md'), 'utf8')).toBe('[[m/beta|Original]]\n');+ expect(readFileSync(join(contentDir, 'stale.md'), 'utf8')).toBe(+ '[[archive/beta|Added after indexing]]\n',+ );+ });++ test('rewrites a file-indexed referrer that the backlink index has not seen yet', async () => {+ seed(contentDir, 'moving/target.md', '# Target\n');+ const result = await renameFolder(contentDir, 'moving', 'moved', {+ afterIndex: () => seed(contentDir, 'late.md', '[[moving/target]]\n'),+ fileIndex: new Map([+ [+ 'late',+ {+ size: 18,+ modified: new Date(0).toISOString(),+ canonicalPath: join(contentDir, 'late.md'),+ inode: 0,+ aliases: [],+ kind: 'markdown',+ },+ ],+ ]),+ });+ expect(result.status).toBe(200);+ expect(readFileSync(join(contentDir, 'late.md'), 'utf8')).toBe(+ '[[moved/target|moving/target]]\n',+ );+ });++ test('leaves loaded non-Markdown documents untouched when a wiki winner changes', async () => {+ seed(contentDir, 'docs/Login.md', '# Login\n');+ seed(contentDir, 'm/Login.md', '# Other login\n');+ seed(contentDir, 'index.md', 'See [[Login]].\n');+ const diagram = 'flowchart LR\n A --> B[[Login]]\n';+ seed(contentDir, 'diagram.mmd', diagram);+ const doc = new Y.Doc();+ doc.getText('source').insert(0, diagram);+ try {+ const result = await renameFolder(contentDir, 'docs', 'zz', {+ documents: new Map([['diagram.mmd', doc]]),+ });+ expect(result.status).toBe(200);+ expect(readFileSync(join(contentDir, 'index.md'), 'utf8')).toBe('See [[zz/Login|Login]].\n');+ expect(doc.getText('source').toString()).toBe(diagram);+ expect(readFileSync(join(contentDir, 'diagram.mmd'), 'utf8')).toBe(diagram);+ expect(+ (result.structured.rewrittenDocs as Array<{ docName: string }>).map((d) => d.docName),+ ).toEqual(['index']);+ } finally {+ doc.destroy();+ }+ });++ test('treats an unrelated document whose folder became a file as absent', async () => {+ seed(contentDir, 'moving/target.md', '# Target\n');+ seed(contentDir, 'linked.md', '[[moving/target]]\n');+ seed(contentDir, 'unrelated/a.md', '# A\n');+ const result = await renameFolder(contentDir, 'moving', 'moved', {+ afterIndex: () => {+ rmSync(join(contentDir, 'unrelated'), { recursive: true });+ writeFileSync(join(contentDir, 'unrelated'), 'now a file');+ },+ });+ expect(result.status).toBe(200);+ expect(readFileSync(join(contentDir, 'linked.md'), 'utf8')).toBe(+ '[[moved/target|moving/target]]\n',+ );+ });+});diff --git a/packages/server/src/api-rename-rollback-summary.test.ts b/packages/server/src/api-rename-rollback-summary.test.tsindex 853b612f9..beded8348 100644--- a/packages/server/src/api-rename-rollback-summary.test.ts+++ b/packages/server/src/api-rename-rollback-summary.test.ts@@ -520,14 +520,14 @@ describe('handleRenamePath — actor identity routing', () => {});expect(response.status).toBe(200);- expect(readFileSync(join(tmpDir, 'journal.md'), 'utf-8')).toContain('[[renamed-notes]]');+ expect(readFileSync(join(tmpDir, 'journal.md'), 'utf-8')).toContain('[[renamed-notes|notes]]');const parsed = JSON.parse(response.body);expect(parsed.rewrittenDocs).toEqual(expect.arrayContaining([expect.objectContaining({ docName: 'journal' })]),);});- test('case-only rename succeeds and rewrites inbound wiki-links', async () => {+ test('case-only rename succeeds and preserves resolving inbound wiki-links', async () => {writeFileSync(join(tmpDir, 'Notes.md'), '# Notes\n', 'utf-8');writeFileSync(join(tmpDir, 'journal.md'), '# Journal\n\nSee [[Notes]].\n', 'utf-8');@@ -540,7 +540,7 @@ describe('handleRenamePath — actor identity routing', () => {expect(response.status).toBe(200);expect(readdirSync(tmpDir)).toContain('notes.md');expect(readdirSync(tmpDir)).not.toContain('Notes.md');- expect(readFileSync(join(tmpDir, 'journal.md'), 'utf-8')).toContain('[[notes]]');+ expect(readFileSync(join(tmpDir, 'journal.md'), 'utf-8')).toContain('[[Notes]]');const parsed = JSON.parse(response.body) as Record<string, unknown>;expect(parsed.renamed).toEqual([{ fromDocName: 'Notes', toDocName: 'notes' }]);});@@ -619,8 +619,8 @@ describe('handleRenamePath — folder rename via consolidated endpoint', () => {expect(response.status).toBe(200);const indexContent = readFileSync(join(setupDir, 'index.md'), 'utf-8');- expect(indexContent).toContain('[[essays/auth]]');- expect(indexContent).toContain('[[essays/login]]');+ expect(indexContent).toContain('[[essays/auth|articles/auth]]');+ expect(indexContent).toContain('[[essays/login|articles/login]]');expect(indexContent).not.toContain('[[articles/');} finally {rmSync(setupDir, { recursive: true, force: true });diff --git a/packages/server/src/api-resolved-link-views.test.ts b/packages/server/src/api-resolved-link-views.test.tsnew file mode 100644index 000000000..63254a14d--- /dev/null+++ b/packages/server/src/api-resolved-link-views.test.ts@@ -0,0 +1,143 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import {+ BacklinkCountsSuccessSchema,+ BacklinksSuccessSchema,+ ForwardLinksSuccessSchema,+ HubsSuccessSchema,+ LinkGraphSuccessSchema,+ OrphansSuccessSchema,+ SuggestLinksSuccessSchema,+} from '@inkeep/open-knowledge-core';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++async function get(booted: BootedServer, route: string): Promise<unknown> {+ const response = await fetch(`http://127.0.0.1:${booted.port}${route}`);+ expect(response.status).toBe(200);+ return response.json();+}++test('HTTP, MCP and app-facing graph queries agree across a body edit, with a real ancestor hub advisory', async () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-resolved-link-api-'));+ let booted: BootedServer | undefined;+ const client = new Client({ name: 'codex', version: '0.0.0-test' });+ try {+ for (const [doc, body] of Object.entries({+ 'notes/INDEX': '# Notes\n',+ 'notes/beta': '# Beta\n',+ 'notes/gamma': '# Gamma\n',+ 'notes/source': '[[BETA.md|Beta]]\n',+ })) {+ const file = join(root, `${doc}.md`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ }+ booted = await bootCompositionRig(root);+ await booted.ready;+ await client.connect(+ new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${booted.port}/mcp`)),+ );++ const verify = async (target: 'beta' | 'gamma') => {+ if (!booted) throw new Error('Server not booted');+ const canonical = `notes/${target}`;+ const previous = target === 'beta' ? 'notes/gamma' : 'notes/beta';+ const backlinks = BacklinksSuccessSchema.parse(+ await get(booted, `/api/backlinks?docName=${canonical}`),+ );+ expect(backlinks.backlinks.map((entry) => entry.source)).toEqual(['notes/source']);+ const counts = BacklinkCountsSuccessSchema.parse(+ await get(booted, '/api/backlink-counts?docNames=notes/beta,notes/gamma'),+ );+ expect(counts.counts).toEqual({ [canonical]: 1, [previous]: 0 });+ const forward = ForwardLinksSuccessSchema.parse(+ await get(booted, '/api/forward-links?docName=notes/source'),+ );+ expect(forward.forwardLinks).toEqual([+ expect.objectContaining({ kind: 'doc', docName: canonical }),+ ]);+ const orphans = OrphansSuccessSchema.parse(await get(booted, '/api/orphans?mode=incoming'));+ expect(orphans.orphans.map((entry) => entry.docName)).not.toContain(canonical);+ expect(orphans.orphans.map((entry) => entry.docName)).toContain(previous);+ const hubs = HubsSuccessSchema.parse(await get(booted, '/api/hubs'));+ expect(hubs.hubs).toContainEqual(expect.objectContaining({ docName: canonical, count: 1 }));+ const graph = LinkGraphSuccessSchema.parse(await get(booted, '/api/link-graph'));+ expect(graph.links).toContainEqual({ source: 'notes/source', target: canonical });+ expect(graph.links).not.toContainEqual({ source: 'notes/source', target: previous });+ const suggestions = SuggestLinksSuccessSchema.parse(+ await get(booted, `/api/suggest-links?docName=${canonical}`),+ );+ expect(suggestions.mentions).toEqual([]);+ const mcp = await client.callTool({+ name: 'links',+ arguments: {+ kind: ['backlinks', 'hubs', 'orphans', 'suggest'],+ mode: 'incoming',+ document: canonical,+ cwd: root,+ },+ });+ expect(mcp.isError ?? false).toBe(false);+ expect(mcp.structuredContent).toMatchObject({+ backlinks: [expect.objectContaining({ source: 'notes/source' })],+ hubs: expect.arrayContaining([expect.objectContaining({ docName: canonical, count: 1 })]),+ suggest: { mentions: [] },+ });+ const mcpForward = await client.callTool({+ name: 'links',+ arguments: { kind: 'forward', document: 'notes/source', cwd: root },+ });+ expect(mcpForward.isError ?? false).toBe(false);+ expect(mcpForward.structuredContent).toMatchObject({+ forwardLinks: [expect.objectContaining({ kind: 'doc', docName: canonical })],+ });+ };++ await verify('beta');+ const linkedWrite = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'notes/beta', content: '\nUpdated.\n', position: 'append' },+ cwd: root,+ },+ });+ expect(linkedWrite.isError ?? false).toBe(false);+ expect(linkedWrite.structuredContent).toMatchObject({ document: expect.any(Object) });+ expect(JSON.stringify(linkedWrite.structuredContent)).not.toContain('no backlinks yet');+ const unlinkedWrite = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'notes/gamma', content: '\nUpdated.\n', position: 'append' },+ cwd: root,+ },+ });+ expect(unlinkedWrite.isError ?? false).toBe(false);+ expect(unlinkedWrite.structuredContent).toMatchObject({+ document: {+ hints: [expect.objectContaining({ type: 'orphan', parentCandidates: ['notes/INDEX'] })],+ },+ });+ const edit = await client.callTool({+ name: 'edit',+ arguments: {+ document: {+ path: 'notes/source',+ find: '[[BETA.md|Beta]]',+ replace: '[[gamma.mdx|Gamma]]',+ },+ cwd: root,+ },+ });+ expect(edit.isError ?? false).toBe(false);+ await verify('gamma');+ } finally {+ await client.close();+ await booted?.destroy();+ rmSync(root, { recursive: true, force: true });+ }+}, 60_000);diff --git a/packages/server/src/api-skill-document-composition.test.ts b/packages/server/src/api-skill-document-composition.test.tsindex b4cc43e32..c27fa7fd0 100644--- a/packages/server/src/api-skill-document-composition.test.ts+++ b/packages/server/src/api-skill-document-composition.test.ts@@ -1,10 +1,11 @@-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';import type { BootedServer } from './boot.ts';import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';import * as contributorTracker from './contributor-tracker.ts';+import { moveSkillCrossScope } from './mcp/tools/skill-target.ts';let root: string;let server: BootedServer;@@ -166,3 +167,66 @@ test('external editing resolves a real skill directory without launching an editconst result = await request('/api/skill/edit-external', 'POST', { name: 'external', home: dir });expect(result.docName).toBe('__extskill__/external');});++test.each(['same-storage', 'plain-collision'])(+ 'cross-scope %s refusal retains server detail and teaches repair before retry',+ async (refusal) => {+ const name = `move-${refusal}`;+ const created = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Source skill' },+ body: 'Source bytes.\n',+ });+ const sourcePath = join(root, created.path as string);+ const destinationDir = join(home, '.claude/skills', name);+ if (refusal === 'same-storage') {+ mkdirSync(dirname(destinationDir), { recursive: true });+ symlinkSync(dirname(sourcePath), destinationDir, 'dir');+ } else {+ const destination = await request('/api/skill', 'PUT', {+ name,+ scope: 'global',+ frontmatter: { name, description: 'Destination skill' },+ body: 'Destination bytes.\n',+ });+ expect(join(home, destination.path as string)).toBe(join(destinationDir, 'SKILL.md'));+ }+ const destinationPath = join(destinationDir, 'SKILL.md');+ const sourceBefore = readFileSync(sourcePath, 'utf8');+ const destinationBefore = readFileSync(destinationPath, 'utf8');+ const response = await rawRequest(server.port, '/api/skill/move-scope', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name, fromScope: 'project', toScope: 'global' }),+ });+ expect(response.status, response.body).toBe(409);+ const problem = JSON.parse(response.body);+ expect(problem).toMatchObject({+ type: 'urn:ok:error:doc-already-exists',+ moveState: 'nothing-written',+ detail:+ refusal === 'same-storage'+ ? 'SAME_STORAGE'+ : 'Delete or rename it first; this move will not overwrite it.',+ });+ expect(problem).not.toHaveProperty('retentionLedger');++ const result = await moveSkillCrossScope(`http://127.0.0.1:${server.port}`, {+ fromName: name,+ toName: name,+ fromScope: 'project',+ toScope: 'global',+ });+ const text = result.content+ .flatMap((block) => (block.type === 'text' ? [block.text] : []))+ .join('\n');+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, moveState: 'nothing-written' });+ expect(text).toContain(problem.detail);+ expect(text).toContain('safe to retry once the refusal is addressed');+ expect(text).not.toContain('occupant is unverified');+ expect(readFileSync(sourcePath, 'utf8')).toBe(sourceBefore);+ expect(readFileSync(destinationPath, 'utf8')).toBe(destinationBefore);+ },+);diff --git a/packages/server/src/api-skill-install-composition.test.ts b/packages/server/src/api-skill-install-composition.test.tsindex c8141eff0..10ba7d245 100644--- a/packages/server/src/api-skill-install-composition.test.ts+++ b/packages/server/src/api-skill-install-composition.test.ts@@ -178,3 +178,69 @@ async function readArchive(bytes: Buffer): Promise<Map<string, string>> {});});}++test.each(['convert', 'unplace'] as const)(+ '%s preserves an untouched copy after a source edit and reports divergence without assigning blame',+ async (operation) => {+ const name = `source-edit-${operation}`;+ const source = join(seed(name), 'SKILL.md');+ const copyDir = join(root, 'qa048/bundles', name);+ const placement = await post('/api/skill/install', {+ scope: 'project',+ name,+ place: { dir: 'qa048/bundles', mode: 'copy' },+ });+ expect(placement.status, placement.body).toBe(200);+ const originalCopy = readFileSync(join(copyDir, 'SKILL.md'));+ const editedSource = `${markdown(name)}\nSource-only change.\n`;+ writeFileSync(source, editedSource);+ const response = await post('/api/skill/install', {+ scope: 'project',+ name,+ ...(operation === 'convert'+ ? { convert: { target: 'qa048/bundles', mode: 'link' } }+ : { unplace: { path: `qa048/bundles/${name}` } }),+ });+ expect(response.status, response.body).toBe(409);+ expect(JSON.parse(response.body)).toMatchObject({+ type: 'urn:ok:error:doc-already-exists',+ title:+ operation === 'convert'+ ? 'This copy differs from the current source and was preserved. Inspect both versions before replacing or converting it.'+ : 'This copy differs from the current source and was preserved. Inspect both versions before removing it.',+ detail: operation === 'convert' ? 'qa048/bundles' : `qa048/bundles/${name}`,+ });+ expect(readFileSync(join(copyDir, 'SKILL.md'))).toEqual(originalCopy);+ expect(readFileSync(source, 'utf8')).toBe(editedSource);+ expect(lstatSync(copyDir).isSymbolicLink()).toBe(false);+ },+);++test('custom-root removal preserves an untouched copy after a source edit and reports divergence without assigning blame', async () => {+ const name = 'source-edit-custom-remove';+ const source = join(seed(name), 'SKILL.md');+ const copy = join(root, 'qa048/skills', name, 'SKILL.md');+ const placement = await post('/api/skill/install', {+ scope: 'project',+ name,+ place: { dir: 'qa048/skills', mode: 'copy' },+ });+ expect(placement.status, placement.body).toBe(200);+ const originalCopy = readFileSync(copy);+ const editedSource = `${markdown(name)}\nSource-only change.\n`;+ writeFileSync(source, editedSource);+ const response = await post('/api/skill/install', {+ scope: 'project',+ name,+ remove: ['qa048/skills'],+ });+ expect(response.status, response.body).toBe(200);+ expect(SkillInstallSuccessSchema.parse(JSON.parse(response.body))).toMatchObject({+ warnings: [+ `The copy at qa048/skills/${name} differs from the current source and was preserved. Inspect both versions before removing it.`,+ ],+ warningCodes: ['place-fork-refused'],+ });+ expect(readFileSync(copy)).toEqual(originalCopy);+ expect(readFileSync(source, 'utf8')).toBe(editedSource);+});diff --git a/packages/server/src/apply-managed-rename.test.ts b/packages/server/src/apply-managed-rename.test.tsindex 475dd4c71..60c5e4a89 100644--- a/packages/server/src/apply-managed-rename.test.ts+++ b/packages/server/src/apply-managed-rename.test.ts@@ -4,6 +4,15 @@ import {buildRenameMap,ManagedRenameCollisionError,} from './apply-managed-rename.ts';+import { createWikiRenameContext } from './managed-rename-rewrite.ts';++function rewriteInCorpus(content: string, source: string, renames: ReadonlyMap<string, string>) {+ return applyRenameMap(+ content,+ source,+ createWikiRenameContext([source, ...renames.keys()], renames),+ );+}describe('buildRenameMap — collision detection', () => {test('builds a map for non-colliding entries', () => {@@ -82,17 +91,17 @@ describe('buildRenameMap — collision detection', () => {describe('applyRenameMap — single-entry rewrites', () => {test('rewrites wiki-links for a single entry', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [[old-page]] and [[other]].\n','source',new Map([['old-page', 'new-page']]),);- expect(result.markdown).toBe('See [[new-page]] and [[other]].\n');+ expect(result.markdown).toBe('See [[new-page|old-page]] and [[other]].\n');expect(result.rewrites).toBe(1);});test('rewrites does not touch unrelated content', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('# Title\n\nNo links here.\n','source',new Map([['old', 'new']]),@@ -102,7 +111,7 @@ describe('applyRenameMap — single-entry rewrites', () => {});test('skips identity entries (from === to)', () => {- const result = applyRenameMap('See [[same]].\n', 'source', new Map([['same', 'same']]));+ const result = rewriteInCorpus('See [[same]].\n', 'source', new Map([['same', 'same']]));expect(result.markdown).toBe('See [[same]].\n');expect(result.rewrites).toBe(0);});@@ -110,7 +119,7 @@ describe('applyRenameMap — single-entry rewrites', () => {describe('applyRenameMap — multi-entry rewrites', () => {test('rewrites all entries in a multi-entry map', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [[A]] and [[B]] and [[C]].\n','source',new Map([@@ -119,12 +128,12 @@ describe('applyRenameMap — multi-entry rewrites', () => {['C', 'Z'],]),);- expect(result.markdown).toBe('See [[X]] and [[Y]] and [[Z]].\n');+ expect(result.markdown).toBe('See [[X|A]] and [[Y|B]] and [[Z|C]].\n');expect(result.rewrites).toBe(3);});- test('swap cycle ({A→B, B→A}) produces correct output via placeholder-substitute', () => {- const result = applyRenameMap(+ test('swap cycle ({A→B, B→A}) preserves destinations and display text', () => {+ const result = rewriteInCorpus('See [[A]] and [[B]].\n','source',new Map([@@ -132,12 +141,12 @@ describe('applyRenameMap — multi-entry rewrites', () => {['B', 'A'],]),);- expect(result.markdown).toBe('See [[B]] and [[A]].\n');+ expect(result.markdown).toBe('See [[B|A]] and [[A|B]].\n');expect(result.rewrites).toBe(2);});test('swap cycle with multiple references each preserves both directions', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('A1: [[A]]\nA2: [[A]]\nB1: [[B]]\nB2: [[B]]\n','source',new Map([@@ -145,12 +154,12 @@ describe('applyRenameMap — multi-entry rewrites', () => {['B', 'A'],]),);- expect(result.markdown).toBe('A1: [[B]]\nA2: [[B]]\nB1: [[A]]\nB2: [[A]]\n');+ expect(result.markdown).toBe('A1: [[B|A]]\nA2: [[B|A]]\nB1: [[A|B]]\nB2: [[A|B]]\n');expect(result.rewrites).toBe(4);});test('three-way cycle ({A→B, B→C, C→A}) preserves correct mapping', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('[[A]] [[B]] [[C]]\n','source',new Map([@@ -159,12 +168,12 @@ describe('applyRenameMap — multi-entry rewrites', () => {['C', 'A'],]),);- expect(result.markdown).toBe('[[B]] [[C]] [[A]]\n');+ expect(result.markdown).toBe('[[B|A]] [[C|B]] [[A|C]]\n');expect(result.rewrites).toBe(3);});- test('rewrites count is Phase 1 only — Phase 2 unwrap does not double-count', () => {- const result = applyRenameMap(+ test('counts each wiki link once across a multi-entry rename', () => {+ const result = rewriteInCorpus('See [[A]] [[A]] [[B]].\n','source',new Map([@@ -172,22 +181,22 @@ describe('applyRenameMap — multi-entry rewrites', () => {['B', 'Y'],]),);- expect(result.markdown).toBe('See [[X]] [[X]] [[Y]].\n');+ expect(result.markdown).toBe('See [[X|A]] [[X|A]] [[Y|B]].\n');expect(result.rewrites).toBe(3);});test('preserves frontmatter unchanged across rewrites', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus(`---\ntitle: Doc\n---\n\nSee [[A]].\n`,'source',new Map([['A', 'X']]),);- expect(result.markdown).toBe(`---\ntitle: Doc\n---\n\nSee [[X]].\n`);+ expect(result.markdown).toBe(`---\ntitle: Doc\n---\n\nSee [[X|A]].\n`);expect(result.rewrites).toBe(1);});test('rewrites Mirror src for a renamed source doc', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('<Mirror src="api-spec" anchor="intro" />\n','viewer-doc',new Map([['api-spec', 'api-reference']]),@@ -197,19 +206,19 @@ describe('applyRenameMap — multi-entry rewrites', () => {});test('rewrites Mirror src alongside wiki + markdown links in the same body', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [[api-spec]] and [docs](./api-spec.md):\n<Mirror src="api-spec" anchor="dep" />\n','viewer-doc',new Map([['api-spec', 'api-reference']]),);expect(result.markdown).toBe(- 'See [[api-reference]] and [docs](./api-reference.md):\n<Mirror src="api-reference" anchor="dep" />\n',+ 'See [[api-reference|api-spec]] and [docs](./api-reference.md):\n<Mirror src="api-reference" anchor="dep" />\n',);expect(result.rewrites).toBe(3);});test('Mirror rewrite cooperates with frontmatter strip', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus(`---\ntitle: Doc\n---\n\n<Mirror src="A" anchor="x" />\n`,'source',new Map([['A', 'B']]),@@ -219,7 +228,7 @@ describe('applyRenameMap — multi-entry rewrites', () => {});test('rewrites a doc-relative Excalidraw src for a renamed board', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('<Excalidraw src="board.excalidraw" />\n','notes/index',new Map([['notes/board.excalidraw', 'notes/sketch.excalidraw']]),@@ -229,7 +238,7 @@ describe('applyRenameMap — multi-entry rewrites', () => {});test('self-rename recomputes a doc-relative Excalidraw src for the new location', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('<Excalidraw src="board.excalidraw" />\n','notes/index',new Map([['notes/index', 'archive/index']]),@@ -239,7 +248,7 @@ describe('applyRenameMap — multi-entry rewrites', () => {});test('folder move carrying both doc and board keeps the doc-relative src stable', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('<Excalidraw src="board.excalidraw" />\n','notes/index',new Map([@@ -253,7 +262,7 @@ describe('applyRenameMap — multi-entry rewrites', () => {describe('applyRenameMap — outbound link recomputation when source doc moves', () => {test('recomputes outbound markdown link to non-renamed target when source moves folders', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Picasso](./picasso.md).\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -263,7 +272,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('recomputes multiple outbound markdown links in one body', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus(['# Header', '', '[A](./a.md), [B](./b.md), and [C](../shared/c.md)', ''].join('\n'),'artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -280,7 +289,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('preserves anchors and query strings on outbound recomputation', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Section](./other.md#install?tab=api).\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -290,7 +299,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('preserves .mdx extension on outbound recomputation', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Component](./widget.mdx).\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -300,7 +309,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('preserves angle brackets on outbound recomputation', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Spaced](<./other.md>).\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -310,7 +319,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('leaves external URLs, anchor-only links, and root-absolute links unchanged', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus(['[Ext](https://example.com)','[Anchor](#section)',@@ -334,7 +343,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('skips outbound recomputation inside fenced code blocks', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus(['```md', '[Code](./other.md)', '```', '', '[Real](./other.md)', ''].join('\n'),'artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -346,7 +355,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('skips outbound recomputation inside inline code spans', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('Inline `[Skip](./other.md)` and live [Real](./other.md).\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -358,7 +367,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('same-folder rename leaves outbound markdown links untouched', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Picasso](./picasso.md).\n','artists/some-file',new Map([['artists/some-file', 'artists/some-other-file']]),@@ -368,7 +377,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('source moves AND target also renamed — both rewrites compose correctly', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('See [Picasso](./picasso.md).\n','artists/some-file',new Map([@@ -381,7 +390,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('moved doc with self-link resolves correctly post-move', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('[self](./some-file.md)\n','artists/some-file',new Map([['artists/some-file', 'venues/some-file']]),@@ -392,7 +401,7 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',});test('image refs are handled by the self-rename pass (not double-recomputed)', () => {- const result = applyRenameMap(+ const result = rewriteInCorpus('\n','docs/meeting-notes',new Map([['docs/meeting-notes', 'archive/2026/meeting-notes']]),diff --git a/packages/server/src/apply-managed-rename.ts b/packages/server/src/apply-managed-rename.tsindex a968fafff..ab7342164 100644--- a/packages/server/src/apply-managed-rename.ts+++ b/packages/server/src/apply-managed-rename.ts@@ -4,7 +4,8 @@ import {rewriteJsxSrcRefsForDocumentRename,rewriteMarkdownLinksForDocumentRename,rewriteOutboundMarkdownLinksForSourceMove,- rewriteWikiLinksForDocumentRename,+ rewriteWikiLinksForRenameMap,+ type WikiRenameContext,} from './managed-rename-rewrite.ts';interface ManagedRenameAffectedDocPair {@@ -131,9 +132,8 @@ function rewriteSupportedLinksForRename(newDocName: string,): ManagedRenameRewriteSummary {const { frontmatter, body } = stripFrontmatter(markdown);- const wikiRewrite = rewriteWikiLinksForDocumentRename(body, oldDocName, newDocName);const markdownRewrite = rewriteMarkdownLinksForDocumentRename(- wikiRewrite.markdown,+ body,sourceDocName,oldDocName,newDocName,@@ -146,21 +146,23 @@ function rewriteSupportedLinksForRename();return {markdown: prependFrontmatter(frontmatter, jsxRewrite.markdown),- rewrites: wikiRewrite.rewrites + markdownRewrite.rewrites + jsxRewrite.rewrites,+ rewrites: markdownRewrite.rewrites + jsxRewrite.rewrites,};}export function applyRenameMap(content: string,currentDocName: string,- renameMap: ReadonlyMap<string, string>,+ wikiContext: WikiRenameContext,): ManagedRenameRewriteSummary {- let markdown = content;- let rewrites = 0;+ const { frontmatter, body } = stripFrontmatter(content);+ const wikiRewrite = rewriteWikiLinksForRenameMap(body, currentDocName, wikiContext);+ let markdown = prependFrontmatter(frontmatter, wikiRewrite.markdown);+ let rewrites = wikiRewrite.rewrites;let selfRenamedTo: string | undefined;const otherRenames: Array<readonly [string, string]> = [];- for (const [from, to] of renameMap) {+ for (const [from, to] of wikiContext.renames) {if (from === to) continue;if (from === currentDocName) {selfRenamedTo = to;diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 61f70703a..0dd137b45 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -9,8 +9,8 @@ import {} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { LOCAL_DIR } from '@inkeep/open-knowledge-core';-import { beforeEach, describe, expect, test } from 'vitest';+import { LOCAL_DIR, skillLiveDocName } from '@inkeep/open-knowledge-core';+import { beforeEach, describe, expect, test, vi } from 'vitest';import {BacklinkIndex,type BrokenOutboundLink,@@ -22,6 +22,7 @@ import {resolveMarkdownHref,} from './backlink-index.ts';import { _resetDocExtensionsForTests } from './doc-extensions.ts';+import { getLogger } from './logger.ts';beforeEach(() => {_resetDocExtensionsForTests();@@ -501,7 +502,7 @@ describe('BacklinkIndex', () => {const index = new BacklinkIndex({ projectDir, contentDir });await index.rebuildFromDisk();- expect(index.getForwardLinks('index')).toContain('acp.daemon');+ expect(index.getForwardLinks('index')).toContain('notes/acp.daemon');expect(index.getDeadLinks(['index', 'notes/acp.daemon'])).toEqual([]);} finally {rmSync(projectDir, { recursive: true, force: true });@@ -588,8 +589,8 @@ describe('BacklinkIndex', () => {expect(neighborhood).not.toContain('diagram.png');expect(whole).not.toContain('diagram.png');- expect(neighborhood).toContain('acp.daemon');- expect(whole).toContain('acp.daemon');+ expect(neighborhood).toContain('notes/acp.daemon');+ expect(whole).toContain('notes/acp.daemon');} finally {rmSync(projectDir, { recursive: true, force: true });}@@ -652,7 +653,7 @@ describe('BacklinkIndex', () => {index.updateDocument('notes/acp.daemon', []);- expect(index.getLinkGraph().nodes.map((node) => node.id)).toContain('acp.daemon');+ expect(index.getLinkGraph().nodes.map((node) => node.id)).toContain('notes/acp.daemon');} finally {rmSync(projectDir, { recursive: true, force: true });}@@ -788,7 +789,7 @@ describe('BacklinkIndex', () => {writeFileSync(join(cacheDir, 'backlinks.json'),JSON.stringify({- version: 3,+ version: 4,backward: {ghost: [{ source: 'alpha', anchor: null, snippet: 'See ghost.' }],wraith: [@@ -798,6 +799,26 @@ describe('BacklinkIndex', () => {},forward: { alpha: ['ghost', 'wraith', 'shade'] },externalForward: {},+ sourceLinks: {+ alpha: [+ { target: 'ghost', anchor: null, snippet: 'See ghost.', sourceForm: 'wiki' },+ {+ target: 'wraith',+ anchor: null,+ snippet: 'See wraith.',+ sourceForm: 'wiki',+ line: '7',+ column: -2,+ },+ {+ target: 'shade',+ anchor: null,+ snippet: 'See shade.',+ sourceForm: 'wiki',+ line: 1.5,+ },+ ],+ },}),'utf-8',);@@ -873,6 +894,59 @@ describe('BacklinkIndex', () => {}});+ test.each([+ { version: 3, sourceLinks: undefined, expectedWarnings: [] },+ {+ version: 4,+ sourceLinks: {},+ expectedWarnings: [+ [{ branch: 'main' }, 'Incomplete backlink cache snapshot for main; rebuilding from disk'],+ ],+ },+ {+ version: 4,+ sourceLinks: { alpha: [], beta: [] },+ expectedWarnings: [+ [{ branch: 'main' }, 'Incomplete backlink cache snapshot for main; rebuilding from disk'],+ ],+ },+ ])('rejects incomplete source-link snapshots and rebuilds from disk: $version', async (cache) => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-source-links-guard-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ writeFileSync(join(contentDir, 'alpha.md'), '[[beta]]');+ writeFileSync(join(contentDir, 'beta.md'), '# Beta');+ const cacheDir = join(projectDir, '.ok', LOCAL_DIR, 'cache', 'main');+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(+ join(cacheDir, 'backlinks.json'),+ JSON.stringify({+ ...cache,+ backward: { beta: [{ source: 'alpha', anchor: null, snippet: 'beta' }] },+ forward: { alpha: ['beta'], beta: [] },+ externalForward: {},+ }),+ );++ const index = new BacklinkIndex({ projectDir, contentDir });+ const warn = vi.spyOn(getLogger('backlinks'), 'warn');+ try {+ expect(await index.loadFromDisk()).toBe(false);+ expect(warn.mock.calls).toEqual(cache.expectedWarnings);+ } finally {+ warn.mockRestore();+ }+ await index.rebuildFromDisk();+ expect(index.getForwardLinks('alpha')).toEqual(['beta']);+ expect(index.getRenameSourceInventory().find((entry) => entry.docName === 'alpha')).toEqual(+ expect.objectContaining({ wikiTargets: ['beta'] }),+ );+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('a versionless pre-upgrade cache is rejected so boot cold-rebuilds instead of serving stale keys', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-version-guard-'));const contentDir = join(projectDir, 'content');@@ -1797,7 +1871,7 @@ describe('BacklinkIndex with markdown links', () => {});describe('reconcileWithDisk', () => {- test('unchanged files are not re-parsed; mtime snapshot is preserved', async () => {+ test('unchanged snapshot files reuse persisted source links without rereading', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-reconcile-'));const contentDir = join(projectDir, 'content');mkdirSync(contentDir, { recursive: true });@@ -1823,6 +1897,9 @@ describe('reconcileWithDisk', () => {expect(reloaded.getBacklinks('beta')).toEqual([{ source: 'alpha', anchor: null, snippet: 'Links to beta.' },]);+ expect(+ reloaded.getRenameSourceInventory().find((entry) => entry.docName === 'alpha'),+ ).toEqual(expect.objectContaining({ wikiTargets: ['beta'] }));} finally {rmSync(projectDir, { recursive: true, force: true });}@@ -1988,6 +2065,33 @@ describe('computeBrokenOutboundLinks', () => {]);});+ test.each(['guide', 'Guide', 'runbook'])(+ 'does not resolve fuzzy [[%s]] against global skill documents',+ (target) => {+ const global = skillLiveDocName('global', 'guide');+ const admitted = new Set([global, `${global}/references/runbook`]);+ expect(computeBrokenOutboundLinks(`[[${target}]]`, 'notes/a', admitted)).toEqual([+ { href: `[[${target}]]`, resolvedTo: target, reason: 'no-such-doc' },+ ]);+ },+ );++ test('keeps explicit global and fuzzy project skill references admitted', () => {+ const global = skillLiveDocName('global', 'guide');+ const globalReference = `${global}/references/runbook`;+ const projectReference = '.agents/skills/project/references/project-guide';+ const markdown = `[[${global}]] [[${globalReference}]] [[Project Guide]]`;+ expect(+ computeBrokenOutboundLinks(markdown, 'notes/a', [global, globalReference, projectReference]),+ ).toEqual([]);+ });++ test('markdown document links stay literal when the wiki target resolves fuzzily', () => {+ expect(+ computeBrokenOutboundLinks('[[guide]] [guide](./guide.md)', 'notes/a', ['archive/guide']),+ ).toEqual([{ href: './guide.md', resolvedTo: 'notes/guide', reason: 'no-such-doc' }]);+ });+test('a dotted-filename document target is not reported broken', () => {const md = 'See [[acp.daemon]] here.';const admitted = new Set(['notes/acp.daemon', 'notes/a']);diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex ac953105b..ffe5b74bd 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -3,8 +3,6 @@ import { readdir, readFile, stat, writeFile } from 'node:fs/promises';import { dirname, join, relative, resolve } from 'node:path';import {type BrokenLinkReason,- buildPagesByBasenameIndex,- buildPagesBySlugIndex,classifyMarkdownHref,classifyWikiLinkTarget,extractSkillRefs,@@ -42,6 +40,7 @@ import { readMarkdownLinkAt, readWikiLinkAt } from './link-syntax.ts';import { extractLocalTargetOccurrences } from './local-target-occurrences.ts';import { getLogger } from './logger.ts';import { toPosix } from './path-utils.ts';+import { buildProjectWikiLinkLookup } from './project-wiki-link-lookup.ts';const log = getLogger('backlinks');@@ -157,10 +156,12 @@ interface BranchGraphState {externalForward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;externalBackward: Map<string, Map<string, { label: string | null; snippet: string | null }>>;skillRefs: Map<string, Set<string>>;- epoch: number;+ sourceLinks: Map<string, readonly ExtractedWikiLink[]>;+ inventoryEpoch: number;}-const SNAPSHOT_VERSION = 3;+const SNAPSHOT_VERSION = 4;+const EMPTY_BUNDLE_NEIGHBORS: ReadonlySet<string> = new Set();interface SerializedBranchGraphState {version?: number;@@ -171,6 +172,7 @@ interface SerializedBranchGraphState {Array<{ url: string; label: string | null; snippet: string | null }>>;skillRefs?: Record<string, string[]>;+ sourceLinks?: Record<string, ExtractedWikiLink[]>;mtimes?: Record<string, number>;}@@ -179,6 +181,7 @@ interface BacklinkIndexOptions {contentDir: string;contentFilter?: ContentFilter;getFileOracle?: () => GraphFileOracle | undefined;+ documentNames?: Iterable<string>;}function createEmptyState(): BranchGraphState {@@ -188,17 +191,36 @@ function createEmptyState(): BranchGraphState {externalForward: new Map(),externalBackward: new Map(),skillRefs: new Map(),- epoch: 0,+ sourceLinks: new Map(),+ inventoryEpoch: 0,};}-function isUndecidedTarget(state: BranchGraphState, target: string): boolean {- const sources = state.backward.get(target);- if (!sources || sources.size === 0) return false;- for (const meta of sources.values()) {- if (meta.rawWikiTarget !== true) return false;- }- return true;+function requireSourceLinks(state: BranchGraphState, source: string): readonly ExtractedWikiLink[] {+ const links = state.sourceLinks.get(source);+ if (!links) throw new Error(`Missing source links for indexed document ${source}`);+ return links;+}++interface ResolvedGraphState {+ inventoryEpoch: number;+ forward: Map<string, Set<string>>;+ backward: Map<string, Map<string, BackwardLinkMeta>>;+ sortedBacklinks: Map<string, BacklinkEntry[]>;+ wikiSourcesByPathSlug: Map<string, Set<string>>;+ wikiSourcesByBasenameSlug: Map<string, Set<string>>;+ wikiSourcesByFolder: Map<string, Set<string>>;+ wikiKeysBySource: Map<+ string,+ { paths: Set<string>; basenames: Set<string>; folders: Set<string> }+ >;+}++interface CachedDocumentLookup {+ epoch: number;+ lookup: WikiLinkLookupIndex;+ slugBuckets: Map<string, Set<string>>;+ basenameBuckets: Map<string, Set<string>>;}export function parseSkillBundleDocAnyScope(@@ -241,6 +263,10 @@ function mergeLinkMeta(};}+function compareBacklinkSources(a: string, b: string): number {+ return a.localeCompare(b) || (a < b ? -1 : a > b ? 1 : 0);+}+function getRepresentativeAnchor(sources: Map<string, BackwardLinkMeta> | undefined,): string | null {@@ -939,21 +965,10 @@ export function computeBrokenOutboundLinks(}};- let pagesBySlug: ReadonlyMap<string, string> | undefined;- let pagesByBasename: ReadonlyMap<string, string> | undefined;- const wikiLookup: WikiLinkLookupIndex = {- pages: admitted,- get pagesBySlug() {- pagesBySlug ??= buildPagesBySlugIndex(admitted, toWikiLinkSlug);- return pagesBySlug;- },- get pagesByBasename() {- pagesByBasename ??= buildPagesByBasenameIndex(admitted, toWikiLinkSlug);- return pagesByBasename;- },- };+ let wikiLookup: WikiLinkLookupIndex | undefined;const recordWikiLink = (target: string, anchor: string | null): void => {+ wikiLookup ??= buildProjectWikiLinkLookup(admitted);const resolved = resolveWikiLinkTarget(target, anchor, wikiLookup);if (resolved?.kind !== 'doc') return;if (@@ -1055,6 +1070,12 @@ function serializeState(state: BranchGraphState): SerializedBranchGraphState {skillRefs: Object.fromEntries([...state.skillRefs.entries()].map(([source, names]) => [source, [...names].sort()]),),+ sourceLinks: Object.fromEntries(+ [...state.sourceLinks.entries()].map(([source, links]) => [+ source,+ links.map((link) => ({ ...link })),+ ]),+ ),};}@@ -1132,7 +1153,26 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {skillRefs: new Map(Object.entries(data.skillRefs ?? {}).map(([source, names]) => [source, new Set(names)]),),- epoch: 0,+ sourceLinks: new Map(+ Object.entries(data.sourceLinks ?? {}).map(([source, links]) => [+ source,+ links.map((link) => ({+ target: link.target,+ anchor: link.anchor ?? null,+ snippet: link.snippet ?? null,+ sourceForm:+ link.sourceForm === 'wiki' ||+ link.sourceForm === 'markdown' ||+ link.sourceForm === 'jsx'+ ? link.sourceForm+ : undefined,+ line: cachePosition(link.line),+ column: cachePosition(link.column),+ rawWikiTarget: link.rawWikiTarget === true,+ })),+ ]),+ ),+ inventoryEpoch: 0,};}@@ -1153,12 +1193,12 @@ export class BacklinkIndex {private readonly contentDir: string;private readonly contentFilter?: ContentFilter;private readonly getFileOracle: () => GraphFileOracle | undefined;+ private readonly documentNames: readonly string[];private readonly states = new Map<string, BranchGraphState>();private readonly mtimesByBranch = new Map<string, Map<string, number>>();- private readonly documentLookups = new WeakMap<- BranchGraphState,- { epoch: number; lookup: WikiLinkLookupIndex }- >();+ private readonly documentLookups = new WeakMap<BranchGraphState, CachedDocumentLookup>();+ private readonly resolvedGraphs = new WeakMap<BranchGraphState, ResolvedGraphState>();+ private readonly fixedDocumentNames: ReadonlySet<string>;private activeBranch = 'main';constructor(options: BacklinkIndexOptions) {@@ -1166,6 +1206,8 @@ export class BacklinkIndex {this.contentDir = options.contentDir;this.contentFilter = options.contentFilter;this.getFileOracle = options.getFileOracle ?? (() => undefined);+ this.documentNames = [...(options.documentNames ?? [])];+ this.fixedDocumentNames = new Set(this.documentNames);this.states.set(this.activeBranch, createEmptyState());}@@ -1235,7 +1277,10 @@ export class BacklinkIndex {return neighbors;}- private bundleNeighbors(docName: string, branch = this.activeBranch): Set<string> {+ private bundleNeighbors(docName: string, branch = this.activeBranch): ReadonlySet<string> {+ if (docName[0] !== '.' && !docName.startsWith(MANAGED_ARTIFACT_PREFIX_SKILL))+ return EMPTY_BUNDLE_NEIGHBORS;+ if (!parseSkillBundleDocAnyScope(docName)) return EMPTY_BUNDLE_NEIGHBORS;const neighbors = this.structuralBundleNeighbors(docName, branch);for (const n of this.skillRefNeighbors(docName, branch)) neighbors.add(n);return neighbors;@@ -1267,6 +1312,7 @@ export class BacklinkIndex {private registerNodeOnly(docName: string, branch = this.activeBranch): void {const state = this.getState(branch);+ const added = !state.forward.has(docName);const priorTargets = state.forward.get(docName) ?? new Set<string>();const priorExternalTargets = state.externalForward.get(docName) ?? new Map();for (const target of priorTargets) {@@ -1282,8 +1328,10 @@ export class BacklinkIndex {if (sources.size === 0) state.externalBackward.delete(url);}state.forward.set(docName, new Set());- state.epoch++;+ state.sourceLinks.set(docName, []);state.externalForward.set(docName, new Map());+ if (added) this.inventoryChanged(state, docName, true);+ this.refreshResolvedSource(state, docName, branch);}registerGlobalSkillBundleNode(docName: string, branch = this.activeBranch): void {@@ -1296,6 +1344,7 @@ export class BacklinkIndex {links: ExtractedWikiLink[],externalLinks: ExtractedExternalLink[] = [],branch = this.activeBranch,+ sourceLinks: readonly ExtractedWikiLink[] = links,): void {if (isLinkIndexExcludedDoc(docName)) return;if (parseGlobalSkillBundleDoc(docName)) {@@ -1303,6 +1352,7 @@ export class BacklinkIndex {return;}const state = this.getState(branch);+ const added = !state.forward.has(docName);const priorTargets = state.forward.get(docName) ?? new Set<string>();const priorExternalTargets = state.externalForward.get(docName) ?? new Map();@@ -1323,7 +1373,10 @@ export class BacklinkIndex {const nextTargets = new Set<string>();const nextExternalTargets = new Map<string, { label: string | null; snippet: string | null }>();state.forward.set(docName, nextTargets);- state.epoch++;+ state.sourceLinks.set(+ docName,+ sourceLinks.map((link) => ({ ...link })),+ );state.externalForward.set(docName, nextExternalTargets);for (const link of links) {@@ -1365,6 +1418,8 @@ export class BacklinkIndex {});}}+ if (added) this.inventoryChanged(state, docName, true);+ this.refreshResolvedSource(state, docName, branch);}updateDocumentFromMarkdown(docName: string, markdown: string, branch = this.activeBranch): void {@@ -1400,7 +1455,11 @@ export class BacklinkIndex {...mdExternalLinks.filter((link) => !externalSeen.has(link.url)),];this.recordSkillRefs(docName, body, branch);- this.updateDocument(docName, merged, mergedExternal, branch);+ this.updateDocument(docName, merged, mergedExternal, branch, [+ ...wikiLinks,+ ...mdLinks,+ ...jsxLinks,+ ]);} catch (err) {log.warn({ docName, err }, `Failed to scan ${docName} for link extraction`);this.deleteDocument(docName, branch);@@ -1424,10 +1483,11 @@ export class BacklinkIndex {sources.delete(docName);if (sources.size === 0) state.externalBackward.delete(url);}- state.forward.delete(docName);- state.epoch++;+ const deleted = state.forward.delete(docName);state.externalForward.delete(docName);state.skillRefs.delete(docName);+ state.sourceLinks.delete(docName);+ if (deleted) this.inventoryChanged(state, docName, false);}renameDocument(@@ -1441,15 +1501,19 @@ export class BacklinkIndex {}getBacklinks(target: string, branch = this.activeBranch): BacklinkEntry[] {- const state = this.getState(branch);- const sources = state.backward.get(target);+ const resolved = this.resolvedState(branch);+ const sources = resolved.backward.get(target);+ const structural = this.bundleNeighbors(target, branch);+ if (structural.size === 0) {+ return resolved.sortedBacklinks.get(target)?.map((entry) => ({ ...entry })) ?? [];+ }const entries = new Map<string, BacklinkEntry>();if (sources) {for (const [source, meta] of sources) {entries.set(source, { source, anchor: meta.anchor, snippet: meta.snippet });}}- for (const partner of this.bundleNeighbors(target, branch)) {+ for (const partner of structural) {if (!entries.has(partner))entries.set(partner, { source: partner, anchor: null, snippet: null });}@@ -1457,8 +1521,7 @@ export class BacklinkIndex {}getBacklinkCount(target: string, branch = this.activeBranch): number {- const state = this.getState(branch);- const authored = state.backward.get(target);+ const authored = this.resolvedBackward(branch).get(target);const structural = this.bundleNeighbors(target, branch);if (structural.size === 0) return authored?.size ?? 0;const union = new Set(authored?.keys() ?? []);@@ -1467,14 +1530,14 @@ export class BacklinkIndex {}getForwardLinks(source: string, branch = this.activeBranch): string[] {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const targets = new Set(state.forward.get(source) ?? new Set<string>());for (const partner of this.bundleNeighbors(source, branch)) targets.add(partner);return [...targets].sort((a, b) => a.localeCompare(b));}getForwardLinkEntries(source: string, branch = this.activeBranch): ForwardLinkEntry[] {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const internalEntries: ForwardLinkEntry[] = this.getForwardLinks(source, branch).map((target) => ({kind: 'doc',@@ -1497,7 +1560,7 @@ export class BacklinkIndex {}getOrphans(allDocs: string[], mode: OrphanMode = 'both', branch = this.activeBranch): string[] {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const skillDocsWithReference = new Set<string>();for (const candidate of state.forward.keys()) {const parsed = parseSkillBundleDocAnyScope(candidate);@@ -1524,7 +1587,7 @@ export class BacklinkIndex {}getHubs(limit = 20, branch = this.activeBranch): HubEntry[] {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);return [...state.backward.entries()].map(([docName, sources]) => ({ docName, count: sources.size })).sort((a, b) =>@@ -1537,13 +1600,26 @@ export class BacklinkIndex {return [...this.getState(branch).forward.keys()];}+ getRenameSourceInventory(+ branch = this.activeBranch,+ ): Array<{ docName: string; wikiTargets: string[]; indexedMtimeMs: number | undefined }> {+ const state = this.getState(branch);+ const mtimes = this.mtimesByBranch.get(branch);+ return [...state.forward].map(([docName]) => {+ const wikiTargets = requireSourceLinks(state, docName)+ .filter((link) => link.sourceForm === 'wiki')+ .map((link) => link.target);+ return { docName, wikiTargets, indexedMtimeMs: mtimes?.get(docName) };+ });+ }+getDeadLinks(admittedDocs: Iterable<string>,sourceDocNames?: readonly string[],branch = this.activeBranch,knownFolderPaths?: Iterable<string>,): DeadLinkEntry[] {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const admittedDocSet = new Set(admittedDocs);const sourceDocSet = sourceDocNames?.length ? new Set(sourceDocNames) : null;const folderPathSet = deriveFolderPathsFromDocNames([@@ -1598,47 +1674,287 @@ export class BacklinkIndex {private documentLookup(branch = this.activeBranch): WikiLinkLookupIndex {const state = this.getState(branch);const cached = this.documentLookups.get(state);- if (cached?.epoch === state.epoch) return cached.lookup;+ if (cached?.epoch === state.inventoryEpoch) return cached.lookup;+ const lookup = buildProjectWikiLinkLookup([...state.forward.keys(), ...this.documentNames]);+ const slugBuckets = new Map<string, Set<string>>();+ const basenameBuckets = new Map<string, Set<string>>();+ for (const page of lookup.pages) {+ if (parseGlobalSkillBundleDoc(page)) continue;+ const pathSlug = toWikiLinkSlug(page);+ const basenameSlug = toWikiLinkSlug(page.slice(page.lastIndexOf('/') + 1));+ if (pathSlug) {+ const bucket = slugBuckets.get(pathSlug) ?? new Set<string>();+ bucket.add(page);+ slugBuckets.set(pathSlug, bucket);+ }+ if (basenameSlug) {+ const bucket = basenameBuckets.get(basenameSlug) ?? new Set<string>();+ bucket.add(page);+ basenameBuckets.set(basenameSlug, bucket);+ }+ }+ const mutableLookup: WikiLinkLookupIndex = {+ pages: new Set(lookup.pages),+ pagesBySlug: new Map(lookup.pagesBySlug),+ pagesByBasename: new Map(lookup.pagesByBasename),+ };+ this.documentLookups.set(state, {+ epoch: state.inventoryEpoch,+ lookup: mutableLookup,+ slugBuckets,+ basenameBuckets,+ });+ return mutableLookup;+ }- const pages = new Set(state.forward.keys());- const lookup: WikiLinkLookupIndex = {- pages,- pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),- pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ private updateDocumentLookup(state: BranchGraphState, docName: string, added: boolean): void {+ const cached = this.documentLookups.get(state);+ if (!cached || cached.epoch !== state.inventoryEpoch - 1) return;+ cached.epoch = state.inventoryEpoch;+ if (!added && this.fixedDocumentNames.has(docName)) return;+ const pages = cached.lookup.pages as Set<string>;+ if (added ? pages.has(docName) : !pages.has(docName)) return;+ if (added) pages.add(docName);+ else pages.delete(docName);+ if (parseGlobalSkillBundleDoc(docName)) return;+ const pathSlug = toWikiLinkSlug(docName);+ const basenameSlug = toWikiLinkSlug(docName.slice(docName.lastIndexOf('/') + 1));+ const refresh = (+ key: string,+ buckets: Map<string, Set<string>>,+ winners: ReadonlyMap<string, string>,+ ) => {+ if (!key) return;+ const bucket = buckets.get(key) ?? new Set<string>();+ if (added) bucket.add(docName);+ else bucket.delete(docName);+ if (bucket.size) buckets.set(key, bucket);+ else buckets.delete(key);+ const mutableWinners = winners as Map<string, string>;+ const best = [...bucket].sort()[0];+ if (best) mutableWinners.set(key, best);+ else mutableWinners.delete(key);};- this.documentLookups.set(state, { epoch: state.epoch, lookup });- return lookup;+ refresh(pathSlug, cached.slugBuckets, cached.lookup.pagesBySlug);+ refresh(basenameSlug, cached.basenameBuckets, cached.lookup.pagesByBasename ?? new Map());}- private undecidedTargetResolves(target: string, branch = this.activeBranch): boolean {- return resolveWikiLinkTarget(target, null, this.documentLookup(branch))?.kind === 'doc';+ private inventoryChanged(state: BranchGraphState, docName: string, added: boolean): void {+ state.inventoryEpoch++;+ this.updateDocumentLookup(state, docName, added);+ const resolved = this.resolvedGraphs.get(state);+ if (!resolved || resolved.inventoryEpoch !== state.inventoryEpoch - 1) return;+ resolved.inventoryEpoch = state.inventoryEpoch;+ const pathSlug = toWikiLinkSlug(docName) || docName;+ const basenameSlug = toWikiLinkSlug(docName.slice(docName.lastIndexOf('/') + 1));+ const affected = new Set<string>([+ ...(resolved.wikiSourcesByPathSlug.get(pathSlug) ?? []),+ ...(resolved.wikiSourcesByBasenameSlug.get(basenameSlug) ?? []),+ ]);+ const slash = docName.lastIndexOf('/');+ if (slash !== -1) {+ const parent = docName.slice(0, slash);+ const leaf = docName.slice(slash + 1);+ if (leaf === 'index' || leaf === parent.slice(parent.lastIndexOf('/') + 1)) {+ for (const source of resolved.wikiSourcesByFolder.get(parent) ?? []) affected.add(source);+ }+ }+ affected.add(docName);+ const lookup = this.documentLookupForResolved(state);+ const changedTargets = new Set<string>();+ for (const source of affected) {+ for (const target of this.resolveSource(state, resolved, source, lookup))+ changedTargets.add(target);+ }+ for (const target of changedTargets) this.refreshSortedBacklinks(resolved, target);+ }++ private documentLookupForResolved(state: BranchGraphState): WikiLinkLookupIndex {+ const cached = this.documentLookups.get(state);+ if (!cached || cached.epoch !== state.inventoryEpoch) {+ throw new Error('Resolved link graph has no matching document lookup');+ }+ return cached.lookup;+ }++ private resolveSource(+ state: BranchGraphState,+ resolved: ResolvedGraphState,+ source: string,+ lookup: WikiLinkLookupIndex,+ ): Set<string> {+ const priorKeys = resolved.wikiKeysBySource.get(source);+ if (priorKeys) {+ for (const [keys, index] of [+ [priorKeys.paths, resolved.wikiSourcesByPathSlug],+ [priorKeys.basenames, resolved.wikiSourcesByBasenameSlug],+ [priorKeys.folders, resolved.wikiSourcesByFolder],+ ] as const) {+ for (const key of keys) {+ const sources = index.get(key);+ sources?.delete(source);+ if (sources?.size === 0) index.delete(key);+ }+ }+ }+ const changedTargets = new Set(resolved.forward.get(source) ?? []);+ for (const target of changedTargets) {+ const sources = resolved.backward.get(target);+ sources?.delete(source);+ if (sources?.size === 0) resolved.backward.delete(target);+ }+ const targets = new Set<string>();+ if (state.forward.has(source)) resolved.forward.set(source, targets);+ else resolved.forward.delete(source);+ const wikiKeys = {+ paths: new Set<string>(),+ basenames: new Set<string>(),+ folders: new Set<string>(),+ };+ const sourceLinks = state.forward.has(source) ? requireSourceLinks(state, source) : [];+ for (const meta of sourceLinks) {+ const rawTarget = meta.target;+ if (!rawTarget) continue;+ let target = rawTarget;+ if (meta.sourceForm === 'wiki' || meta.sourceForm === undefined) {+ const trimmed = rawTarget.trim();+ for (const form of [trimmed, trimmed.replace(/\.(md|mdx)$/i, '')]) {+ const slug = toWikiLinkSlug(form) || form;+ wikiKeys.paths.add(slug);+ if (!form.includes('/')) wikiKeys.basenames.add(slug);+ wikiKeys.folders.add(form);+ }+ const canonical = resolveWikiLinkTargetDocName(rawTarget, lookup);+ if (meta.rawWikiTarget === true && canonical === undefined) continue;+ target = canonical ?? rawTarget;+ }+ targets.add(target);+ changedTargets.add(target);+ let sources = resolved.backward.get(target);+ if (!sources) {+ sources = new Map();+ resolved.backward.set(target, sources);+ }+ sources.set(source, mergeLinkMeta(sources.get(source), meta));+ }+ if (state.forward.has(source)) {+ resolved.wikiKeysBySource.set(source, wikiKeys);+ for (const [keys, index] of [+ [wikiKeys.paths, resolved.wikiSourcesByPathSlug],+ [wikiKeys.basenames, resolved.wikiSourcesByBasenameSlug],+ [wikiKeys.folders, resolved.wikiSourcesByFolder],+ ] as const) {+ for (const key of keys) {+ const sources = index.get(key) ?? new Set<string>();+ sources.add(source);+ index.set(key, sources);+ }+ }+ } else {+ resolved.wikiKeysBySource.delete(source);+ }+ return changedTargets;+ }++ private refreshSortedBacklinks(resolved: ResolvedGraphState, target: string): void {+ const sources = resolved.backward.get(target);+ if (!sources) {+ resolved.sortedBacklinks.delete(target);+ return;+ }+ resolved.sortedBacklinks.set(+ target,+ Array.from(sources, ([source, meta]) => ({+ source,+ anchor: meta.anchor,+ snippet: meta.snippet,+ })).sort((a, b) => compareBacklinkSources(a.source, b.source)),+ );+ }++ private updateSortedBacklink(resolved: ResolvedGraphState, target: string, source: string): void {+ const meta = resolved.backward.get(target)?.get(source);+ const list = resolved.sortedBacklinks.get(target) ?? [];+ let low = 0;+ let high = list.length;+ while (low < high) {+ const mid = (low + high) >>> 1;+ if (compareBacklinkSources((list[mid] as BacklinkEntry).source, source) < 0) low = mid + 1;+ else high = mid;+ }+ const present = list[low]?.source === source;+ if (meta)+ list.splice(low, present ? 1 : 0, { source, anchor: meta.anchor, snippet: meta.snippet });+ else if (present) list.splice(low, 1);+ if (list.length > 0) resolved.sortedBacklinks.set(target, list);+ else resolved.sortedBacklinks.delete(target);+ }++ private refreshResolvedSource(state: BranchGraphState, source: string, branch: string): void {+ const resolved = this.resolvedGraphs.get(state);+ if (resolved?.inventoryEpoch !== state.inventoryEpoch) return;+ for (const target of this.resolveSource(state, resolved, source, this.documentLookup(branch)))+ this.updateSortedBacklink(resolved, target, source);+ }++ private resolvedState(branch: string): ResolvedGraphState {+ const state = this.getState(branch);+ const resolved = this.resolvedGraphs.get(state);+ if (resolved?.inventoryEpoch === state.inventoryEpoch) return resolved;+ this.resolvedGraph(branch);+ const rebuilt = this.resolvedGraphs.get(state);+ if (!rebuilt) throw new Error('Resolved link graph was not created');+ return rebuilt;+ }++ private resolvedBackward(branch: string): ResolvedGraphState['backward'] {+ return this.resolvedState(branch).backward;+ }++ private resolvedGraph(branch = this.activeBranch): ResolvedGraphState & BranchGraphState {+ const state = this.getState(branch);+ let resolved = this.resolvedGraphs.get(state);+ if (resolved?.inventoryEpoch !== state.inventoryEpoch) {+ resolved = {+ inventoryEpoch: state.inventoryEpoch,+ forward: new Map(),+ backward: new Map(),+ sortedBacklinks: new Map(),+ wikiSourcesByPathSlug: new Map(),+ wikiSourcesByBasenameSlug: new Map(),+ wikiSourcesByFolder: new Map(),+ wikiKeysBySource: new Map(),+ };+ const lookup = this.documentLookup(branch);+ for (const source of state.forward.keys())+ this.resolveSource(state, resolved, source, lookup);+ for (const target of resolved.backward.keys()) this.refreshSortedBacklinks(resolved, target);+ this.resolvedGraphs.set(state, resolved);+ }+ return { ...state, ...resolved };}getLinkGraph(branch = this.activeBranch): {nodes: GraphNode[];links: Array<{ source: string; target: string }>;} {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const nodes = new Map<string, GraphNode>();const links: Array<{ source: string; target: string }> = [];-- for (const [source, targets] of state.forward) {- nodes.set(source, {+ const addDocumentNode = (docName: string) => {+ if (nodes.has(docName)) return;+ nodes.set(docName, {kind: 'doc',- id: source,- docName: source,- anchor: getRepresentativeAnchor(state.backward.get(source)),+ id: docName,+ docName,+ anchor: getRepresentativeAnchor(state.backward.get(docName)),});+ };++ for (const [source, targets] of state.forward) {+ addDocumentNode(source);for (const target of targets) {- if (isUndecidedTarget(state, target) && !this.undecidedTargetResolves(target, branch)) {- continue;- }- nodes.set(target, {- kind: 'doc',- id: target,- docName: target,- anchor: getRepresentativeAnchor(state.backward.get(target)),- });+ addDocumentNode(target);links.push({ source, target });}}@@ -1694,7 +2010,7 @@ export class BacklinkIndex {nodes: GraphNode[];links: Array<{ source: string; target: string }>;} {- const state = this.getState(branch);+ const state = this.resolvedGraph(branch);const externalLabelsByUrl = new Map<string, string | null>();for (const targets of state.externalForward.values()) {for (const [url, meta] of targets) {@@ -1720,9 +2036,6 @@ export class BacklinkIndex {}} else {for (const target of state.forward.get(current.nodeId) ?? new Set<string>()) {- if (isUndecidedTarget(state, target) && !this.undecidedTargetResolves(target, branch)) {- continue;- }neighbors.add(target);}for (const url of state.externalForward.get(current.nodeId)?.keys() ?? []) {@@ -1814,6 +2127,19 @@ export class BacklinkIndex {const raw = await readFile(filePath, 'utf-8');const parsed = JSON.parse(raw) as SerializedBranchGraphState;if (parsed.version !== SNAPSHOT_VERSION) return false;+ if (+ !parsed.sourceLinks ||+ Object.entries(parsed.forward ?? {}).some(([source, targets]) => {+ const links = parsed.sourceLinks?.[source];+ return !Array.isArray(links) || (targets.length > 0 && links.length === 0);+ })+ ) {+ log.warn(+ { branch },+ `Incomplete backlink cache snapshot for ${branch}; rebuilding from disk`,+ );+ return false;+ }this.states.set(branch, deserializeState(parsed));if (parsed.mtimes) {this.mtimesByBranch.set(branch, new Map(Object.entries(parsed.mtimes)));@@ -1903,7 +2229,7 @@ export class BacklinkIndex {const externalTargets = new Map<string, { label: string | null; snippet: string | null }>();this.recordSkillRefsInto(state, docName, body);state.forward.set(docName, targets);- state.epoch++;+ state.sourceLinks.set(docName, [...wikiLinks, ...mdLinks, ...jsxLinks]);state.externalForward.set(docName, externalTargets);for (const link of links) {if (!link.target) continue;@@ -1994,7 +2320,13 @@ export class BacklinkIndex {changedDocs: Array<{ docName: string; filePath: string }>;}> {if (!existsSync(this.contentDir))- return { added: 0, updated: 0, deleted: 0, deletedDocNames: [], changedDocs: [] };+ return {+ added: 0,+ updated: 0,+ deleted: 0,+ deletedDocNames: [],+ changedDocs: [],+ };const storedMtimes = this.mtimesByBranch.get(branch) ?? new Map<string, number>();const rawDocs: Array<{ docName: string; filePath: string }> = [];@@ -2012,8 +2344,12 @@ export class BacklinkIndex {let added = 0;let updated = 0;- const toProcess: Array<{ docName: string; filePath: string; mtimeMs: number; isNew: boolean }> =- [];+ const toProcess: Array<{+ docName: string;+ filePath: string;+ mtimeMs: number;+ isNew: boolean;+ }> = [];const statResults = await Promise.allSettled(docs.map(async ({ docName, filePath }) => ({docName,@@ -2025,11 +2361,17 @@ export class BacklinkIndex {if (result.status === 'rejected') continue;const { docName, filePath, mtimeMs } = result.value;const storedMtime = storedMtimes.get(docName);- if (storedMtime !== undefined && storedMtime === mtimeMs) {+ const unchanged = storedMtime !== undefined && storedMtime === mtimeMs;+ if (unchanged) {newMtimes.set(docName, mtimeMs);continue;}- toProcess.push({ docName, filePath, mtimeMs, isNew: storedMtime === undefined });+ toProcess.push({+ docName,+ filePath,+ mtimeMs,+ isNew: storedMtime === undefined,+ });}const BATCH_SIZE = 50;diff --git a/packages/server/src/backlink-resolution.test.ts b/packages/server/src/backlink-resolution.test.tsnew file mode 100644index 000000000..44f378b3f--- /dev/null+++ b/packages/server/src/backlink-resolution.test.ts@@ -0,0 +1,379 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { LOCAL_DIR, OK_DIR, skillLiveDocName } from '@inkeep/open-knowledge-core';+import { afterEach, describe, expect, test } from 'vitest';+import { BacklinkIndex } from './backlink-index.ts';++const roots: string[] = [];+function createIndex(): { index: BacklinkIndex; projectDir: string } {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-resolved-links-'));+ roots.push(projectDir);+ return { index: new BacklinkIndex({ projectDir, contentDir: projectDir }), projectDir };+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('resolved document relationships', () => {+ test('slug-collision targets stay stable when file inventory order changes', () => {+ for (const pages of [+ ['a/b', 'a-b'],+ ['a-b', 'a/b'],+ ]) {+ const { index } = createIndex();+ for (const name of pages) index.updateDocumentFromMarkdown(name, '# Target');+ index.updateDocumentFromMarkdown('source', '[[A B]]');+ expect(index.getForwardLinks('source')).toEqual(['a-b']);+ expect(index.getBacklinkCount('a-b')).toBe(1);+ expect(index.getBacklinkCount('a/b')).toBe(0);+ }+ });++ test('all graph views merge spelling variants and retain the representative source metadata', () => {+ const { index } = createIndex();+ index.updateDocumentFromMarkdown('notes/beta', '# Beta');+ index.updateDocumentFromMarkdown('source', 'See [[beta#intro]] and [[NOTES/BETA.md|Beta]].');+ index.updateDocumentFromMarkdown('second', 'See [[beta.mdx]].');+ expect(index.getBacklinks('notes/beta')).toEqual([+ { source: 'second', anchor: null, snippet: 'See beta.mdx.' },+ { source: 'source', anchor: 'intro', snippet: 'See beta#intro and Beta.' },+ ]);+ expect(index.getBacklinkCount('notes/beta')).toBe(2);+ expect(index.getBacklinks('beta')).toEqual([]);+ expect(index.getForwardLinks('source')).toEqual(['notes/beta']);+ expect(index.getForwardLinkEntries('source')).toEqual([+ { kind: 'doc', target: 'notes/beta', anchor: 'intro', snippet: 'See beta#intro and Beta.' },+ ]);+ expect(index.getOrphans(['notes/beta', 'source', 'second'], 'incoming')).toEqual([+ 'second',+ 'source',+ ]);+ expect(index.getOrphans(['notes/beta', 'source', 'second'], 'outgoing')).toEqual([+ 'notes/beta',+ ]);+ expect(index.getHubs()).toEqual([{ docName: 'notes/beta', count: 2 }]);+ expect(index.getLinkGraph().links).toEqual([+ { source: 'source', target: 'notes/beta' },+ { source: 'second', target: 'notes/beta' },+ ]);+ expect(index.getLinkGraphNeighborhood('notes/beta', 1).nodes.map((node) => node.id)).toEqual([+ 'notes/beta',+ 'second',+ 'source',+ ]);+ });++ test('literal Markdown and JSX targets remain literal while wiki assets stay out of the graph', () => {+ const { index } = createIndex();+ index.updateDocumentFromMarkdown('notes/beta', '# Beta');+ index.updateDocumentFromMarkdown('wiki', '[[beta]] [[logo.png]]');+ index.updateDocumentFromMarkdown('markdown', '[Beta](/beta.md)');+ index.updateDocumentFromMarkdown('jsx', '<Mirror src="beta" anchor="intro" />');+ expect(index.getForwardLinks('wiki')).toEqual(['notes/beta']);+ expect(index.getForwardLinks('markdown')).toEqual(['beta']);+ expect(index.getForwardLinks('jsx')).toEqual(['beta']);+ expect(index.getBacklinks('notes/beta').map((entry) => entry.source)).toEqual(['wiki']);+ expect(index.getBacklinks('beta').map((entry) => entry.source)).toEqual(['jsx', 'markdown']);+ expect(index.getLinkGraph().nodes.map((node) => node.id)).not.toContain('logo.png');+ });++ test('same-source wiki and literal keys keep separate identities before and after warm snapshot reconciliation', async () => {+ const { index, projectDir } = createIndex();+ mkdirSync(join(projectDir, 'notes'));+ writeFileSync(join(projectDir, 'notes/beta.md'), '# Beta');+ writeFileSync(join(projectDir, 'source.md'), '[[beta#intro]] and [literal](/beta.md#literal)');+ await index.rebuildFromDisk();+ const verify = (current: BacklinkIndex) => {+ expect(current.getForwardLinkEntries('source')).toEqual([+ expect.objectContaining({ kind: 'doc', target: 'beta', anchor: 'literal' }),+ expect.objectContaining({ kind: 'doc', target: 'notes/beta', anchor: 'intro' }),+ ]);+ expect(current.getBacklinkCount('notes/beta')).toBe(1);+ expect(current.getBacklinkCount('beta')).toBe(1);+ expect(current.getDeadLinks(['source', 'notes/beta'])).toEqual([+ {+ target: 'beta',+ sources: [expect.objectContaining({ source: 'source', sourceForm: 'markdown' })],+ },+ ]);+ };+ verify(index);+ await index.saveToDisk();+ const reloaded = new BacklinkIndex({ projectDir, contentDir: projectDir });+ expect(await reloaded.loadFromDisk()).toBe(true);+ const diff = await reloaded.reconcileWithDisk();+ expect(diff).toMatchObject({+ added: 0,+ updated: 0,+ deleted: 0,+ changedDocs: [],+ });+ expect(reloaded.getRenameSourceInventory().find((entry) => entry.docName === 'source')).toEqual(+ expect.objectContaining({ wikiTargets: ['beta'] }),+ );+ verify(reloaded);+ reloaded.updateDocumentFromMarkdown('source', '[literal](/beta.md#literal)');+ expect(reloaded.getForwardLinks('source')).toEqual(['beta']);+ expect(reloaded.getBacklinkCount('notes/beta')).toBe(0);+ });++ test('warm snapshot reconciliation preserves forward links, dead links and later fuzzy winners', async () => {+ const { index, projectDir } = createIndex();+ mkdirSync(join(projectDir, 'notes'));+ const docs = {+ 'notes/beta': '# Beta',+ jsx: '<Mirror src="beta" anchor="intro" />',+ complete: '[Beta](/beta.md#intro)\n<Mirror src="beta" />',+ incomplete: '[](/beta.md)\n<Mirror src="beta" />',+ mixed: '[[beta#intro]] and [literal](/beta.md#literal)',+ };+ for (const [name, body] of Object.entries(docs))+ writeFileSync(join(projectDir, `${name}.md`), body);+ await index.rebuildFromDisk();+ const expected = Object.fromEntries(+ Object.keys(docs).map((name) => [name, index.getForwardLinkEntries(name)]),+ );+ const expectedDead = index.getDeadLinks(Object.keys(docs));+ await index.saveToDisk();+ const reloaded = new BacklinkIndex({ projectDir, contentDir: projectDir });+ expect(await reloaded.loadFromDisk()).toBe(true);+ expect(await reloaded.reconcileWithDisk()).toMatchObject({+ added: 0,+ updated: 0,+ deleted: 0,+ changedDocs: [],+ });+ for (const name of Object.keys(docs))+ expect(reloaded.getForwardLinkEntries(name)).toEqual(expected[name]);+ expect(reloaded.getDeadLinks(Object.keys(docs))).toEqual(expectedDead);+ expect(reloaded.getForwardLinkEntries('incomplete')).toEqual([+ expect.objectContaining({ target: 'beta', anchor: null, snippet: '<Mirror src="beta" />' }),+ ]);+ expect(reloaded.getForwardLinks('mixed')).toEqual(['beta', 'notes/beta']);+ reloaded.updateDocumentFromMarkdown('archive/beta', '# New fuzzy winner');+ expect(reloaded.getForwardLinks('mixed')).toEqual(['archive/beta', 'beta']);+ expect(reloaded.getForwardLinks('jsx')).toEqual(['beta']);+ expect(reloaded.getForwardLinks('complete')).toEqual(['beta']);+ });++ test('graph retains the lexically first incoming anchor under repeated fan-in', () => {+ const { index } = createIndex();+ index.updateDocumentFromMarkdown('target', '# Target');+ for (let i = 99; i >= 0; i--)+ index.updateDocumentFromMarkdown(+ `sources/${String(i).padStart(3, '0')}`,+ `[[target#anchor-${i}]]`,+ );+ const graph = index.getLinkGraph();+ expect(graph.nodes.filter((node) => node.id === 'target')).toEqual([+ { kind: 'doc', id: 'target', docName: 'target', anchor: 'anchor-0' },+ ]);+ expect(graph.links).toHaveLength(100);+ index.deleteDocument('sources/000');+ expect(index.getLinkGraph().nodes.find((node) => node.id === 'target')).toEqual({+ kind: 'doc',+ id: 'target',+ docName: 'target',+ anchor: 'anchor-1',+ });+ });++ test('snapshot v4 distinguishes wiki-only sources from colliding literal links', async () => {+ const snapshots: string[] = [];+ for (const [body, expectedTargets] of [+ ['[[beta]]', ['notes/beta']],+ ['[[beta]]\n[literal](/beta.md)', ['beta', 'notes/beta']],+ ] as const) {+ const { index, projectDir } = createIndex();+ index.updateDocumentFromMarkdown('notes/beta', '# Beta');+ index.updateDocumentFromMarkdown('source', body);+ expect(index.getForwardLinks('source')).toEqual(expectedTargets);+ await index.saveToDisk();+ snapshots.push(+ readFileSync(+ join(projectDir, OK_DIR, LOCAL_DIR, 'cache', 'main', 'backlinks.json'),+ 'utf8',+ ),+ );+ }+ expect(snapshots[0]).not.toBe(snapshots[1]);+ });++ test('a body-only update replaces edges without an inventory change', () => {+ const { index } = createIndex();+ for (const doc of ['notes/beta', 'notes/gamma'])+ index.updateDocumentFromMarkdown(doc, '# Target');+ index.updateDocumentFromMarkdown('source', '[[beta]]');+ expect(index.getBacklinkCount('notes/beta')).toBe(1);+ index.updateDocumentFromMarkdown('source', '[[GAMMA.md#next]]');+ expect(index.getBacklinks('notes/beta')).toEqual([]);+ expect(index.getBacklinkCount('notes/gamma')).toBe(1);+ expect(index.getForwardLinkEntries('source')).toEqual([+ { kind: 'doc', target: 'notes/gamma', anchor: 'next', snippet: 'GAMMA.md#next' },+ ]);+ expect(index.getOrphans(['notes/beta', 'notes/gamma'], 'incoming')).toEqual(['notes/beta']);+ expect(index.getHubs()).toEqual([{ docName: 'notes/gamma', count: 1 }]);+ expect(index.getLinkGraph().links).toEqual([{ source: 'source', target: 'notes/gamma' }]);+ expect(index.getLinkGraphNeighborhood('notes/beta', 1).nodes.map((node) => node.id)).toEqual([+ 'notes/beta',+ ]);+ });++ test('incrementally maintained relationships equal a fresh rebuild after create, delete and edit walks', () => {+ const docNames = [+ 'x',+ 'x.md',+ 'x.md.md',+ 'x-md',+ 'notes/x',+ 'notes/x.md',+ 'hub/index',+ 'hub/hub',+ 'hub.md/index',+ 'hub.md/hub.md',+ 'a/b',+ 'a-b',+ 'z/beta',+ 'a/beta',+ 'beta',+ 'beta.md',+ 'q/beta.md',+ '!!!',+ ];+ const targets = [+ 'x',+ 'x.md',+ 'X.MD',+ 'x.md.md',+ 'x.mdx',+ 'notes/x.md',+ 'hub',+ 'hub.md',+ 'a/b',+ 'A B',+ 'a b.md',+ 'beta',+ 'beta.md',+ 'BETA.mdx',+ 'q/beta',+ '!!!',+ 'x-md',+ ];+ let seed = 0x2f6b;+ const next = (bound: number) => {+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;+ return seed % bound;+ };+ const names = [...new Set([...docNames, ...targets])];+ for (let walk = 0; walk < 40; walk++) {+ const { index } = createIndex();+ const docs = new Map<string, string>();+ for (let step = 0; step < 30; step++) {+ const name = docNames[next(docNames.length)] as string;+ if (docs.has(name) && next(4) === 0) {+ docs.delete(name);+ index.deleteDocument(name);+ } else {+ const body = Array.from(+ { length: next(3) },+ () => `[[${targets[next(targets.length)]}]]`,+ ).join(' ');+ docs.set(name, body || '# Page');+ index.updateDocumentFromMarkdown(name, body || '# Page');+ }+ index.getLinkGraph();+ const { index: fresh } = createIndex();+ for (const [doc, body] of docs) fresh.updateDocumentFromMarkdown(doc, body);+ for (const target of names) {+ const at = `walk ${walk} step ${step} ${target}`;+ expect(index.getForwardLinks(target), at).toEqual(fresh.getForwardLinks(target));+ expect(index.getBacklinks(target), at).toEqual(fresh.getBacklinks(target));+ }+ }+ }+ });++ test('inventory changes invalidate fuzzy winners, independently for each branch', () => {+ const { index } = createIndex();+ index.updateDocumentFromMarkdown('z/beta', '# Beta');+ index.updateDocumentFromMarkdown('source', '[[beta]]');+ expect(index.getForwardLinks('source')).toEqual(['z/beta']);+ index.updateDocumentFromMarkdown('a/beta', '# Beta');+ expect(index.getForwardLinks('source')).toEqual(['a/beta']);+ index.switchBranch('feature');+ index.updateDocumentFromMarkdown('f/beta', '# Beta');+ index.updateDocumentFromMarkdown('source', '[[beta]]');+ expect(index.getForwardLinks('source')).toEqual(['f/beta']);+ index.switchBranch('main');+ index.deleteDocument('a/beta');+ expect(index.getForwardLinks('source')).toEqual(['z/beta']);+ expect(index.getForwardLinks('source', 'feature')).toEqual(['f/beta']);+ });++ test('global skills cannot steal fuzzy targets while explicit and structural skill links survive', () => {+ const { index } = createIndex();+ const global = skillLiveDocName('global', 'guide');+ const globalReference = `${global}/references/beta`;+ index.registerGlobalSkillBundleNode(global);+ index.registerGlobalSkillBundleNode(globalReference);+ index.updateDocumentFromMarkdown('z/beta', '# Beta');+ index.updateDocumentFromMarkdown('source', `[[beta]] [[${global}]]`);+ index.updateDocumentFromMarkdown('.agents/skills/project/SKILL', '# Project');+ index.updateDocumentFromMarkdown('.agents/skills/project/references/gamma', '# Gamma');+ index.updateDocumentFromMarkdown('project-ref', '[[gamma]]');+ expect(index.getForwardLinks('source')).toEqual(+ [global, 'z/beta'].sort((a, b) => a.localeCompare(b)),+ );+ expect(index.getBacklinkCount('z/beta')).toBe(1);+ expect(index.getForwardLinks(global)).toContain(globalReference);+ expect(index.getBacklinks(globalReference)).toContainEqual({+ source: global,+ anchor: null,+ snippet: null,+ });+ expect(index.getForwardLinks('project-ref')).toEqual([+ '.agents/skills/project/references/gamma',+ ]);+ expect(index.getForwardLinks('.agents/skills/project/SKILL')).toContain(+ '.agents/skills/project/references/gamma',+ );+ });++ test('versioned raw-key snapshots query and reconcile without changing their persisted keys', async () => {+ const { index, projectDir } = createIndex();+ const cache = join(projectDir, OK_DIR, LOCAL_DIR, 'cache/main/backlinks.json');+ mkdirSync(dirname(cache), { recursive: true });+ writeFileSync(+ cache,+ JSON.stringify({+ version: 4,+ backward: {+ beta: [{ source: 'source', anchor: 'intro', snippet: 'See Beta', sourceForm: 'wiki' }],+ },+ forward: { source: ['beta'], 'notes/beta': [] },+ externalForward: {},+ sourceLinks: {+ source: [{ target: 'beta', anchor: 'intro', snippet: 'See Beta', sourceForm: 'wiki' }],+ 'notes/beta': [],+ },+ }),+ );+ expect(await index.loadFromDisk()).toBe(true);+ expect(index.getBacklinkCount('notes/beta')).toBe(1);+ expect(index.getForwardLinks('source')).toEqual(['notes/beta']);+ await index.saveToDisk();+ const saved = JSON.parse(readFileSync(cache, 'utf8'));+ expect(saved.version).toBe(4);+ expect(saved.forward.source).toEqual(['beta']);+ expect(Object.keys(saved.backward)).toEqual(['beta']);+ mkdirSync(join(projectDir, 'notes'));+ writeFileSync(join(projectDir, 'notes/beta.md'), '# Beta');+ writeFileSync(join(projectDir, 'source.md'), '[[BETA.md#changed]]');+ await index.reconcileWithDisk();+ expect(index.getBacklinks('notes/beta')).toEqual([+ { source: 'source', anchor: 'changed', snippet: 'BETA.md#changed' },+ ]);+ });+});diff --git a/packages/server/src/conflict-errors.test.ts b/packages/server/src/conflict-errors.test.tsindex 9fe495bc4..dd3228c4d 100644--- a/packages/server/src/conflict-errors.test.ts+++ b/packages/server/src/conflict-errors.test.ts@@ -66,7 +66,7 @@ describe('respondDocInConflict — slim RFC 9457 envelope', () => {expect(body.title).toBe('Document is in conflict.');expect(body.status).toBe(409);expect(body.detail).toBe(- 'The document is in a conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',+ 'The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.',);expect(body.file).toBe('docs/notes.md');diff --git a/packages/server/src/conflict-errors.ts b/packages/server/src/conflict-errors.tsindex a70cec236..e7f78c28e 100644--- a/packages/server/src/conflict-errors.ts+++ b/packages/server/src/conflict-errors.ts@@ -41,7 +41,7 @@ export function docInConflictEnvelope(conflict?: Conflict): DocInConflictEnvelopconflict?.kind === 'reconcile' ? conflict.reason : undefined;return {detail:- 'The document is in a conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',+ 'The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.',...(conflict === undefined? {}: { conflict: { kind: conflict.kind, ...(reason === undefined ? {} : { reason }) } }),diff --git a/packages/server/src/derived-document-index.test.ts b/packages/server/src/derived-document-index.test.tsindex 536995274..57de22e2e 100644--- a/packages/server/src/derived-document-index.test.ts+++ b/packages/server/src/derived-document-index.test.ts@@ -1,4 +1,12 @@-import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import {+ mkdirSync,+ mkdtempSync,+ rmSync,+ statSync,+ unlinkSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { afterEach, describe, expect, test, vi } from 'vitest';@@ -81,6 +89,43 @@ afterEach(async () => {});describe('DerivedDocumentIndex', () => {+ test('every body feeder refreshes the resolved graph with unchanged document inventory', async () => {+ const rig = createRig();+ writeDoc(rig, 'notes/beta.md', '# Beta');+ writeDoc(rig, 'notes/gamma.md', '# Gamma');+ writeDoc(rig, 'source.md', '[[beta]]');+ await settleStartup(rig);+ expect(await rig.index.getBacklinkCount('notes/beta')).toBe(1);+ const feed = [+ async (markdown: string) => rig.index.recordDirectDocument('source', markdown),+ async (markdown: string) => {+ const token = rig.index.captureLiveUpdateToken();+ if (token === null) throw new Error('Live token unavailable');+ await rig.index.recordLiveDocument('source', markdown, token);+ },+ async (markdown: string) => rig.index.recordDurableStore('source', markdown),+ async (markdown: string) => rig.index.recordDiskUpsert('source', markdown),+ async (markdown: string) => rig.index.recordLinkRewrite('source', markdown),+ ];+ for (const [i, write] of feed.entries()) {+ const target = i % 2 === 0 ? 'gamma' : 'beta';+ const previous = target === 'beta' ? 'gamma' : 'beta';+ await write(`[[${target.toUpperCase()}.md#section]]`);+ expect(await rig.index.getBacklinkCount(`notes/${target}`)).toBe(1);+ expect(await rig.index.getBacklinkCount(`notes/${previous}`)).toBe(0);+ expect(await rig.index.getForwardLinkEntries('source')).toEqual([+ expect.objectContaining({ kind: 'doc', target: `notes/${target}`, anchor: 'section' }),+ ]);+ expect((await rig.index.getLinkGraph()).links).toEqual([+ { source: 'source', target: `notes/${target}` },+ ]);+ expect(await rig.index.getHubs()).toEqual([{ docName: `notes/${target}`, count: 1 }]);+ expect(await rig.index.getOrphans(['notes/beta', 'notes/gamma'], 'incoming')).toEqual([+ `notes/${previous}`,+ ]);+ }+ });+test('direct documents update links and tags before returning and signal B/G/T', async () => {const rig = createRig();await settleStartup(rig);@@ -1163,4 +1208,79 @@ describe('DerivedDocumentIndex local-target projection', () => {reason: 'no-such-doc',});});++ test('startup and branch-switch reuse persisted source links without reconcile logs', async () => {+ const rig = createRig();+ writeDoc(rig, 'source.md', 'See [[target]].\n');+ writeDoc(rig, 'target.md', '# Target\n');+ await settleStartup(rig);+ await rig.index.close();+ const info = vi.spyOn(getLogger('derived-document-index'), 'info');+ const restarted = new DerivedDocumentIndex({+ projectDir: rig.projectDir,+ contentDir: rig.contentDir,+ contentFilter: rig.contentFilter,+ getGlobalSkillRoots: () => [],+ signalChannel: () => {},+ });+ cleanups.unshift(() => restarted.close());+ await restarted.beginStartup('main').backlinksReady;+ await restarted.settleStartupAfterWatcherSeed();+ expect(info).not.toHaveBeenCalled();++ await restarted.settleBranchFromDisk(await restarted.beginBranchSwitch('feature'));+ info.mockClear();+ await restarted.settleBranchFromDisk(await restarted.beginBranchSwitch('main'));+ expect(info).not.toHaveBeenCalled();+ });++ test('startup and branch-switch reconcile changed sources from valid snapshots', async () => {+ const rig = createRig();+ writeDoc(rig, 'source.md', 'See [[first]].\n');+ await settleStartup(rig);+ await rig.index.close();++ const sourcePath = join(rig.contentDir, 'source.md');+ let nextMtimeMs = statSync(sourcePath).mtimeMs + 2000;+ const changeSource = (markdown: string) => {+ writeFileSync(sourcePath, markdown);+ const bumped = new Date(nextMtimeMs);+ nextMtimeMs += 2000;+ utimesSync(sourcePath, bumped, bumped);+ };+ const info = vi.spyOn(getLogger('derived-document-index'), 'info');+ const rebuild = vi.spyOn(BacklinkIndex.prototype, 'rebuildFromDisk');+ changeSource('See [[second]].\n');++ const restarted = new DerivedDocumentIndex({+ projectDir: rig.projectDir,+ contentDir: rig.contentDir,+ contentFilter: rig.contentFilter,+ getGlobalSkillRoots: () => [],+ signalChannel: () => {},+ });+ cleanups.unshift(() => restarted.close());+ await restarted.beginStartup('main').backlinksReady;+ await restarted.settleStartupAfterWatcherSeed();+ expect(info).toHaveBeenCalledWith(+ expect.objectContaining({ added: 0, updated: 1, deleted: 0 }),+ '[backlinks] startup reconcile',+ );+ expect(await restarted.getBacklinks('second')).toHaveLength(1);+ expect(await restarted.getBacklinks('first')).toHaveLength(0);+ expect(rebuild).not.toHaveBeenCalled();++ await restarted.settleBranchFromDisk(await restarted.beginBranchSwitch('feature'));+ expect(rebuild).toHaveBeenCalledTimes(1);+ changeSource('See [[third]].\n');+ info.mockClear();+ await restarted.settleBranchFromDisk(await restarted.beginBranchSwitch('main'));+ expect(info).toHaveBeenCalledWith(+ expect.objectContaining({ added: 0, updated: 1, deleted: 0 }),+ '[backlinks] branch-switch reconcile for main',+ );+ expect(await restarted.getBacklinks('third')).toHaveLength(1);+ expect(await restarted.getBacklinks('second')).toHaveLength(0);+ expect(rebuild).toHaveBeenCalledTimes(1);+ });});diff --git a/packages/server/src/derived-document-index.ts b/packages/server/src/derived-document-index.tsindex 21f67a210..329cc23a7 100644--- a/packages/server/src/derived-document-index.ts+++ b/packages/server/src/derived-document-index.ts@@ -113,6 +113,9 @@ export interface DerivedDocumentIndexApiPort {): Promise<LocalTargetSourceAssessments[]>;readLocalTargetGeneration?(): string | number;getIndexedDocNames(): Promise<string[]>;+ getRenameSourceInventory(): Promise<+ Array<{ docName: string; wikiTargets: string[]; indexedMtimeMs: number | undefined }>+ >;getAllTags(): Promise<TagSummaryEntry[]>;getDocsForTagWithMatches(tag: string): Promise<TagDocMatch[]>;}@@ -607,6 +610,12 @@ export class DerivedDocumentIndexreturn this.runQuery(() => this.backlinkIndex.getIndexedDocNames());}+ getRenameSourceInventory(): Promise<+ Array<{ docName: string; wikiTargets: string[]; indexedMtimeMs: number | undefined }>+ > {+ return this.runQuery(() => this.backlinkIndex.getRenameSourceInventory());+ }+getAllTags(): Promise<TagSummaryEntry[]> {return this.runQuery(() => this.tagIndex.getAllTags());}@@ -699,8 +708,12 @@ export class DerivedDocumentIndexdeletedDocNames = diff.deletedDocNames;if (diff.added > 0 || diff.updated > 0 || diff.deleted > 0) {log.info(- { added: diff.added, updated: diff.updated, deleted: diff.deleted },- '[backlinks] startup reconcile: offline changes applied',+ {+ added: diff.added,+ updated: diff.updated,+ deleted: diff.deleted,+ },+ '[backlinks] startup reconcile',);}} else {diff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.tsindex f9e60570f..2d37186d4 100644--- a/packages/server/src/doc-extensions.test.ts+++ b/packages/server/src/doc-extensions.test.ts@@ -91,6 +91,14 @@ describe('docNameToRelativePath', () => {expect(docNameToRelativePath('notes.ts')).toBe('notes.ts.md');});+ test.each(['.md', '.mdx', '.MD', '.MDX'])(+ 'appends the observed %s extension to an exact dotted identity',+ (extension) => {+ registerDocExtension('notes.md', extension);+ expect(docNameToRelativePath('notes.md')).toBe(`notes.md${extension}`);+ },+ );+test('returns Mermaid docNames verbatim (extension retained, no .md appended)', () => {expect(docNameToRelativePath('assets/flow.mmd')).toBe('assets/flow.mmd');expect(docNameToRelativePath('diagrams/seq.mermaid')).toBe('diagrams/seq.mermaid');@@ -223,9 +231,26 @@ describe('canonicalDocName', () => {expect(canonicalDocName('foo.md')).toBe('foo');});- test('registering a qualified name does not manufacture ambiguity', () => {+ test('preserves an exact registered dotted identity before removing a suffix', () => {+ registerDocExtension('notes', '.md');+ registerDocExtension('notes.md', '.md');+ expect(canonicalDocName('notes.md')).toBe('notes.md');+ expect(canonicalDocName('notes.md.md')).toBe('notes.md');+ expect(canonicalDocName(canonicalDocName('notes.md.md'))).toBe('notes.md');+ });++ test('stops at a registered identity after removing one suffix', () => {+ registerDocExtension('nested/topic.md.md', '.MDX');+ expect(canonicalDocName('nested/topic.md.md')).toBe('nested/topic.md.md');+ expect(canonicalDocName('nested/topic.md.md.MDX')).toBe('nested/topic.md.md');+ });++ test('an exact dotted identity wins over a same-stem shadowed sibling', () => {+ registerDocExtension('notes', '.md');+ registerDocExtension('notes', '.mdx');registerDocExtension('notes.md', '.md');- expect(canonicalDocName('notes.md')).toBe('notes');+ expect(canonicalDocName('notes.md')).toBe('notes.md');+ expect(docNameToRelativePath(canonicalDocName('notes.md'))).toBe('notes.md.md');});test('leaves non-markdown docNames that own their extension alone', () => {diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex b557fdc64..245519cb0 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -87,10 +87,9 @@ export function isRegisteredMarkdownDocName(docName: string): boolean {}export function canonicalDocName(docName: string): string {- if (!isSupportedDocFile(docName)) return docName;- if (addressesShadowedSibling(docName)) return docName;let candidate = docName;while (isSupportedDocFile(candidate)) {+ if (docExtensionByName.has(candidate) || addressesShadowedSibling(candidate)) return candidate;candidate = stripDocExtension(candidate);}return candidate;@@ -105,6 +104,8 @@ function addressesShadowedSibling(docName: string): boolean {}export function docNameToRelativePath(docName: string): string {+ const registeredExtension = docExtensionByName.get(docName);+ if (registeredExtension !== undefined) return `${docName}${registeredExtension}`;return isSupportedDocFile(docName) ||isMermaidDocFile(docName) ||isExcalidrawDocFile(docName) ||diff --git a/packages/server/src/file-watcher.test.ts b/packages/server/src/file-watcher.test.tsindex 620f52377..b398d0c2c 100644--- a/packages/server/src/file-watcher.test.ts+++ b/packages/server/src/file-watcher.test.ts@@ -1,4 +1,12 @@-import { mkdirSync, realpathSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';+import {+ mkdirSync,+ readFileSync,+ realpathSync,+ renameSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';@@ -2141,3 +2149,125 @@ describe('structural-ignore discovery feeds the parcel prefix list', () => {}});});++describe('file index canonical path after a real rename', () => {+ let tmpDir: string;+ let contentDir: string;++ beforeEach(async () => {+ tmpDir = realpathSync(await mkdtemp(resolve(tmpdir(), 'ok-watcher-rename-')));+ contentDir = resolve(tmpDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ lastKnownHash.clear();+ });++ afterEach(async () => {+ lastKnownHash.clear();+ await rm(tmpDir, { recursive: true, force: true });+ });++ async function seedIndexFromStartupWalk() {+ const handle = await startWatcher(contentDir, async () => {});+ try {+ return {+ fileIndex: new Map(handle.getAllFilesIndex()),+ folderIndex: new Map(handle.getFolderIndex()),+ aliasMap: new Map(handle.getAliasMap()),+ };+ } finally {+ await handle.unsubscribe();+ }+ }++ function declareLastKnownContent(filePath: string): void {+ updateLastKnownHash(filePath, contentHash(readFileSync(filePath, 'utf-8')));+ }++ function readOrErrnoCode(filePath: string): string {+ try {+ return readFileSync(filePath, 'utf-8');+ } catch (e) {+ return `<${(e as { code?: string }).code}: ${filePath}>`;+ }+ }++ async function applyRawEvents(+ seeded: Awaited<ReturnType<typeof seedIndexFromStartupWalk>>,+ rawEvents: Array<{ type: 'create' | 'update' | 'delete'; path: string }>,+ ): Promise<DiskEvent[]> {+ const dispatched: DiskEvent[] = [];+ await handleRawEvents(+ rawEvents,+ contentDir,+ undefined,+ seeded.fileIndex,+ seeded.folderIndex,+ async (event) => {+ dispatched.push(event);+ },+ seeded.aliasMap,+ );+ return dispatched;+ }++ test.each([+ { ext: '.md', stem: 'md-target', body: '# Unique real md rename target\n' },+ { ext: '.mdx', stem: 'mdx-target', body: '# Unique real mdx rename target\n' },+ ])(+ 'a real $ext rename publishes a path that reads the moved file',+ async ({ ext, stem, body }) => {+ mkdirSync(resolve(contentDir, 'z'), { recursive: true });+ mkdirSync(resolve(contentDir, 'f'), { recursive: true });+ const oldPath = resolve(contentDir, 'z', `${stem}${ext}`);+ const newPath = resolve(contentDir, 'f', `${stem}${ext}`);+ writeFileSync(oldPath, body, 'utf-8');++ const seeded = await seedIndexFromStartupWalk();+ expect(seeded.fileIndex.get(`z/${stem}`)?.canonicalPath).toBe(oldPath);++ declareLastKnownContent(oldPath);+ renameSync(oldPath, newPath);++ const dispatched = await applyRawEvents(seeded, [+ { type: 'delete', path: oldPath },+ { type: 'create', path: newPath },+ ]);++ expect(dispatched.filter((event) => event.kind === 'rename')).toHaveLength(1);+ expect(seeded.fileIndex.has(`z/${stem}`)).toBe(false);+ const entry = seeded.fileIndex.get(`f/${stem}`);+ expect(entry).toBeDefined();+ expect(readOrErrnoCode(entry?.canonicalPath ?? '')).toBe(body);+ expect(entry?.canonicalPath).toBe(newPath);+ },+ );++ test('a rename landing on a symlink publishes the canonical target, not the alias path', async () => {+ mkdirSync(resolve(contentDir, 'real'), { recursive: true });+ mkdirSync(resolve(contentDir, 'z'), { recursive: true });+ const body = '# Shared body carried by the alias\n';+ const keeperPath = resolve(contentDir, 'real', 'keeper.md');+ const originPath = resolve(contentDir, 'z', 'origin.md');+ const aliasPath = resolve(contentDir, 'alias.md');+ writeFileSync(keeperPath, body, 'utf-8');+ writeFileSync(originPath, body, 'utf-8');++ const seeded = await seedIndexFromStartupWalk();+ expect(seeded.fileIndex.get('real/keeper')?.canonicalPath).toBe(keeperPath);++ declareLastKnownContent(originPath);+ unlinkSync(originPath);+ symlinkSync(keeperPath, aliasPath);++ const dispatched = await applyRawEvents(seeded, [+ { type: 'delete', path: originPath },+ { type: 'create', path: aliasPath },+ ]);++ expect(dispatched.filter((event) => event.kind === 'rename')).toHaveLength(1);+ const entry = seeded.fileIndex.get('real/keeper');+ expect(entry).toBeDefined();+ expect(readOrErrnoCode(entry?.canonicalPath ?? '')).toBe(body);+ expect(entry?.canonicalPath).toBe(keeperPath);+ });+});diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.tsindex 2e32235c3..dd53ed782 100644--- a/packages/server/src/file-watcher.ts+++ b/packages/server/src/file-watcher.ts@@ -968,7 +968,7 @@ export function updateFileIndex(event: DiskEvent, fileIndex: Map<string, FileIndfileIndex.set(event.newDocName, {size: Buffer.byteLength(event.content, 'utf-8'),modified: new Date().toISOString(),- canonicalPath: existing?.canonicalPath ?? event.newPath,+ canonicalPath: event.newPath,inode: existing?.inode ?? 0,aliases: existing?.aliases ?? [],kind: 'markdown',@@ -1197,6 +1197,7 @@ export async function handleRawEvents(for (const event of diskEvents) {let isSelf = false;+ let indexEvent = event;const previousIndexedFields =event.kind === 'update'@@ -1242,6 +1243,7 @@ export async function handleRawEvents(}}isSelf = isSelfWrite(checkPath, hash);+ indexEvent = { ...event, newPath: checkPath };voidRemoval(event.oldPath, declaredBeforeBatch);voidRemoval(event.newPath, declaredBeforeBatch);} else {@@ -1253,7 +1255,7 @@ export async function handleRawEvents(? { ...event, previousIndexedFields }: event;- updateFileIndex(event, fileIndex);+ updateFileIndex(indexEvent, fileIndex);if (contentFilter && !isSelf) {switch (event.kind) {diff --git a/packages/server/src/http/lint-routes.test.ts b/packages/server/src/http/lint-routes.test.tsnew file mode 100644index 000000000..0d0c99eb0--- /dev/null+++ b/packages/server/src/http/lint-routes.test.ts@@ -0,0 +1,71 @@+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Hocuspocus } from '@hocuspocus/server';+import { afterEach, describe, expect, test } from 'vitest';+import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';+import { isValidRelativeContentPath } from '../relative-content-path.ts';+import { createLintRoutes } from './lint-routes.ts';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('audit routes with a missing content directory', () => {+ test.each(['/api/lint/audit', '/api/audit'])(+ '%s reports missing root and child scopes while rejecting explicit dot paths',+ async (routePath) => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-missing-audit-route-'));+ roots.push(projectDir);+ const contentDir = join(projectDir, 'missing-content');+ const group = createLintRoutes({+ hocuspocus: new Hocuspocus({ quiet: true }),+ contentDir,+ projectDir,+ contentFilter: undefined,+ isSafeDocName: () => true,+ resolveDocFilePath: () => null,+ isValidRelativeContentPath,+ async *streamShowAllEntries() {+ yield* [];+ return { truncated: false };+ },+ getLinterBaseConfig: undefined,+ getLinkAdvisoryPolicy: () => ({ links: 'off', suppressLogLinkAdvisories: false }),+ derivedDocumentIndex: undefined,+ collectAdmittedDocNames: async () => new Set<string>(),+ unmatchedGlobProblems: () => [],+ readAuditGeneration: () => 'initial',+ });+ const dispatch = group.table.resolve(routePath)?.dispatch;+ if (dispatch === undefined) throw new Error(`${routePath} was not registered`);+ const rootResponse = makeCaptureRes();+ await dispatch(makeSyntheticReq({ url: routePath }), rootResponse.res);+ expect(rootResponse.captured.status).toBe(404);+ expect(rootResponse.captured.headers['content-type']).toContain('application/problem+json');+ expect(JSON.parse(rootResponse.captured.body)).toMatchObject({+ type: 'urn:ok:error:not-found',+ status: 404,+ title: expect.stringContaining('Set content.dir to an existing directory.'),+ });+ const dotResponse = makeCaptureRes();+ await dispatch(makeSyntheticReq({ url: `${routePath}?path=.` }), dotResponse.res);+ expect(dotResponse.captured.status).toBe(400);+ expect(JSON.parse(dotResponse.captured.body)).toMatchObject({+ type: 'urn:ok:error:invalid-request',+ status: 400,+ title: 'Invalid path.',+ });+ mkdirSync(contentDir);+ const { res, captured } = makeCaptureRes();+ await dispatch(makeSyntheticReq({ url: `${routePath}?path=child` }), res);+ expect(captured.status).toBe(404);+ expect(JSON.parse(captured.body)).toMatchObject({+ type: 'urn:ok:error:not-found',+ title: expect.stringContaining('Use an existing file or directory'),+ });+ },+ );+});diff --git a/packages/server/src/http/lint-routes.ts b/packages/server/src/http/lint-routes.tsindex 93e3a7243..dec6969cb 100644--- a/packages/server/src/http/lint-routes.ts+++ b/packages/server/src/http/lint-routes.ts@@ -19,8 +19,9 @@ import type { ContentFilter } from '../content-filter.ts';import type { DerivedDocumentIndexApiPort } from '../derived-document-index.ts';import { isContainmentRejection } from '../fs-safety.ts';import type { LinkAdvisoryPolicy } from '../link-advisory-policy.ts';-import { AuditSupersededError, auditProject, lintDoc } from '../lint/audit.ts';+import { AuditSupersededError, auditProject, auditScopeWarning, lintDoc } from '../lint/audit.ts';import { AuditCache } from '../lint/audit-cache.ts';+import { type AuditScope, resolveAuditScope } from '../lint/audit-scope.ts';import { listProjectSchemaFiles, SCHEMA_LIST_CAP } from '../lint/frontmatter-schemas.ts';import {composeEffectiveLinterConfig,@@ -88,7 +89,8 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {const liveLintSourceFor = (docRelPath: string): string | null => {const docName = docRelPath.replace(/\.(md|mdx)$/i, '');const doc = hocuspocus.documents.get(docName);- return doc === undefined ? null : doc.getText('source').toString();+ if (doc === undefined || resolveDocFilePath(contentDir, docName) !== docRelPath) return null;+ return doc.getText('source').toString();};const auditCache = new AuditCache();@@ -98,9 +100,11 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {validators: readonly ProjectValidator[],targetPath: string | undefined,configFingerprint: string,+ resolvedScope?: AuditScope,): Promise<ValidationAuditResult> {- const key = `${configFingerprint} ${readAuditGeneration()} ${targetPath ?? ''}`;- return auditFlight.run(key, () => runValidationAudit(validators, { targetPath })).promise;+ const key = `${configFingerprint} ${readAuditGeneration()} ${resolvedScope?.kind ?? ''} ${targetPath ?? ''}`;+ return auditFlight.run(key, () => runValidationAudit(validators, { targetPath, resolvedScope }))+ .promise;}function respondAuditSuperseded(res: ServerResponse, handler: string): void {@@ -269,19 +273,35 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {try {const url = new URL(req.url ?? '', 'http://localhost');const rawTarget = url.searchParams.get('path');- const target = rawTarget === null || rawTarget === '' ? undefined : rawTarget;+ let target = rawTarget === null || rawTarget === '' ? undefined : rawTarget;if (target !== undefined && !isValidRelativeContentPath(target)) {errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid path.', {handler: 'lint-audit',});return;}+ let resolvedScope: AuditScope | undefined;+ if (+ target === undefined ||+ auditScopeWarning({ path: resolve(contentDir, target) }, contentDir, target) === undefined+ ) {+ const resolution = resolveAuditScope(target, contentDir);+ if (!resolution.ok) {+ errorResponse(res, 404, 'urn:ok:error:not-found', resolution.title, {+ handler: 'lint-audit',+ });+ return;+ }+ resolvedScope = resolution.scope;+ target = relative(contentDir, resolvedScope.path);+ }const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;const result = await auditProject({projectDir: projectDir ?? contentDir,contentDir,baseConfig,targetPath: target,+ resolvedScope,liveSourceFor: liveLintSourceFor,cache: auditCache,auditGeneration: readAuditGeneration,@@ -325,6 +345,23 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {}target = resolveDocFilePath(contentDir, docParam) ?? `${docParam}.md`;}+ let resolvedScope: AuditScope | undefined;+ if (+ docParam === undefined &&+ (target === undefined ||+ auditScopeWarning({ path: resolve(contentDir, target) }, contentDir, target) ===+ undefined)+ ) {+ const resolution = resolveAuditScope(target, contentDir);+ if (!resolution.ok) {+ errorResponse(res, 404, 'urn:ok:error:not-found', resolution.title, {+ handler: 'audit',+ });+ return;+ }+ resolvedScope = resolution.scope;+ target = relative(contentDir, resolvedScope.path);+ }const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;const linkPolicy = getLinkAdvisoryPolicy();const validators = createProjectValidators({@@ -343,6 +380,7 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {validators,target,AuditCache.fingerprintConfig(baseConfig),+ resolvedScope,);if (url.searchParams.get('counts') === '1') {successResponse(diff --git a/packages/server/src/http/skills-install-routes.ts b/packages/server/src/http/skills-install-routes.tsindex de079f5e8..245deabb1 100644--- a/packages/server/src/http/skills-install-routes.ts+++ b/packages/server/src/http/skills-install-routes.ts@@ -437,7 +437,7 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRoutres,409,'urn:ok:error:doc-already-exists',- 'That copy has been edited and no longer matches the skill — remove it manually if you mean it.',+ 'This copy differs from the current source and was preserved. Inspect both versions before removing it.',{ handler: 'skill-install', detail: unplaced.path },);return;@@ -525,7 +525,7 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRoutres,409,'urn:ok:error:doc-already-exists',- 'That copy has been edited and no longer matches the skill — resolve the fork before converting it.',+ 'This copy differs from the current source and was preserved. Inspect both versions before replacing or converting it.',{ handler: 'skill-install', detail: target },);return;diff --git a/packages/server/src/http/sync-routes.ts b/packages/server/src/http/sync-routes.tsindex 2384345fe..1a0c67e1a 100644--- a/packages/server/src/http/sync-routes.ts+++ b/packages/server/src/http/sync-routes.ts@@ -312,7 +312,7 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {{handler: 'sync-resolve-conflict',detail:- 'This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Re-read conflicts({ kind: "list" }) before retrying.',+ 'This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Refresh the conflict list in the OpenKnowledge app before retrying.',extensions: { file: e.file },},);diff --git a/packages/server/src/index-telemetry.test.ts b/packages/server/src/index-telemetry.test.tsindex 5d679f68b..5f827c25f 100644--- a/packages/server/src/index-telemetry.test.ts+++ b/packages/server/src/index-telemetry.test.ts@@ -1,3 +1,6 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { context, metrics, trace } from '@opentelemetry/api';import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';import {@@ -7,6 +10,7 @@ import {SimpleSpanProcessor,} from '@opentelemetry/sdk-trace-base';import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { BacklinkIndex } from './backlink-index.ts';import {__resetIndexTelemetryForTests,instrumentIndexRebuild,@@ -70,6 +74,35 @@ describe('instrumentIndexRebuild', () => {expect(span.attributes['index.deleted']).toBe(2);});+ test('warm backlink reconciliation reports source-link reuse', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlink-rehydrate-span-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir);+ try {+ writeFileSync(join(contentDir, 'source.md'), '[[target]]');+ writeFileSync(join(contentDir, 'target.md'), '# Target');+ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();+ await index.saveToDisk();+ const reloaded = new BacklinkIndex({ projectDir, contentDir });+ expect(await reloaded.loadFromDisk()).toBe(true);+ expect(await reloaded.reconcileWithDisk()).toMatchObject({ updated: 0, changedDocs: [] });+ const span = exporter+ .getFinishedSpans()+ .find(+ (entry) =>+ entry.name === 'ok.index.rebuild' && entry.attributes['index.mode'] === 'reconcile',+ );+ expect(span?.attributes).toMatchObject({+ 'index.name': 'backlink',+ 'index.mode': 'reconcile',+ 'index.updated': 0,+ });+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('propagates the rebuild error and still ends the span', async () => {await expect(instrumentIndexRebuild('tag', 'full', async () => {diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex a7804c92f..9b233277b 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -302,6 +302,13 @@ export {removeProjectSkillGitignoreBlock,writeRootGitignoreForNewRepo,} from './init-project.ts';+export {+ AUDIT_EMPTY_SCOPE_WARNING,+ type AuditScope,+ type AuditScopeResolution,+ auditScopeNotFoundTitle,+ resolveAuditScope,+} from './lint/audit-scope.ts';export {type DiscoveredMarkdownlintConfig,discoverMarkdownlintConfig,diff --git a/packages/server/src/lint/audit-scope-errors.test.ts b/packages/server/src/lint/audit-scope-errors.test.tsnew file mode 100644index 000000000..5e21c9c47--- /dev/null+++ b/packages/server/src/lint/audit-scope-errors.test.ts@@ -0,0 +1,39 @@+import * as fs from 'node:fs';+import { join } from 'node:path';+import { afterEach, expect, test, vi } from 'vitest';+import { auditScopeWarning } from './audit.ts';+import { resolveAuditScope } from './audit-scope.ts';++vi.mock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof fs>();+ return {+ ...actual,+ lstatSync: vi.fn(actual.lstatSync),+ realpathSync: vi.fn(actual.realpathSync),+ };+});++afterEach(() => {+ vi.mocked(fs.lstatSync).mockReset();+ vi.mocked(fs.realpathSync).mockReset();+});++test.each(['EACCES', 'EIO', 'EPERM'])('keeps %s scope resolution failures operational', (code) => {+ const failure = Object.assign(new Error(`scope probe ${code}`), { code });+ vi.mocked(fs.lstatSync).mockImplementationOnce(() => {+ throw failure;+ });+ expect(() => resolveAuditScope('document.md', process.cwd())).toThrow(failure);+});++test.each(['EACCES', 'EIO', 'EPERM'])('keeps %s containment failures operational', (code) => {+ const failure = Object.assign(new Error(`containment probe ${code}`), { code });+ const root = process.cwd();+ vi.mocked(fs.realpathSync).mockImplementation((path) => {+ if (path === root) return root;+ throw failure;+ });+ expect(() => auditScopeWarning({ path: join(root, 'document.md') }, root, 'document.md')).toThrow(+ failure,+ );+});diff --git a/packages/server/src/lint/audit-scope.test.ts b/packages/server/src/lint/audit-scope.test.tsnew file mode 100644index 000000000..e8daeb410--- /dev/null+++ b/packages/server/src/lint/audit-scope.test.ts@@ -0,0 +1,329 @@+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { auditProject } from './audit.ts';+import { AuditCache } from './audit-cache.ts';+import {+ AUDIT_EMPTY_SCOPE_WARNING,+ auditScopeNotFoundTitle,+ resolveAuditScope,+} from './audit-scope.ts';++let root: string;+const baseConfig: LinterConfig = {+ ...DEFAULT_LINTER_CONFIG,+ plugins: {+ ...DEFAULT_LINTER_CONFIG.plugins,+ markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true },+ },+};+const TABBED = '# Title\n\n\tA hard tab.\n';++function write(path: string, body = TABBED): void {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), body);+}++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-audit-scope-')));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe('resolveAuditScope', () => {+ test('resolves an extensionless document to the same cache identity as its explicit suffix', async () => {+ write('guide.mdx');+ const cache = new AuditCache();+ const results = [];+ for (const targetPath of ['guide', 'guide.mdx']) {+ const result = resolveAuditScope(targetPath, root);+ if (!result.ok) throw new Error(result.title);+ results.push(+ await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ targetPath,+ resolvedScope: result.scope,+ cache,+ }),+ );+ }+ const direct = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ targetPath: 'guide',+ cache,+ });+ expect(results[0]).toEqual(results[1]);+ expect(direct).toEqual(results[0]);+ expect(results[0]?.files[0]?.file).toBe('guide.mdx');+ expect(+ results[0]?.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010'),+ ).toBe(true);+ expect(cache.stats().entries).toBe(1);+ expect(cache.stats().hits).toBe(2);+ });++ test('existing regular files and directories win over document candidates', () => {+ write('guide');+ write('guide.mdx');+ mkdirSync(join(root, 'folder.md'));+ write('folder.md.mdx');+ expect(resolveAuditScope('guide', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'guide') },+ });+ expect(resolveAuditScope('folder.md', root)).toEqual({+ ok: true,+ scope: { kind: 'dir', path: join(root, 'folder.md') },+ });+ });++ test('prefers mdx only for an absent extensionless path', () => {+ write('guide.md');+ write('guide.mdx');+ write('only-mdx.mdx');+ expect(resolveAuditScope('guide', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'guide.mdx') },+ });+ expect(resolveAuditScope('guide.md', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'guide.md') },+ });+ expect(resolveAuditScope('only-mdx.md', root)).toEqual({+ ok: false,+ path: join(root, 'only-mdx.md'),+ title: auditScopeNotFoundTitle('only-mdx.md'),+ });+ expect(resolveAuditScope('missing', root)).toEqual({+ ok: false,+ path: join(root, 'missing'),+ title: auditScopeNotFoundTitle('missing'),+ });+ });++ test('resolves an absent dotted document stem before reporting it missing', () => {+ write('notes/v1.2.md');+ write('notes/v1.2.mdx');+ expect(resolveAuditScope('notes/v1.2', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'notes/v1.2.mdx') },+ });+ expect(resolveAuditScope('notes/v1.2.md', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'notes/v1.2.md') },+ });+ });++ test('a missing content directory names content.dir and never resolves to a sibling document', () => {+ const missing = join(root, 'content');+ write('content.md');+ write('outside.md');+ const expected = {+ ok: false,+ path: missing,+ title: `Content directory ${JSON.stringify(missing)} was not found. Set content.dir to an existing directory.`,+ };+ expect(resolveAuditScope(undefined, missing)).toEqual(expected);+ expect(resolveAuditScope('.', missing)).toEqual(expected);+ expect(resolveAuditScope('../outside', missing)).toEqual(expected);+ expect(resolveAuditScope('../outside', join(root, 'inner'))).toMatchObject({ ok: false });+ });++ test('an existing content root retains explicit outer-file selection', () => {+ mkdirSync(join(root, 'content'));+ write('outside.md');+ expect(resolveAuditScope('../outside.md', join(root, 'content'))).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, 'outside.md') },+ });+ });++ test('a child under a regular file is an unknown scope with its path and a fix', () => {+ write('parent');+ const result = resolveAuditScope('parent/child', root);+ expect(result).toEqual({+ ok: false,+ path: join(root, 'parent/child'),+ title: auditScopeNotFoundTitle('parent/child'),+ });+ if (result.ok) throw new Error('Expected an unknown scope');+ expect(result.title).toContain('"parent/child"');+ expect(result.title).toBe(+ 'Scope "parent/child" was not found. Use an existing file or directory; a document stem without .md or .mdx resolves .mdx before .md. Explicit document extensions must exist as written.',+ );+ });++ test('falls back to md and accepts canonical relative or absolute spellings', () => {+ write('nested/guide.md');+ const expected = { ok: true, scope: { kind: 'file', path: join(root, 'nested/guide.md') } };+ expect(resolveAuditScope('nested/guide', root)).toEqual(expected);+ expect(resolveAuditScope('nested/./guide.md', root)).toEqual(expected);+ expect(resolveAuditScope(join(root, 'nested/guide.md'), root)).toEqual(expected);+ });++ test('does not replace a dangling supplied symlink with a sibling document', () => {+ symlinkSync(join(root, 'missing'), join(root, 'guide'));+ write('guide.mdx');+ expect(resolveAuditScope('guide', root)).toMatchObject({+ ok: false,+ title: auditScopeNotFoundTitle('guide'),+ });+ });++ test.each(['overlong segment', 'symlink loop'])(+ 'returns the teaching not-found outcome for a %s',+ (kind) => {+ const target = kind === 'overlong segment' ? 'x'.repeat(300) : 'loop';+ if (kind === 'symlink loop') symlinkSync(join(root, target), join(root, target));+ expect(resolveAuditScope(target, root)).toEqual({+ ok: false,+ path: join(root, target),+ title: auditScopeNotFoundTitle(target),+ });+ },+ );++ test('leaves hidden and external scope admission to each entrypoint', () => {+ write('.hidden.md');+ expect(resolveAuditScope('.hidden', root)).toEqual({+ ok: true,+ scope: { kind: 'file', path: join(root, '.hidden.md') },+ });+ expect(resolveAuditScope(dirname(root), root)).toEqual({+ ok: true,+ scope: { kind: 'dir', path: dirname(root) },+ });+ });+});++describe('server scope admission and coverage', () => {+ test.each(['empty', 'ignored'])(+ 'reports zero-document coverage for %s without diagnostic counts',+ async (targetPath) => {+ mkdirSync(join(root, 'empty'));+ write('ignored/document.md');+ write('.gitignore', 'ignored/\n');+ const result = resolveAuditScope(targetPath, root);+ if (!result.ok) throw new Error(result.title);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ targetPath,+ resolvedScope: result.scope,+ });+ expect(audit).toEqual({+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [AUDIT_EMPTY_SCOPE_WARNING],+ ran: ['markdownlint'],+ });+ },+ );++ test('does not classify an unreadable directory as an empty admitted scope', async () => {+ const missing = join(root, 'missing');+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ resolvedScope: { kind: 'dir', path: missing },+ });+ expect(audit.fileCount).toBe(0);+ expect(audit.warnings).toEqual([expect.stringContaining('could not read missing')]);+ });++ test('a removed content directory reports the unavailable scope', async () => {+ const missing = join(root, 'missing');+ const audit = await auditProject({ projectDir: root, contentDir: missing, baseConfig });+ expect(audit.fileCount).toBe(0);+ expect(audit.warnings).toEqual([expect.stringContaining('could not read')]);+ });++ test.each(['.gitignore', '.okignore'])(+ 'lints explicitly requested files excluded by %s',+ async (ignoreFile) => {+ write(ignoreFile, 'ignored/\n');+ for (const targetPath of ['ignored/document.md', 'ignored/document.mdx', 'ignored/plain']) {+ write(targetPath);+ const resolution = resolveAuditScope(targetPath, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ targetPath,+ resolvedScope: resolution.scope,+ });+ expect(audit.fileCount).toBe(1);+ expect(audit.files.map((file) => file.file)).toEqual([targetPath]);+ expect(audit.files[0]?.diagnostics.some((diagnostic) => diagnostic.code === 'MD010')).toBe(+ true,+ );+ expect(audit.warnings).toEqual([]);+ }+ },+ );++ test('a resolved file scope never reports project-wide unmatched schema globs', async () => {+ write('notes/a.md', '# A\n');+ write(+ '.ok/schemas/doc.schema.json',+ JSON.stringify({ $schema: 'http://json-schema.org/draft-07/schema#', type: 'object' }),+ );+ const config: LinterConfig = {+ ...baseConfig,+ plugins: {+ ...baseConfig.plugins,+ frontmatter: {+ enabled: true,+ schemas: [{ file: '.ok/schemas/doc.schema.json', appliesTo: ['specs/**'] }],+ },+ },+ };+ const unmatched =+ 'unmatched appliesTo glob "specs/**" — matches no docs in this project (frontmatter mapping for .ok/schemas/doc.schema.json)';+ const whole = await auditProject({ projectDir: root, contentDir: root, baseConfig: config });+ expect(whole.warnings).toContain(unmatched);+ const resolution = resolveAuditScope('notes/a.md', root);+ if (!resolution.ok) throw new Error(resolution.title);+ const scoped = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: config,+ resolvedScope: resolution.scope,+ });+ expect(scoped.fileCount).toBe(1);+ expect(scoped.warnings).not.toContain(unmatched);+ });++ test('keeps non-document regular files and in-root symlink aliases admitted', async () => {+ write('plain');+ write('guide.md');+ symlinkSync(join(root, 'guide.md'), join(root, 'alias.md'));+ for (const targetPath of ['plain', 'alias.md']) {+ const result = resolveAuditScope(targetPath, root);+ if (!result.ok) throw new Error(result.title);+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig,+ targetPath,+ resolvedScope: result.scope,+ });+ expect(audit.fileCount).toBe(1);+ expect(audit.files[0]?.file).toBe(targetPath);+ expect(audit.warnings).toEqual([]);+ }+ });+});diff --git a/packages/server/src/lint/audit-scope.ts b/packages/server/src/lint/audit-scope.tsnew file mode 100644index 000000000..0b27bf40f--- /dev/null+++ b/packages/server/src/lint/audit-scope.ts@@ -0,0 +1,73 @@+import { lstatSync, statSync } from 'node:fs';+import { resolve } from 'node:path';+import { SUPPORTED_DOC_EXTENSIONS } from '@inkeep/open-knowledge-core';+import { isWithinContentDir } from '../content-path.ts';++export interface AuditScope {+ kind: 'dir' | 'file';+ path: string;+}++export function auditScopeNotFoundTitle(path: string): string {+ return `Scope ${JSON.stringify(path)} was not found. Use an existing file or directory; a document stem without .md or .mdx resolves .mdx before .md. Explicit document extensions must exist as written.`;+}++export { AUDIT_EMPTY_SCOPE_WARNING } from '@inkeep/open-knowledge-core';++export type AuditScopeResolution =+ | { ok: true; scope: AuditScope }+ | { ok: false; path: string; title: string };++export function resolveAuditScope(+ targetPath: string | undefined,+ contentDir: string,+): AuditScopeResolution {+ const root = resolve(contentDir);+ const path = resolve(root, targetPath ?? '');+ if (!readScopeEntry(root, true)?.isDirectory()) {+ return {+ ok: false,+ path: root,+ title: `Content directory ${JSON.stringify(root)} was not found. Set content.dir to an existing directory.`,+ };+ }+ const entry = readScopeEntry(path);+ if (entry !== undefined) {+ const stat = entry.isSymbolicLink() ? readScopeEntry(path, true) : entry;+ if (stat?.isFile()) return { ok: true, scope: { kind: 'file', path } };+ if (stat?.isDirectory()) return { ok: true, scope: { kind: 'dir', path } };+ } else if (+ path !== root &&+ isWithinContentDir(path, root) &&+ !SUPPORTED_DOC_EXTENSIONS.some((extension) => path.toLowerCase().endsWith(extension))+ ) {+ for (const extension of SUPPORTED_DOC_EXTENSIONS) {+ const candidate = `${path}${extension}`;+ if (readScopeEntry(candidate, true)?.isFile()) {+ return { ok: true, scope: { kind: 'file', path: candidate } };+ }+ }+ }+ return { ok: false, path, title: auditScopeNotFoundTitle(targetPath ?? '.') };+}++export function isAbsentPathError(error: unknown): boolean {+ return (+ error instanceof Error &&+ 'code' in error &&+ (error.code === 'ENOENT' ||+ error.code === 'ENOTDIR' ||+ error.code === 'ENAMETOOLONG' ||+ error.code === 'ELOOP' ||+ error.code === 'ERR_INVALID_ARG_VALUE')+ );+}++export function readScopeEntry(path: string, followSymlinks = false) {+ try {+ return followSymlinks ? statSync(path) : lstatSync(path);+ } catch (error) {+ if (isAbsentPathError(error)) return undefined;+ throw error;+ }+}diff --git a/packages/server/src/lint/audit.test.ts b/packages/server/src/lint/audit.test.tsindex 56290e1ae..2c7c74b85 100644--- a/packages/server/src/lint/audit.test.ts+++ b/packages/server/src/lint/audit.test.ts@@ -2,12 +2,13 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'nodimport { tmpdir } from 'node:os';import { join } from 'node:path';import {+ AUDIT_EMPTY_SCOPE_WARNING,DEFAULT_LINTER_CONFIG,LINT_PLUGINS,type LinterConfig,} from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';-import { auditProject, lintDoc } from './audit.ts';+import { auditProject, lintDoc, resolveScope } from './audit.ts';import { AuditCache } from './audit-cache.ts';let root: string;@@ -112,6 +113,43 @@ describe('lintDoc', () => {});describe('auditProject', () => {+ test('a directory lost after scope resolution reports an incomplete scan, not an empty selection', async () => {+ mkdirSync(join(root, 'notes'));+ const resolvedScope = resolveScope('notes', root);+ rmSync(join(root, 'notes'), { recursive: true });++ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: DEFAULT_LINTER_CONFIG,+ resolvedScope,+ });++ expect(audit.fileCount).toBe(0);+ expect(audit.warnings).toEqual([expect.stringContaining('could not read notes:')]);+ expect(audit.warnings).not.toContain(AUDIT_EMPTY_SCOPE_WARNING);+ });++ test('reports zero admitted documents alongside a configuration warning', async () => {+ const audit = await auditProject({+ projectDir: root,+ contentDir: root,+ baseConfig: {+ ...DEFAULT_LINTER_CONFIG,+ plugins: {+ ...DEFAULT_LINTER_CONFIG.plugins,+ frontmatter: {+ enabled: true,+ schemas: [{ appliesTo: '**', file: '.ok/schemas/missing.json' }],+ },+ },+ },+ });+ expect(audit.fileCount).toBe(0);+ expect(audit.warnings).toContain(AUDIT_EMPTY_SCOPE_WARNING);+ expect(audit.warnings.some((warning) => warning.includes('missing.json'))).toBe(true);+ });+test('emits an explicit empty selection when linting is disabled', async () => {write('clean.md', CLEAN_DOC);const audit = await auditProject({diff --git a/packages/server/src/lint/audit.ts b/packages/server/src/lint/audit.tsindex 16d27eb0a..e17304030 100644--- a/packages/server/src/lint/audit.ts+++ b/packages/server/src/lint/audit.ts@@ -1,7 +1,8 @@import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';-import { isAbsolute, join, relative, resolve } from 'node:path';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';import { setImmediate as yieldToEventLoop } from 'node:timers/promises';import {+ AUDIT_EMPTY_SCOPE_WARNING,deriveValidationRunSources,fixDocument,type LintDiagnostic,@@ -16,6 +17,7 @@ import { SymlinkEscapeError } from '../apply-managed-rename.ts';import { createContentFilter } from '../content-filter.ts';import { isWithinContentDir } from '../content-path.ts';import { AuditCache } from './audit-cache.ts';+import { type AuditScope, resolveAuditScope } from './audit-scope.ts';import { unmatchedAppliesToProblems } from './frontmatter-schemas.ts';import { composeFrontmatterSchemasConfig, resolveEffectiveLinterConfig } from './resolve-config.ts';@@ -54,6 +56,7 @@ export interface AuditOptions {liveSourceFor?: (docRelPath: string) => string | null;cache?: AuditCache;auditGeneration?: () => string;+ resolvedScope?: AuditScope;}export async function lintDoc(@@ -168,6 +171,8 @@ export function collectDocFiles(opts: {}}+ const scopeRel = relative(contentDir, scopeDir ?? contentDir);+ if (scopeRel !== '' && filter.isDirExcluded(scopeRel)) return [];walk(scopeDir ?? contentDir);return docFiles;}@@ -181,22 +186,17 @@ export async function auditProject(const startGeneration = auditGeneration?.();const docFiles: string[] = [];- const scope = resolveScope(targetPath, contentDir);- const scopeRel = relative(contentDir, scope.path);- if (scopeRel.startsWith('..') || isAbsolute(scopeRel)) {- warnings.push(`refusing audit scope outside the content directory: ${targetPath ?? ''}`);- return { files: [], fileCount: 0, errorCount: 0, warningCount: 0, warnings, ran: [] };- }- if (scopeRel.split('/').some((segment) => segment.startsWith('.'))) {- warnings.push(`refusing audit scope under a hidden path segment: ${targetPath ?? ''}`);+ let scanIncomplete = false;+ const scopeWarning = auditScopeWarning(+ opts.resolvedScope ?? { path: resolve(contentDir, targetPath ?? '') },+ contentDir,+ targetPath,+ );+ if (scopeWarning !== undefined) {+ warnings.push(scopeWarning);return { files: [], fileCount: 0, errorCount: 0, warningCount: 0, warnings, ran: [] };}- try {- if (!isWithinContentDir(realpathSync(scope.path), realpathSync(contentDir))) {- warnings.push(`symlink-escape: audit scope resolves outside the content directory`);- return { files: [], fileCount: 0, errorCount: 0, warningCount: 0, warnings, ran: [] };- }- } catch {}+ const scope = opts.resolvedScope ?? resolveScope(targetPath, contentDir);if (scope.kind === 'file') {docFiles.push(relative(contentDir, scope.path));} else {@@ -205,12 +205,16 @@ export async function auditProject(projectDir,contentDir,scopeDir: scope.path,- onWarning: (warning) => warnings.push(warning),+ onWarning: (warning) => {+ scanIncomplete = true;+ warnings.push(warning);+ },}),);}docFiles.sort();+ if (docFiles.length === 0 && !scanIncomplete) warnings.push(AUDIT_EMPTY_SCOPE_WARNING);const files: FileLintResult[] = [];const pluginFailures: LintPluginFailure[] = [];@@ -225,7 +229,7 @@ export async function auditProject(const auditBase = composeFrontmatterSchemasConfig(projectDir, baseConfig, onConfigProblem);ran = deriveValidationRunSources(auditBase, { mode: 'lint' });const fmSlice = auditBase.plugins.frontmatter;- if ((targetPath === undefined || targetPath === '') && fmSlice.enabled) {+ if (scope.kind === 'dir' && relative(contentDir, scope.path) === '' && fmSlice.enabled) {for (const problem of unmatchedAppliesToProblems(fmSlice.schemas, docFiles)) {onConfigProblem(problem);}@@ -290,15 +294,52 @@ function resolveCanonicalDocPath(abs: string, contentDir: string): string {return canonical;}-type Scope = { kind: 'dir' | 'file'; path: string };--export function resolveScope(targetPath: string | undefined, contentDir: string): Scope {- if (targetPath === undefined || targetPath === '') return { kind: 'dir', path: contentDir };- const abs = isAbsolute(targetPath) ? targetPath : resolve(contentDir, targetPath);+export function auditScopeWarning(+ scope: Pick<AuditScope, 'path'>,+ contentDir: string,+ targetPath: string | undefined,+): string | undefined {+ const scopeRel = relative(contentDir, scope.path);+ if (scopeRel.startsWith('..') || isAbsolute(scopeRel)) {+ return `refusing audit scope outside the content directory: ${targetPath ?? ''}`;+ }+ if (scopeRel.split('/').some((segment) => segment.startsWith('.'))) {+ return `refusing audit scope under a hidden path segment: ${targetPath ?? ''}`;+ }+ let canonicalContent: string;try {- if (statSync(abs).isFile()) return { kind: 'file', path: abs };- } catch {}- return { kind: 'dir', path: abs };+ canonicalContent = realpathSync(contentDir);+ } catch (error) {+ if (+ error instanceof Error &&+ 'code' in error &&+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')+ ) {+ return undefined;+ }+ throw error;+ }+ let candidate = scope.path;+ for (;;) {+ try {+ if (!isWithinContentDir(realpathSync(candidate), canonicalContent)) {+ return 'symlink-escape: audit scope resolves outside the content directory';+ }+ return undefined;+ } catch (error) {+ if (!(error instanceof Error) || !('code' in error)) throw error;+ if (error.code === 'ELOOP' || error.code === 'ENAMETOOLONG') return undefined;+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;+ const parent = dirname(candidate);+ if (parent === candidate) return undefined;+ candidate = parent;+ }+ }+}++export function resolveScope(targetPath: string | undefined, contentDir: string): AuditScope {+ const resolution = resolveAuditScope(targetPath, contentDir);+ return resolution.ok ? resolution.scope : { kind: 'dir', path: resolution.path };}function isDocFile(name: string): boolean {diff --git a/packages/server/src/lint/okf-project-validator.ts b/packages/server/src/lint/okf-project-validator.tsindex 89a634478..80d61ce9c 100644--- a/packages/server/src/lint/okf-project-validator.ts+++ b/packages/server/src/lint/okf-project-validator.ts@@ -1,10 +1,10 @@-import { dirname, relative } from 'node:path';+import { dirname, relative, resolve } from 'node:path';import {deriveValidationRunSources,type LinterConfig,runOkfProjectRules,} from '@inkeep/open-knowledge-core';-import { collectDocFiles, resolveScope } from './audit.ts';+import { auditScopeWarning, collectDocFiles, resolveScope } from './audit.ts';import type {ProjectValidator,ValidationDiagnosticFor,@@ -36,7 +36,16 @@ export function createOkfProjectValidator(deps: OkfProjectValidatorDeps): Projec}const warnings: string[] = [];- const resolved = resolveScope(scope.targetPath, deps.contentDir);+ if (+ auditScopeWarning(+ scope.resolvedScope ?? { path: resolve(deps.contentDir, scope.targetPath ?? '') },+ deps.contentDir,+ scope.targetPath,+ ) !== undefined+ ) {+ return { files: [], fileCount: 0, warnings: [] };+ }+ const resolved = scope.resolvedScope ?? resolveScope(scope.targetPath, deps.contentDir);const targetFile =resolved.kind === 'file' ? relative(deps.contentDir, resolved.path) : undefined;const walkDir = resolved.kind === 'file' ? dirname(resolved.path) : resolved.path;@@ -63,7 +72,8 @@ export function createOkfProjectValidator(deps: OkfProjectValidatorDeps): Projecreturn {files: [...byFile.entries()].map(([file, diagnostics]) => ({ file, diagnostics })),- fileCount: targetFile === undefined ? docFiles.length : 1,+ fileCount:+ targetFile === undefined ? docFiles.length : Number(docFiles.includes(targetFile)),warnings,};},diff --git a/packages/server/src/lint/physical-scope-links.test.ts b/packages/server/src/lint/physical-scope-links.test.tsnew file mode 100644index 000000000..770cf7142--- /dev/null+++ b/packages/server/src/lint/physical-scope-links.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'vitest';+import { BacklinkIndex } from '../backlink-index.ts';++describe('isolated backlink document inventory', () => {+ test('resolves a single source against an immutable inventory without registering extra graph sources', () => {+ const inventory = new Set(['guides/known', 'literal.md']);+ const index = new BacklinkIndex({+ projectDir: '/unused',+ contentDir: '/unused',+ documentNames: inventory,+ });+ inventory.add('late');+ index.updateDocumentFromMarkdown('source', '[[known]] [[literal.md]] [[late]] [[missing]]');+ expect(index.getIndexedDocNames()).toEqual(['source']);+ expect(+ index+ .getDeadLinks(['source'])+ .map((entry) => entry.target)+ .sort(),+ ).toEqual(['late', 'missing']);+ });++ test('ordinary graph callers retain their own live inventory and source edits', () => {+ const index = new BacklinkIndex({ projectDir: '/unused', contentDir: '/unused' });+ index.updateDocumentFromMarkdown('source', '[[known]]');+ expect(index.getDeadLinks(['source']).map((entry) => entry.target)).toEqual(['known']);+ index.updateDocumentFromMarkdown('guides/known', '# Known');+ expect(index.getDeadLinks(['source', 'guides/known'])).toEqual([]);+ index.updateDocumentFromMarkdown('source', '[[new-ghost]]');+ expect(index.getDeadLinks(['source', 'guides/known']).map((entry) => entry.target)).toEqual([+ 'new-ghost',+ ]);+ });+});diff --git a/packages/server/src/lint/physical-scope-links.ts b/packages/server/src/lint/physical-scope-links.tsnew file mode 100644index 000000000..921763c27--- /dev/null+++ b/packages/server/src/lint/physical-scope-links.ts@@ -0,0 +1,79 @@+import { readFileSync, realpathSync } from 'node:fs';+import { extname, relative, resolve } from 'node:path';+import { SUPPORTED_DOC_EXTENSIONS } from '@inkeep/open-knowledge-core';+import { BacklinkIndex } from '../backlink-index.ts';+import { createContentFilter } from '../content-filter.ts';+import { isWithinContentDir } from '../content-path.ts';+import { isSupportedDocFile, stripDocExtension } from '../doc-extensions.ts';+import { assessLocalTargets, createTolerantDocumentResolver } from '../local-target-assessment.ts';+import { toPosix } from '../path-utils.ts';+import { readScopeEntry } from './audit-scope.ts';+import type { ValidationAuditDeps, ValidationScope } from './validation-audit.ts';++interface PhysicalScopeLinks {+ source: string;+ file: string;+ deadLinks: ReturnType<BacklinkIndex['getDeadLinks']>;+ localTargets: { source: string; assessments: ReturnType<typeof assessLocalTargets> }[];+}++export function physicalScopeLinks(+ scope: ValidationScope,+ deps: ValidationAuditDeps,+ admitted: readonly string[],+): PhysicalScopeLinks | undefined {+ const selected = scope.resolvedScope;+ if (selected?.kind !== 'file' || !isSupportedDocFile(selected.path)) return undefined;+ const stem = stripDocExtension(selected.path);+ const extension = extname(selected.path).toLowerCase();+ if (+ !SUPPORTED_DOC_EXTENSIONS.some(+ (candidate) =>+ candidate !== extension && readScopeEntry(`${stem}${candidate}`, true)?.isFile(),+ )+ )+ return undefined;++ const file = toPosix(relative(deps.contentDir, selected.path));+ const source = stripDocExtension(file);+ const filter = createContentFilter({ projectDir: deps.projectDir, contentDir: deps.contentDir });+ if (filter.isExcluded(file)) return undefined;+ const canonicalContent = realpathSync(deps.contentDir);+ const canonicalFile = realpathSync(selected.path);+ if (!isWithinContentDir(canonicalFile, canonicalContent))+ throw new Error('symlink-escape: audit scope resolves outside the content directory');++ const live = deps.docFilePathFor(source) === file ? deps.liveSourceFor?.(file) : null;+ const markdown = live ?? readFileSync(canonicalFile, 'utf8');+ const targetExists = (path: string, kind: 'file' | 'dir'): boolean => {+ const full = resolve(deps.contentDir, path);+ if (!isWithinContentDir(full, deps.contentDir)) return false;+ if (kind === 'file' ? filter.isExcluded(path) : filter.isDirExcluded(path)) return false;+ const stat = readScopeEntry(full, true);+ if (stat === undefined) return false;+ if (!isWithinContentDir(realpathSync(full), canonicalContent)) return false;+ return kind === 'file' ? stat.isFile() : stat.isDirectory();+ };+ const hasFile = (path: string) => targetExists(path, 'file');+ const hasFolder = (path: string) => targetExists(path, 'dir');+ const graph = new BacklinkIndex({+ projectDir: deps.projectDir,+ contentDir: deps.contentDir,+ documentNames: admitted,+ getFileOracle: () => ({ hasFile }),+ });+ graph.updateDocumentFromMarkdown(source, markdown);+ const documents = new Set(admitted);+ const assessments = assessLocalTargets(markdown, source, {+ hasDocument: (name) => documents.has(name),+ hasFile,+ hasFolder,+ resolveTolerantDocument: createTolerantDocumentResolver(documents),+ });+ return {+ source,+ file,+ deadLinks: graph.getDeadLinks(admitted, [source]).filter((link) => !hasFolder(link.target)),+ localTargets: [{ source, assessments }],+ };+}diff --git a/packages/server/src/lint/validation-audit.test.ts b/packages/server/src/lint/validation-audit.test.tsindex 05e67c1b0..b861e245c 100644--- a/packages/server/src/lint/validation-audit.test.ts+++ b/packages/server/src/lint/validation-audit.test.ts@@ -12,6 +12,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { BacklinkIndex } from '../backlink-index.ts';import type { LinkAdvisoryPolicy } from '../link-advisory-policy.ts';import { LocalTargetIndex } from '../local-target-index.ts';+import { resolveAuditScope } from './audit-scope.ts';import {createProjectValidators,type ProjectValidator,@@ -211,6 +212,29 @@ describe('runValidationAudit', () => {expect(scoped.warningCount).toBe(1);});+ test('an extensionless direct scope selects the same physical document in every validator', async () => {+ const source = '# Guide\n\n\tTabbed.\n\nSee [[ghost]].\n';+ writeFileSync(join(root, 'guide.md'), '# Other\n');+ writeFileSync(join(root, 'guide.mdx'), source);+ index.updateDocumentFromMarkdown('guide', source);+ localTargets.setSource('guide', source);+ admitted.add('guide');+ const config: LinterConfig = {+ ...lintOn,+ plugins: { ...lintOn.plugins, okf: { enabled: true } },+ };++ const result = await runValidationAudit(createProjectValidators(deps({ baseConfig: config })), {+ targetPath: 'guide',+ });++ expect(result.fileCount).toBe(1);+ expect(result.files.map((file) => file.file)).toEqual(['guide.mdx']);+ expect(result.files[0]?.diagnostics.map((diagnostic) => diagnostic.source)).toEqual(+ expect.arrayContaining(['markdownlint', 'links', 'okf']),+ );+ });+test('a scope matching no docs returns no findings even when dead links exist elsewhere', async () => {seedDoc('linker', '# Linker\n\nSee [[ghost]].\n');@@ -1205,3 +1229,90 @@ describe('reserved-log link advisory policy', () => {expect(result.brokenLinkSuppression).toBeUndefined();});});++describe('selected physical scope with same-stem document siblings', () => {+ test('each explicit suffix checks its own lint and link source without mutating the live index', async () => {+ seedDoc('guides/dual', '# MD\n\nA\ttab.\n\n[[md-ghost]] and [missing](./md-file.txt).\n');+ writeFileSync(+ join(root, 'guides/dual.mdx'),+ '# MDX\n\nA\ttab.\n\n[[mdx-ghost]] and [missing](./mdx-file.txt).\n',+ );+ const before = index.getDeadLinks(admitted);+ const validators = createProjectValidators(deps());+ const results = new Map<string, Awaited<ReturnType<typeof runValidationAudit>>>();+ for (const path of ['guides/dual', 'guides/dual.mdx', 'guides/dual.md']) {+ const resolution = resolveAuditScope(path, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: path,+ resolvedScope: resolution.scope,+ });+ results.set(path, result);+ const target = path.endsWith('.md') ? 'md' : 'mdx';+ expect(result.ran).toEqual(['markdownlint', 'links']);+ expect(result.fileCount).toBe(1);+ expect(result.files.map((file) => file.file)).toEqual([`guides/dual.${target}`]);+ const links =+ result.files[0]?.diagnostics.filter((diagnostic) => diagnostic.source === 'links') ?? [];+ expect(links).toHaveLength(2);+ expect(links.map((diagnostic) => diagnostic.linkTarget).filter(Boolean)).toEqual([+ `${target}-ghost`,+ ]);+ expect(links.find((diagnostic) => diagnostic.localTarget)?.localTarget?.resolvedTarget).toBe(+ `guides/${target}-file.txt`,+ );+ expect(result.warningCount).toBe(+ result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.severity !== 'error').length,+ );+ }+ expect(results.get('guides/dual')).toEqual(results.get('guides/dual.mdx'));+ expect(index.getDeadLinks(admitted)).toEqual(before);+ });++ test('an overlong link target is reported as missing instead of failing the links validator', async () => {+ const overlong = `${'x'.repeat(300)}.txt`;+ seedDoc('long', `# MD\n\n[[ghost]] and [missing](./${overlong}).\n`);+ writeFileSync(join(root, 'long.mdx'), '# MDX\n');+ const resolution = resolveAuditScope('long.md', root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(createProjectValidators(deps()), {+ targetPath: 'long.md',+ resolvedScope: resolution.scope,+ });+ expect(result.warnings ?? []).toEqual([]);+ const links = result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.source === 'links');+ expect(links.map((diagnostic) => diagnostic.linkTarget).filter(Boolean)).toEqual(['ghost']);+ expect(links.find((diagnostic) => diagnostic.localTarget)?.localTarget?.resolvedTarget).toBe(+ overlong,+ );+ });++ test('uses live source for the canonical sibling and disk source for the alternate sibling', async () => {+ seedDoc('dual', '# MD\n\n[[md-disk-ghost]]\n');+ writeFileSync(join(root, 'dual.mdx'), '# MDX\n\n[[mdx-disk-ghost]]\n');+ const validators = createProjectValidators(+ deps({ liveSourceFor: () => '# Live\n\n[[live-ghost]]\n' }),+ );+ for (const [path, expected] of [+ ['dual.mdx', 'live-ghost'],+ ['dual.md', 'md-disk-ghost'],+ ]) {+ const resolution = resolveAuditScope(path, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: path,+ resolvedScope: resolution.scope,+ });+ expect(+ result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.source === 'links')+ .map((diagnostic) => diagnostic.linkTarget),+ ).toEqual([expected]);+ }+ });+});diff --git a/packages/server/src/lint/validation-audit.ts b/packages/server/src/lint/validation-audit.tsindex 578b8b8e5..5c7f1095d 100644--- a/packages/server/src/lint/validation-audit.ts+++ b/packages/server/src/lint/validation-audit.ts@@ -1,10 +1,10 @@+import { relative, resolve } from 'node:path';import {type BrokenLinkSuppression,countDiagnosticsBySource,deriveValidationRunSources,type LinterConfig,type LintPluginId,- SUPPORTED_DOC_EXTENSIONS,type ValidationDiagnostic,type ValidationDocCounts,type ValidationSource,@@ -21,9 +21,12 @@ import {type LocalTargetAssessment,} from '../local-target-assessment.ts';import { getLogger } from '../logger.ts';-import { AuditSupersededError, auditProject } from './audit.ts';+import { toPosix } from '../path-utils.ts';+import { AuditSupersededError, auditProject, auditScopeWarning, resolveScope } from './audit.ts';import type { AuditCache } from './audit-cache.ts';+import type { AuditScope } from './audit-scope.ts';import { createOkfProjectValidator } from './okf-project-validator.ts';+import { physicalScopeLinks } from './physical-scope-links.ts';type DeadLinksResult = Awaited<ReturnType<DerivedDocumentIndexApiPort['getDeadLinks']>>;type LocalTargetsResult = Awaited<@@ -89,6 +92,7 @@ export function toValidationCountsPlane(export interface ValidationScope {targetPath?: string;+ resolvedScope?: AuditScope;}interface ValidatorRunResult<Source extends ValidationSource = ValidationSource> {@@ -239,6 +243,7 @@ function createLintValidator(deps: ValidationAuditDeps): ProjectValidator<LintPlcontentDir: deps.contentDir,baseConfig: deps.baseConfig,targetPath: scope.targetPath,+ resolvedScope: scope.resolvedScope,liveSourceFor: deps.liveSourceFor,cache: deps.cache,auditGeneration: deps.auditGeneration,@@ -268,6 +273,15 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator<'linkif (setting === 'off') {return { files: [], fileCount: 0, warnings: [] };}+ if (+ auditScopeWarning(+ scope.resolvedScope ?? { path: resolve(deps.contentDir, scope.targetPath ?? '') },+ deps.contentDir,+ scope.targetPath,+ ) !== undefined+ ) {+ return { files: [], fileCount: 0, warnings: [] };+ }const severity = setting === 'error' ? 'error' : 'warning';if (!deps.derivedDocumentIndex) {return {@@ -288,12 +302,26 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator<'link}};const admitted = [...(await deps.admittedDocNames())];- const sourceFilter = scopedSourceDocNames(admitted, scope.targetPath);+ const normalizedScope = {+ ...scope,+ resolvedScope: scope.resolvedScope ?? resolveScope(scope.targetPath, deps.contentDir),+ };+ const physical = physicalScopeLinks(normalizedScope, deps, admitted);+ const sourceFilter =+ physical === undefined+ ? scopedSourceDocNames(admitted, normalizedScope.resolvedScope, deps)+ : [physical.source];+ const filePathFor = (source: string): string =>+ physical?.source === source+ ? physical.file+ : (deps.docFilePathFor(source) ?? `${source}.md`);if (sourceFilter !== undefined && sourceFilter.length === 0) {assertCurrent();return { files: [], fileCount: 0, warnings: [] };}- const deadLinks = await deps.derivedDocumentIndex.getDeadLinks(admitted, sourceFilter);+ const deadLinks =+ physical?.deadLinks ??+ (await deps.derivedDocumentIndex.getDeadLinks(admitted, sourceFilter));const isSuppressedLogAdvisorySource = (source: string): boolean =>shouldSuppressLogLinkAdvisories(source, suppressLogAdvisories);@@ -315,11 +343,12 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator<'linklet suppressedBrokenLinkCount = 0;try {const assessed =- await deps.derivedDocumentIndex.getLocalTargetAssessmentsForSources(sourceFilter);+ physical?.localTargets ??+ (await deps.derivedDocumentIndex.getLocalTargetAssessmentsForSources(sourceFilter));for (const { source, assessments } of assessed) {if (isProblemsPlaneExcludedDoc(source)) continue;const suppressSource = isSuppressedLogAdvisorySource(source);- const file = deps.docFilePathFor(source) ?? `${source}.md`;+ const file = filePathFor(source);for (const assessment of assessments) {const diagnostic = toLocalTargetDiagnostic(assessment, severity);if (!diagnostic) continue;@@ -364,7 +393,7 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator<'linksuppressedBrokenLinkCount++;continue;}- const file = deps.docFilePathFor(occurrence.source) ?? `${occurrence.source}.md`;+ const file = filePathFor(occurrence.source);const line = occurrence.line ?? 0;const character = occurrence.column ?? 0;push(file, {@@ -440,14 +469,13 @@ function toLocalTargetDiagnostic(function scopedSourceDocNames(admitted: readonly string[],- targetPath: string | undefined,+ scope: AuditScope,+ deps: Pick<ValidationAuditDeps, 'contentDir' | 'docFilePathFor'>,): 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 scopePath = toPosix(relative(deps.contentDir, scope.path));+ if (scope.kind === 'file') {+ return admitted.filter((name) => deps.docFilePathFor(name) === scopePath);}- const prefix = `${targetPath.replace(/\/+$/, '')}/`;- return admitted.filter((name) => name.startsWith(prefix));+ if (scopePath === '') return undefined;+ return admitted.filter((name) => deps.docFilePathFor(name)?.startsWith(`${scopePath}/`));}diff --git a/packages/server/src/managed-rename-resolution.test.ts b/packages/server/src/managed-rename-resolution.test.tsnew file mode 100644index 000000000..e09062577--- /dev/null+++ b/packages/server/src/managed-rename-resolution.test.ts@@ -0,0 +1,198 @@+import {+ getWikiLinkText,+ resolveSkillBundleWikiTarget,+ resolveWikiLinkTargetDocName,+ skillLiveDocName,+} from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { applyRenameMap } from './apply-managed-rename.ts';+import { matchWikiLinks } from './link-syntax.ts';+import { createWikiRenameContext, rewriteWikiLinksForRenameMap } from './managed-rename-rewrite.ts';++function rewrite(content: string, pages: string[], renames: [string, string][], source = 'source') {+ const context = createWikiRenameContext(pages, new Map(renames));+ const result = applyRenameMap(content, source, context);+ const beforeLinks = content.split('\n').flatMap(matchWikiLinks);+ const afterLinks = result.markdown.split('\n').flatMap(matchWikiLinks);+ expect(afterLinks).toHaveLength(beforeLinks.length);+ for (const [i, before] of beforeLinks.entries()) {+ const original = resolveWikiLinkTargetDocName(+ resolveSkillBundleWikiTarget(before.target, source) ?? before.target,+ context.before,+ );+ const after = afterLinks[i];+ expect(getWikiLinkText(after)).toBe(getWikiLinkText(before));+ expect(after.anchor).toBe(before.anchor);+ if (original !== undefined) {+ expect(+ resolveWikiLinkTargetDocName(+ resolveSkillBundleWikiTarget(after.target, context.renames.get(source) ?? source) ??+ after.target,+ context.after,+ ),+ ).toBe(context.renames.get(original) ?? original);+ }+ }+ return result;+}++describe('managed rename preserves resolved wiki identity', () => {+ test('preserves the same slug-collision winner for reversed inventories', () => {+ for (const pages of [+ ['source', 'a/b', 'a-b'],+ ['a-b', 'a/b', 'source'],+ ]) {+ expect(rewrite('[[A B]]', pages, [['a-b', 'archive/winner']])).toEqual({+ markdown: '[[archive/winner|A B]]',+ rewrites: 1,+ });+ }+ });++ test('qualifies a moved target when its old basename would resolve to another document', () => {+ expect(+ rewrite(+ '[[beta]]',+ ['source', 'notes/beta', 'zzz/beta'],+ [['notes/beta', 'archive/beta-old']],+ ),+ ).toEqual({ markdown: '[[archive/beta-old|beta]]', rewrites: 1 });+ });++ test('qualifies an unmoved target when a new path would steal its basename winner', () => {+ expect(+ rewrite('[[beta]]', ['source', 'm/beta', 'notes/beta'], [['notes/beta', 'archive/beta']]),+ ).toEqual({ markdown: '[[m/beta|beta]]', rewrites: 1 });+ });++ test('keeps bytes for basename-preserving moves and unaffected documents', () => {+ const body = ' [[ beta # intro | Alias ]]\r\n[[BETA.mdx]]\r\n[[unresolved]]';+ expect(rewrite(body, ['source', 'notes/beta'], [['notes/beta', 'archive/beta']])).toEqual({+ markdown: body,+ rewrites: 0,+ });+ expect(+ rewrite('No links\n', ['source', 'notes/beta'], [['notes/beta', 'archive/beta']]),+ ).toEqual({ markdown: 'No links\n', rewrites: 0 });+ });++ test('preserves alias and heading bytes and adds a display alias only when absent', () => {+ expect(+ rewrite(+ '[[BETA# Intro | Display ]] [[beta#install]]',+ ['source', 'notes/beta'],+ [['notes/beta', 'archive/new']],+ ),+ ).toEqual({+ markdown: '[[archive/new# Intro | Display ]] [[archive/new#install|beta#install]]',+ rewrites: 2,+ });+ });++ test('keeps a Markdown suffix only when the emitted spelling resolves to the intended identity', () => {+ expect(+ rewrite(+ '[[notes/beta.md]]',+ ['source', 'notes/beta', 'archive/beta.md'],+ [['notes/beta', 'archive/beta']],+ ),+ ).toEqual({ markdown: '[[archive/beta|notes/beta.md]]', rewrites: 1 });+ expect(+ rewrite('[[notes/beta.mdx|Beta]]', ['source', 'notes/beta'], [['notes/beta', 'archive/new']]),+ ).toEqual({ markdown: '[[archive/new.mdx|Beta]]', rewrites: 1 });+ });++ test('uses complete pre/post batch snapshots through swaps and moved sources', () => {+ expect(+ rewrite(+ '[[a]] [[b]] [a](/notes/a.md) [b](/notes/b.md)',+ ['source', 'notes/a', 'notes/b'],+ [+ ['notes/a', 'notes/b'],+ ['notes/b', 'notes/a'],+ ],+ ),+ ).toEqual({+ markdown: '[[notes/b|a]] [[notes/a|b]] [a](/notes/b.md) [b](/notes/a.md)',+ rewrites: 4,+ });+ expect(+ rewrite(+ '[[beta]] [Beta](./beta.md)',+ ['notes/source', 'notes/beta'],+ [+ ['notes/source', 'archive/source'],+ ['notes/beta', 'archive/beta'],+ ],+ 'notes/source',+ ),+ ).toEqual({ markdown: '[[beta]] [Beta](beta.md)', rewrites: 2 });+ });++ test('ordinary fuzzy links ignore global skills while explicit and project skill targets stay supported', () => {+ const global = skillLiveDocName('global', 'demo');+ const reference = `${global}/references/beta`;+ expect(+ rewrite('[[beta]]', ['source', reference, 'notes/beta'], [['notes/beta', 'archive/new']])+ .markdown,+ ).toBe('[[archive/new|beta]]');+ expect(+ rewrite(`[[${global}]]`, ['source', global, 'notes/beta'], [['notes/beta', 'archive/new']])+ .rewrites,+ ).toBe(0);+ const skill = '.agents/skills/demo/references/beta';+ expect(+ rewrite('[[beta]]', ['source', skill], [[skill, '.agents/skills/renamed/references/new']])+ .markdown,+ ).toBe('[[.agents/skills/renamed/references/new|beta]]');+ });++ test.each(['SKILL', 'references/nested/guide'])(+ 'rewrites a bundle-relative internal target from %s',+ (sourcePath) => {+ const bundle = '.agents/skills/demo';+ const source = `${bundle}/${sourcePath}`;+ const target = `${bundle}/references/beta`;+ expect(+ rewrite(+ '[[references/beta.md#intro| Beta ]]',+ [source, target, '.agents/skills/other/references/beta'],+ [[target, `${bundle}/references/renamed`]],+ source,+ ),+ ).toEqual({+ markdown: '[[.agents/skills/demo/references/renamed.md#intro| Beta ]]',+ rewrites: 1,+ });+ },+ );++ test('moving an entire bundle preserves relative wiki bytes from the skill and nested references', () => {+ const bundle = '.agents/skills/demo';+ const pages = [+ `${bundle}/SKILL`,+ `${bundle}/references/nested/guide`,+ `${bundle}/references/beta`,+ ];+ const renames: [string, string][] = pages.map((page) => [+ page,+ page.replace('/demo/', '/renamed/'),+ ]);+ const body = ' [[ references/beta.md# intro | Beta ]]\r\n[[references/beta]]\r\n';+ for (const source of pages.slice(0, 2)) {+ expect(rewrite(body, pages, renames, source)).toEqual({ markdown: body, rewrites: 0 });+ }+ });++ test('fenced code, inline code and escaped links stay byte identical', () => {+ const content = '```md\n[[beta]]\n```\n`[[beta]]` \\[[beta]]';+ const context = createWikiRenameContext(+ ['source', 'notes/beta'],+ new Map([['notes/beta', 'archive/new']]),+ );+ expect(rewriteWikiLinksForRenameMap(content, 'source', context)).toEqual({+ markdown: content,+ rewrites: 0,+ });+ });+});diff --git a/packages/server/src/managed-rename-rewrite.test.ts b/packages/server/src/managed-rename-rewrite.test.tsindex 0a200a3b8..9fbdecc7f 100644--- a/packages/server/src/managed-rename-rewrite.test.ts+++ b/packages/server/src/managed-rename-rewrite.test.ts@@ -6,11 +6,13 @@ import {} from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {+ createWikiRenameContext,rewriteAssetReferencesForRename,rewriteJsxSrcRefsForDocumentRename,rewriteMarkdownLinksForDocumentRename,rewriteOutboundMarkdownLinksForSourceMove,rewriteWikiLinksForDocumentRename,+ rewriteWikiLinksForRenameMap,} from './managed-rename-rewrite.ts';import { findWikiLinkAttrs, type PmJson } from './wiki-pm-json.test-helper.ts';@@ -993,6 +995,61 @@ describe('rewriteWikiLinksForDocumentRename — escaped alias separators insidereturn count;}+ test.each([+ ['| Link |\n| --- |\n| [[beta]] |', '| Link |\n| --- |\n| [[gamma\\|beta]] |'],+ [+ 'Link | Note\n--- | ---\n[[beta#part]] | value',+ 'Link | Note\n--- | ---\n[[gamma#part\\|beta#part]] | value',+ ],+ ])('synthesized alias keeps the table row intact', (before, after) => {+ const context = createWikiRenameContext(['beta'], new Map([['beta', 'gamma']]));+ const result = rewriteWikiLinksForRenameMap(before, 'index', context);+ expect(result).toEqual({ markdown: after, rewrites: 1 });+ expect(dataRowCellCount(result.markdown)).toBe(dataRowCellCount(before));+ expect(findWikiLinkAttrs(mdManager.parse(result.markdown) as unknown as PmJson)).toMatchObject({+ target: 'gamma',+ alias: before.includes('#part') ? 'beta#part' : 'beta',+ });+ });++ test.each([+ ['| A | B |\n|-|-|\n| [[beta]] | c |', '| A | B |\n|-|-|\n| [[gamma\\|beta]] | c |'],+ ['| A | B |\n|--|--|\n| [[beta]] | c |', '| A | B |\n|--|--|\n| [[gamma\\|beta]] | c |'],+ ['| A | B |\n|:-:|:-:|\n| [[beta]] | c |', '| A | B |\n|:-:|:-:|\n| [[gamma\\|beta]] | c |'],+ [+ '> | A | B |\n> |---|---|\n> | [[beta]] | c |',+ '> | A | B |\n> |---|---|\n> | [[gamma\\|beta]] | c |',+ ],+ [+ '- | A | B |\n | --- | --- |\n | [[beta]] | c |',+ '- | A | B |\n | --- | --- |\n | [[gamma\\|beta]] | c |',+ ],+ ['| A |\n| --- |\n| x |\n[[beta]]', '| A |\n| --- |\n| x |\n[[gamma\\|beta]]'],+ ])('synthesized alias keeps every GFM table form intact: %j', (before, after) => {+ const context = createWikiRenameContext(['beta'], new Map([['beta', 'gamma']]));+ const result = rewriteWikiLinksForRenameMap(before, 'index', context);+ expect(result).toEqual({ markdown: after, rewrites: 1 });+ expect(dataRowCellCount(result.markdown)).toBe(dataRowCellCount(before));+ expect(findWikiLinkAttrs(mdManager.parse(result.markdown) as unknown as PmJson)).toMatchObject({+ target: 'gamma',+ alias: 'beta',+ });+ });++ test.each([+ [+ '| A |\n| --- |\n| x |\n# Heading [[beta]]',+ '| A |\n| --- |\n| x |\n# Heading [[gamma|beta]]',+ ],+ ['```\n| A |\n| --- |\n```\n[[beta]]', '```\n| A |\n| --- |\n```\n[[gamma|beta]]'],+ ])('synthesized alias outside a GFM table stays unescaped: %j', (before, after) => {+ const context = createWikiRenameContext(['beta'], new Map([['beta', 'gamma']]));+ expect(rewriteWikiLinksForRenameMap(before, 'index', context)).toEqual({+ markdown: after,+ rewrites: 1,+ });+ });+test('no-anchor rename keeps the escape and the cell whole', () => {const row = '| Link |\n| --- |\n| [[Page\\|Friendly label]] |';const result = rewriteWikiLinksForDocumentRename(row, 'Page', 'NewPage');diff --git a/packages/server/src/managed-rename-rewrite.ts b/packages/server/src/managed-rename-rewrite.tsindex f4c88cb1b..83763c21b 100644--- a/packages/server/src/managed-rename-rewrite.ts+++ b/packages/server/src/managed-rename-rewrite.ts@@ -2,18 +2,25 @@ import { posix } from 'node:path';import {encodeHrefPath,encodeHrefPathSegment,+ getWikiLinkText,isExternalHref,type JsxSrcRefTagSpec,rawSegmentOr,resolveAssetProjectPath,resolveInternalHref,+ resolveSkillBundleWikiTarget,+ resolveWikiLinkTargetDocName,+ type WikiLinkLookupIndex,} from '@inkeep/open-knowledge-core';+import type { Nodes as MdastNodes } from 'mdast';import {createJsxSrcAttrRe,readJsxSrcRefTagAt,resolveJsxSrcRefTarget,} from './jsx-src-ref-tags.ts';import { readMarkdownLinkAt, readWikiLinkAt, type WikiLinkMatch } from './link-syntax.ts';+import { mdManager } from './md-manager.ts';+import { buildProjectWikiLinkLookup } from './project-wiki-link-lookup.ts';interface FenceState {char: '`' | '~';@@ -173,12 +180,30 @@ function splitLines(markdown: string): Array<{ line: string; ending: string }> {return lines;}+function gfmTableRows(markdown: string): ReadonlySet<number> {+ const rows = new Set<number>();+ if (!markdown.includes('|')) return rows;+ const visit = (node: MdastNodes): void => {+ if (node.type === 'table' && node.position) {+ for (let line = node.position.start.line; line <= node.position.end.line; line++)+ rows.add(line - 1);+ }+ if ('children' in node) for (const child of node.children) visit(child);+ };+ visit(mdManager.parseToMdast(markdown));+ return rows;+}+type WikiLinkRenameSegments = Pick<WikiLinkMatch,'targetRaw' | 'anchor' | 'anchorRaw' | 'alias' | 'aliasRaw'>;-function renderWikiLinkSegments(segments: WikiLinkRenameSegments, nextTarget: string): string {+function renderWikiLinkSegments(+ segments: WikiLinkRenameSegments,+ nextTarget: string,+ escapeAliasSeparator = false,+): string {let out = `[[${nextTarget}`;const anchorRaw = segments.anchorRaw;const anchorSegmentSurvived = anchorRaw !== null && anchorRaw.trim() !== '';@@ -193,7 +218,7 @@ function renderWikiLinkSegments(segments: WikiLinkRenameSegments, nextTarget: st: rawSegmentOr(segments.aliasRaw, '', 'alias');if (alias.length > 0) {if (!anchorSegmentSurvived && segments.targetRaw.trim().endsWith('\\')) out += '\\';- out += `|${alias}`;+ out += escapeAliasSeparator ? `\\|${alias.replaceAll('|', '\\|')}` : `|${alias}`;}return `${out}]]`;}@@ -202,6 +227,11 @@ function rewriteWikiLinksInLine(line: string,oldDocName: string,newDocName: string,+ rewriteTarget?: (+ link: WikiLinkRenameSegments & { target: string },+ inTable: () => boolean,+ ) => string | null,+ inTable: () => boolean = () => false,): RenameRewriteResult {let rewritten = '';let rewrites = 0;@@ -232,8 +262,13 @@ function rewriteWikiLinksInLine(if (line[idx] === '[' && line[idx + 1] === '[') {const wikiLink = readWikiLink(line, idx);if (wikiLink) {- if (wikiLink.target === oldDocName) {- rewritten += renderWikiLinkSegments(wikiLink, newDocName);+ const replacement = rewriteTarget+ ? rewriteTarget(wikiLink, inTable)+ : wikiLink.target === oldDocName+ ? renderWikiLinkSegments(wikiLink, newDocName)+ : null;+ if (replacement !== null) {+ rewritten += replacement;rewrites++;} else {rewritten += line.slice(idx, wikiLink.nextIndex);@@ -769,16 +804,88 @@ export function rewriteJsxSrcRefsForDocumentRename(return { markdown: rewrittenMarkdown, rewrites };}+export interface WikiRenameContext {+ readonly before: WikiLinkLookupIndex;+ readonly after: WikiLinkLookupIndex;+ readonly renames: ReadonlyMap<string, string>;+}++export function createWikiRenameContext(+ docNames: Iterable<string>,+ renameMap: ReadonlyMap<string, string>,+): WikiRenameContext {+ const renames = new Map(renameMap);+ const before = buildProjectWikiLinkLookup(docNames);+ const after = buildProjectWikiLinkLookup(+ [...before.pages].map((page) => renames.get(page) ?? page),+ );+ return { before, after, renames };+}++function resolveRenameWikiTarget(+ target: string,+ sourceDocName: string,+ lookup: WikiLinkLookupIndex,+): string | undefined {+ return resolveWikiLinkTargetDocName(+ resolveSkillBundleWikiTarget(target, sourceDocName) ?? target,+ lookup,+ );+}++export function wikiLinkRenameDestination(+ target: string,+ sourceDocName: string,+ context: WikiRenameContext,+): string | null {+ const originalTarget = resolveRenameWikiTarget(target, sourceDocName, context.before);+ if (originalTarget === undefined) return null;+ const desired = context.renames.get(originalTarget) ?? originalTarget;+ const nextSource = context.renames.get(sourceDocName) ?? sourceDocName;+ return resolveRenameWikiTarget(target, nextSource, context.after) === desired ? null : desired;+}++export function rewriteWikiLinksForRenameMap(+ markdown: string,+ sourceDocName: string,+ context: WikiRenameContext,+): RenameRewriteResult {+ const nextSource = context.renames.get(sourceDocName) ?? sourceDocName;+ return rewriteWikiLinksForDocumentRename(markdown, '', '', (link, inTable) => {+ const desired = wikiLinkRenameDestination(link.target, sourceDocName, context);+ if (desired === null) return null;+ const suffix = link.target.match(/\.(md|mdx)$/i)?.[0];+ const withSuffix = suffix ? `${desired}${suffix}` : desired;+ const nextTarget =+ resolveRenameWikiTarget(withSuffix, nextSource, context.after) === desired+ ? withSuffix+ : desired;+ if (link.alias) return renderWikiLinkSegments(link, nextTarget);+ const display = getWikiLinkText({ target: link.target, alias: null, anchor: link.anchor });+ return renderWikiLinkSegments(+ { ...link, alias: display, aliasRaw: display },+ nextTarget,+ inTable(),+ );+ });+}+export function rewriteWikiLinksForDocumentRename(markdown: string,oldDocName: string,newDocName: string,+ rewriteTarget?: (+ link: WikiLinkRenameSegments & { target: string },+ inTable: () => boolean,+ ) => string | null,): RenameRewriteResult {let fence: FenceState | null = null;let rewrites = 0;+ const lines = splitLines(markdown);+ let tableRows: ReadonlySet<number> | undefined;- const rewrittenMarkdown = splitLines(markdown)- .map(({ line, ending }) => {+ const rewrittenMarkdown = lines+ .map(({ line, ending }, row) => {if (fence) {if (isFenceClose(line, fence)) {fence = null;@@ -792,7 +899,16 @@ export function rewriteWikiLinksForDocumentRename(return `${line}${ending}`;}- const rewrittenLine = rewriteWikiLinksInLine(line, oldDocName, newDocName);+ const rewrittenLine = rewriteWikiLinksInLine(+ line,+ oldDocName,+ newDocName,+ rewriteTarget,+ () => {+ tableRows ??= gfmTableRows(markdown);+ return tableRows.has(row);+ },+ );rewrites += rewrittenLine.rewrites;return `${rewrittenLine.markdown}${ending}`;})diff --git a/packages/server/src/mcp-managed-rename-resolution.test.ts b/packages/server/src/mcp-managed-rename-resolution.test.tsnew file mode 100644index 000000000..b4f1e8f8b--- /dev/null+++ b/packages/server/src/mcp-managed-rename-resolution.test.ts@@ -0,0 +1,130 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { resolveWikiLinkTargetDocName } from '@inkeep/open-knowledge-core';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';+import { matchWikiLinks } from './link-syntax.ts';+import { buildProjectWikiLinkLookup } from './project-wiki-link-lookup.ts';++const cases = [+ {+ name: 'moved target loses basename precedence',+ from: 'notes/beta',+ to: 'archive/beta-old',+ pages: { 'notes/beta': '# Beta\n', 'zzz/beta': '# Other\n', source: '[[beta#intro]]\n' },+ expected: { source: '[[archive/beta-old#intro|beta#intro]]\n' },+ targets: { source: ['archive/beta-old'] },+ },+ {+ name: 'new destination would steal an unmoved target',+ from: 'notes/beta',+ to: 'archive/beta',+ pages: { 'notes/beta': '# Moving\n', 'm/beta': '# Intended\n', source: '[[beta|Original]]\n' },+ expected: { source: '[[m/beta|Original]]\n' },+ targets: { source: ['m/beta'] },+ },+ {+ name: 'a suffix collision cannot redirect to an exact dotted identity',+ from: 'notes/beta',+ to: 'archive/beta',+ pages: {+ 'notes/beta': '# Beta\n',+ 'archive/beta.md': '# Dotted\n',+ source: '[[notes/beta.md]]\n',+ },+ expected: { source: '[[archive/beta|notes/beta.md]]\n' },+ targets: { source: ['archive/beta'] },+ },+ {+ name: 'folder batch preserves shorthand bytes and rewrites qualified links once',+ from: 'notes',+ to: 'archive',+ pages: {+ 'notes/beta': '# Beta\n',+ 'notes/gamma': '[[beta]]\n',+ source: '[[beta]] [[GAMMA.mdx|Gamma]] [[notes/beta#intro| Beta ]]\r\n',+ control: 'Unrelated bytes.\r\n',+ },+ expected: {+ source: '[[beta]] [[GAMMA.mdx|Gamma]] [[archive/beta#intro| Beta ]]\r\n',+ 'archive/gamma': '[[beta]]\n',+ control: 'Unrelated bytes.\r\n',+ },+ targets: {+ source: ['archive/beta', 'archive/gamma', 'archive/beta'],+ 'archive/gamma': ['archive/beta'],+ control: [],+ },+ },+] satisfies Array<{+ name: string;+ from: string;+ to: string;+ pages: Record<string, string>;+ expected: Record<string, string>;+ targets: Record<string, string[]>;+}>;++test.each(cases)(+ 'managed MCP move: $name',+ async ({ from, to, pages, expected, targets }) => {+ const root = mkdtempSync(join(tmpdir(), 'ok-mcp-rename-resolution-'));+ let booted: BootedServer | undefined;+ const client = new Client({ name: 'codex', version: '0.0.0-test' });+ try {+ for (const [name, body] of Object.entries(pages)) {+ const file = join(root, `${name}${name === 'notes/beta' ? '.mdx' : '.md'}`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ }+ booted = await bootCompositionRig(root);+ await booted.ready;+ await client.connect(+ new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${booted.port}/mcp`)),+ );+ const connection = await booted.serverInstance.hocuspocus.openDirectConnection('source');+ try {+ const result = await client.callTool({ name: 'move', arguments: { from, to, cwd: root } });+ expect(result.isError ?? false, JSON.stringify(result)).toBe(false);+ expect(existsSync(join(root, `${from}.md`))).toBe(false);+ expect(existsSync(join(root, `${from}.mdx`))).toBe(false);+ expect(existsSync(join(root, from))).toBe(false);+ const postPages = Object.keys(pages).map((page) =>+ page === from+ ? to+ : page.startsWith(`${from}/`)+ ? `${to}${page.slice(from.length)}`+ : page,+ );+ const lookup = buildProjectWikiLinkLookup(postPages);+ for (const [name, body] of Object.entries(expected)) {+ const actual = readFileSync(join(root, `${name}.md`), 'utf8');+ expect(actual, name).toBe(body);+ const actualTargets = actual+ .split(/\r?\n/)+ .flatMap(matchWikiLinks)+ .map((link) => resolveWikiLinkTargetDocName(link.target, lookup));+ expect(actualTargets, name).toEqual(targets[name]);+ }+ expect(connection.document.getText('source').toString()).toBe(expected.source);+ const dead = await client.callTool({+ name: 'links',+ arguments: { kind: 'dead', sourceDocuments: Object.keys(expected), cwd: root },+ });+ expect(dead.isError ?? false).toBe(false);+ expect(dead.structuredContent).toMatchObject({ deadLinks: [] });+ } finally {+ await connection.disconnect();+ }+ } finally {+ await client.close();+ await booted?.destroy();+ rmSync(root, { recursive: true, force: true });+ }+ },+ 60_000,+);diff --git a/packages/server/src/mcp/tools/audit.test.ts b/packages/server/src/mcp/tools/audit.test.tsindex 7ea1eb6e0..8eb0fa74f 100644--- a/packages/server/src/mcp/tools/audit.test.ts+++ b/packages/server/src/mcp/tools/audit.test.ts@@ -475,7 +475,11 @@ describe('audit — output cap', () => {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('lint({ document: "doc-00.md" })');+ expect(text).toContain('links({ kind: "dead", sourceDocuments: ["doc-00.md"] })');+ expect(text).toContain('Project-tree OKF findings remain capped');expect(text).toContain('… and 2 more files with problems');+ expect(text).toContain('Narrow path to reduce competing files; per-file caps still apply');expect(text).toContain('markdownlint/MD010');expect(text).toContain('links/dead-link');const shownFileHeaders = text.match(/^doc-\d+\.md:$/gm) ?? [];diff --git a/packages/server/src/mcp/tools/audit.ts b/packages/server/src/mcp/tools/audit.tsindex 8cecbb680..e82165b49 100644--- a/packages/server/src/mcp/tools/audit.ts+++ b/packages/server/src/mcp/tools/audit.ts@@ -21,20 +21,15 @@ import {resolveProjectServerContext,textPlusStructured,textResult,+ zeroFindingsSummary,} 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.',- '- The result reports `ran`, the source families selected for this run. Project audit can report `markdownlint`, `frontmatter`, `okf`, and `links`. A family absent from `ran` was not checked. `okf` covers both document and project-tree OKF checks here.',- '- A selected family stays in `ran` if it degrades, with the reason in `warnings`. A partial degradation may still have contributed findings.',- '- 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.)',- '- Broken links written INSIDE a lowercase-stemmed `log.md`/`log.mdx` are omitted at any depth while the project\'s default-on `validation.suppressLogLinkAdvisories` setting is enabled. When findings are withheld, `brokenLinkSuppression: { reason: "reserved-log-policy", count: N }` makes the filtered result explicit without exposing paths or hrefs. A log is an append-only history whose entries deliberately reference pages that moved or were never written, so repairing them would rewrite that history. `LOG.md` is an ordinary doc and keeps its findings, and `links({ kind: "dead" })` reads the raw state unconditionally.',- '',- "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 and project-wide at 10 warnings, with explicit '… and N more' indicators and `omittedWarningCount` when warnings are dropped; 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`.',+ 'Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.',+ 'ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.',+ "Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.",+ 'Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.',+ 'Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.',].join('\n');export const AUDIT_WARNINGS_DESCRIPTION =@@ -153,7 +148,7 @@ async function runAudit(path: string | undefined, url: string, cwd: string) {const fileCount = data.fileCount ?? 0;const errorCount = data.errorCount ?? 0;const warningCount = data.warningCount ?? 0;- const coverageLines = validationCoverageLines(data.ran);+ const coverageLines = validationCoverageLines(data.ran, fileCount);const rawSuppression = data.brokenLinkSuppression;const suppressionPresent = rawSuppression !== undefined && rawSuppression !== null;const suppression = parseBrokenLinkSuppression(rawSuppression);@@ -197,10 +192,7 @@ async function runAudit(path: string | undefined, url: string, cwd: string) {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}.`;+ const summary = zeroFindingsSummary('Audit', fileCount, warnings, scope);return textPlusStructured([summary,@@ -216,14 +208,16 @@ async function runAudit(path: string | undefined, url: string, cwd: string) {const lines = file.diagnostics.map(formatDiagnosticLine);if (file.omittedDiagnosticCount !== undefined) {lines.push(- ` … and ${file.omittedDiagnosticCount} more problem${file.omittedDiagnosticCount === 1 ? '' : 's'}`,+ ` … and ${file.omittedDiagnosticCount} more problem${file.omittedDiagnosticCount === 1 ? '' : 's'}. For lint findings, use lint({ document: ${JSON.stringify(file.file)} }); for broken links, use links({ kind: "dead", sourceDocuments: [${JSON.stringify(file.file)}] }). Project-tree OKF findings remain capped.`,);}return [`${file.file ?? '(unknown)'}:`, ...lines].join('\n');});const footer =omittedFileCount > 0- ? [`… and ${omittedFileCount} more file${omittedFileCount === 1 ? '' : 's'} with problems`]+ ? [+ `… and ${omittedFileCount} more file${omittedFileCount === 1 ? '' : 's'} with problems. Narrow path to reduce competing files; per-file caps still apply.`,+ ]: [];return textPlusStructured([diff --git a/packages/server/src/mcp/tools/checkpoint.ts b/packages/server/src/mcp/tools/checkpoint.tsindex ae5033591..a0dde25a2 100644--- a/packages/server/src/mcp/tools/checkpoint.ts+++ b/packages/server/src/mcp/tools/checkpoint.ts@@ -17,12 +17,7 @@ import {} from './shared.ts';export const DESCRIPTION = [- '[Requires: Hocuspocus server] Save a project-wide checkpoint of every document — a single restore point you can return to.',- '',- '**Parameters:**',- '- `summary` — Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Appears as the checkpoint subject in `history`. Avoid secrets or PII — persisted to git history.',- '',- 'Returns `{ version }` — the 40-char checkpoint SHA. Find checkpoints later via `history`; restore a single doc with `restore_version({ document, version })`.',+ 'Save a project-wide checkpoint of every document. Requires the Hocuspocus server. Optional summary ≤80 chars defaults to "Checkpoint version"; avoid secrets or PII because it persists in git history. Returns version (40-char SHA). Find it with history and restore one doc with restore_version({document,version}).',].join('\n');export interface CheckpointDeps {diff --git a/packages/server/src/mcp/tools/config.ts b/packages/server/src/mcp/tools/config.tsindex e3bc70719..536820ee9 100644--- a/packages/server/src/mcp/tools/config.ts+++ b/packages/server/src/mcp/tools/config.ts@@ -8,19 +8,8 @@ import {} from './shared.ts';const DESCRIPTION = [- '[Operates on disk; no running OK server required] Read the effective merged OpenKnowledge config (defaults → user → project).',- '',- 'Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.',- '',- 'Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.',- '',- 'Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)',- '',- "This tool is a pure READ. Folder-level skill topology (link / unlink / add-root) moved to the `install` tool's `skillFolders` argument, so this one keeps its read-only annotation and stays auto-approvable.",- '',- '**Parameters:**',- '- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',- '- `cwd` (optional) — Project root (see `cwd` description below).',+ 'Read effective config merged defaults → user → project; no running OK server needed. Optional key is a dotted path (content, appearance.theme); omit for the full config. All fields are readable. Re-read after disk changes or before relying on an old value.',+ 'Removed server.*, mcp.*, github.*, preview.baseUrl and preview.scriptSrc return exists:false; appearance.preview.autoOpen remains live. This is a pure read. Use `install` skillFolders for folder topology.',].join('\n');interface GetConfigDeps {diff --git a/packages/server/src/mcp/tools/conflicts.test.ts b/packages/server/src/mcp/tools/conflicts.test.tsdeleted file mode 100644index 0f6abcf5d..000000000--- a/packages/server/src/mcp/tools/conflicts.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { mkdtempSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';-import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';-import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';-import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';-import { afterAll, beforeAll, describe, expect, test } from 'vitest';-import { type Config, ConfigSchema } from '../../config/schema.ts';-import { register } from './conflicts.ts';-import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';-import type { ServerInstance } from './shared.ts';-import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';--const BASE_CONFIG: Config = ConfigSchema.parse({});--interface ToolResult {- content: Array<{ type: 'text'; text: string }>;- structuredContent?: Record<string, unknown>;- isError?: boolean;-}-type Handler = (args: {- kind: 'list' | 'content';- file?: string;- cwd?: string;-}) => Promise<ToolResult>;--function capture(serverUrl: string | undefined, cwd: string): Handler {- let handler: Handler | undefined;- const server = {- registerTool(_n: string, config: { outputSchema: unknown }, h: Handler) {- const normalized = normalizeObjectSchema(config.outputSchema);- if (!normalized) throw new Error('missing output schema');- const schema = toJsonSchemaCompat(normalized, { strictUnions: true, pipeStrategy: 'output' });- expect(JSON.stringify(schema)).toContain('stale-external-write');- expect(JSON.stringify(schema)).toContain('working-tree');- const validateAgainstAdvertisedSchema = new AjvJsonSchemaValidator().getValidator(schema);- handler = async (args) => {- const result = await h(args);- if (result.structuredContent) {- expect(validateAgainstAdvertisedSchema(result.structuredContent).valid).toBe(true);- if (args.kind === 'content') {- expect(- validateAgainstAdvertisedSchema({- ...result.structuredContent,- content: {- ...(result.structuredContent.content as Record<string, unknown>),- conflictKind: 'unknown',- },- }).valid,- ).toBe(false);- } else {- expect(- validateAgainstAdvertisedSchema({- ...result.structuredContent,- list: [{ file: 'a.md', detectedAt: 'now', conflictKind: 'unknown' }],- }).valid,- ).toBe(false);- }- }- return result;- };- },- } as unknown as ServerInstance;- register(server, { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwd });- if (!handler) throw new Error('not registered');- return handler;-}--let testServer: FetchTestServer;-let baseUrl: string;-const cwd = mkdtempSync(join(tmpdir(), 'ok-conflicts-test-'));--beforeAll(async () => {- testServer = await startFetchTestServer({- port: 0,- hostname: '127.0.0.1',- fetch(req) {- const url = new URL(req.url);- if (url.pathname === '/api/sync/conflicts') {- return Response.json({- ok: true,- conflicts: [- {- file: 'notes/sso.md',- detectedAt: 'now',- conflict: 'reconcile',- reason: 'stale-external-write',- conflictKind: 'stale-external-write',- docName: 'notes/sso',- },- {- file: 'overlay.md',- detectedAt: 'now',- conflict: 'working-tree',- conflictKind: 'git',- docName: 'overlay',- },- ],- });- }- if (url.pathname === '/api/sync/conflict-content') {- return Response.json({- ok: true,- file: 'notes/sso.md',- base: 'B',- ours: 'O',- theirs: 'T',- kind: 'both-modified',- conflict: 'reconcile',- reason: 'stale-external-write',- conflictKind: 'stale-external-write',- resolutionOptions: ['mine', 'theirs', 'content', 'delete'],- });- }- return new Response('Not found', { status: 404 });- },- });- baseUrl = `http://127.0.0.1:${testServer.port}`;-});-afterAll(() => testServer.stop());--describe('conflicts — kind discriminator', () => {- test('kind:list enumerates tracked conflicts (nested under `list`)', async () => {- const result = await capture(baseUrl, cwd)({ kind: 'list' });- expect(result.isError).toBeFalsy();- expect(result.structuredContent?.list).toMatchObject([- { conflict: 'reconcile', conflictKind: 'stale-external-write' },- { conflict: 'working-tree', conflictKind: 'git' },- ]);- expect(result.content[0]?.text).toContain('notes/sso.md (reconcile / stale-external-write)');- expect(result.content[0]?.text).toContain('overlay.md (working-tree)');- });-- test('kind:content nests stages under `content` and remaps route `kind` → `shape` (DD4)', async () => {- const result = await capture(baseUrl, cwd)({ kind: 'content', file: 'notes/sso.md' });- expect(result.isError).toBeFalsy();- const content = result.structuredContent?.content as { shape?: string } | undefined;- expect(content?.shape).toBe('both-modified');- expect(content).toMatchObject({- conflict: 'reconcile',- conflictKind: 'stale-external-write',- resolutionOptions: ['mine', 'theirs', 'content', 'delete'],- });- expect(content).not.toHaveProperty('kind');- expect(result.content[0]?.text).toContain('shape: both-modified');- expect(result.content[0]?.text).toContain('strategies: mine, theirs, content, delete');- });-- test('kind:content without `file` returns a teaching error', async () => {- const result = await capture(baseUrl, cwd)({ kind: 'content' });- expect(result.isError).toBe(true);- expect(result.content[0]?.text).toContain('requires `file`');- });-- test('Hocuspocus-unavailable error when no serverUrl', async () => {- const result = await capture(undefined, cwd)({ kind: 'list' });- expect(result.isError).toBe(true);- expect(result.content[0]?.text).toContain(HOCUSPOCUS_NOT_RUNNING_ERROR);- });-});diff --git a/packages/server/src/mcp/tools/conflicts.ts b/packages/server/src/mcp/tools/conflicts.tsdeleted file mode 100644index c1e63d79f..000000000--- a/packages/server/src/mcp/tools/conflicts.ts+++ /dev/null@@ -1,166 +0,0 @@-import { ConflictEntrySchema } from '@inkeep/open-knowledge-core';-import { z } from 'zod';-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';-import {- HOCUSPOCUS_NOT_RUNNING_ERROR,- httpGet,- outputSchemaWithText,- ROUTED_CWD_DESCRIPTION,- resolveProjectServerContext,- textPlusStructured,- textResult,-} from './shared.ts';--const DESCRIPTION = [- '[Requires: Hocuspocus server] Read tracked conflicts. Dispatches on `kind`:',- '',- '- `kind: "list"` enumerates every file currently tracked as conflicted. Returns `{ list: [{ file, detectedAt, conflict, reason?, conflictKind?, docName }] }` (empty when none). The entry point to the resolve flow.',- '- `kind: "content"` fetches the three stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, conflict, reason?, conflictKind?, resolutionOptions } }`. `ours` is the live Y.Text when the doc is loaded server-side and marker-free, else the stage pinned when the conflict was detected; for `reason: "stale-external-write"` it is the protected acknowledged content and `theirs` the rejected older save. On a `reconcile` conflict, `resolve_conflict` with `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers. To keep exactly the bytes reviewed here, send them back as `content`. Returns 404 (`urn:ok:error:no-conflict-tracked`) when no conflict is tracked for that `file`; re-read the list before retrying.',- '',- '**Parameters:**',- '- `kind` — `list` | `content`.',- '- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',- '',- "`conflict` names where the conflict came from: `merge-native` (a git merge left unmerged stages), `working-tree` (a pull-only overlay collision pinned to an origin blob), or `reconcile` (OK's own merge of editor and disk, including local stale-save protection); `reason` refines a `reconcile` conflict, and the compatibility `conflictKind` field is `stale-external-write` for that reason and `git` otherwise. `resolutionOptions` lists the strategies that apply to THIS conflict: a `reconcile` conflict whose `theirs` side is raw marker text does not offer `theirs`, and `refused-too-large` offers only `mine`, `theirs`, and `delete`.",- '',- 'The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy.',-].join('\n');--interface ConflictsDeps {- serverUrl: ServerUrlOrResolver;- config: ConfigOrResolver;- resolveCwd: (explicit?: string) => Promise<string>;-}--export function register(server: ServerInstance, deps: ConflictsDeps): void {- server.registerTool(- 'conflicts',- {- description: DESCRIPTION,- inputSchema: {- kind: z- .enum(['list', 'content'])- .describe("`list` enumerates tracked conflicts; `content` fetches one file's stages."),- file: z- .string()- .min(1)- .optional()- .describe(- 'Required when `kind: "content"`. Conflicted file WITH extension (e.g. `notes/sso.md`) — git stages key on the exact path, so keep the extension (DD2).',- ),- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),- },- outputSchema: outputSchemaWithText({- list: z- .array(ConflictEntrySchema)- .optional()- .describe('`kind: "list"` returns every tracked conflict.'),- content: z- .object({- file: z.string().describe('The conflicted file.'),- base: z.string().describe('Merge-base stage content.'),- ours: z.string().describe('Our stage (live Y.Text when loaded server-side).'),- theirs: z.string().describe('Their stage content.'),- shape: z- .enum(['both-modified', 'delete-modify', 'modify-delete'])- .describe('Conflict shape — pick the `resolve_conflict` strategy from it.'),- conflict: z- .enum(['merge-native', 'working-tree', 'reconcile'])- .describe('Where this conflict came from.'),- reason: z.string().optional().describe('Refines a `reconcile` conflict.'),- conflictKind: z- .enum(['git', 'stale-external-write'])- .optional()- .describe('Compatibility classification for Git and protected stale-save conflicts.'),- resolutionOptions: z- .array(z.enum(['mine', 'theirs', 'content', 'delete']))- .describe('The strategies that apply to this conflict.'),- })- .optional()- .describe(- '`kind: "content"` returns the three stages plus shape, conflict kind and options.',- ),- }),- annotations: { readOnlyHint: true, idempotentHint: true },- },- async (args: { kind: 'list' | 'content'; file?: string; cwd?: string }) => {- const context = await resolveProjectServerContext(- deps.resolveCwd,- deps.config,- deps.serverUrl,- args.cwd,- );- if (!context.ok) return textResult(`Error: ${context.error}`, true);- const { url } = context;- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);-- if (args.kind === 'content') {- if (!args.file) {- return textResult(- 'Error: `kind: "content"` requires `file` — the conflicted file WITH extension, e.g. conflicts({ kind: "content", file: "notes/sso.md" }).',- true,- );- }- const query = `?file=${encodeURIComponent(args.file)}&source=ytext`;- const result = await httpGet(url, `/api/sync/conflict-content${query}`);- if (!result.ok) {- const error = result.error as string;- const detail = typeof result.detail === 'string' ? result.detail : undefined;- return textResult(`Error: ${detail ? `${error} — ${detail}` : error}`, true);- }- const rec = result as Record<string, unknown>;- const file = typeof rec.file === 'string' ? rec.file : args.file;- const base = typeof rec.base === 'string' ? rec.base : '';- const ours = typeof rec.ours === 'string' ? rec.ours : '';- const theirs = typeof rec.theirs === 'string' ? rec.theirs : '';- const shape: 'both-modified' | 'delete-modify' | 'modify-delete' =- rec.kind === 'delete-modify' || rec.kind === 'modify-delete' ? rec.kind : 'both-modified';- const conflict: 'merge-native' | 'working-tree' | 'reconcile' =- rec.conflict === 'working-tree' || rec.conflict === 'reconcile'- ? rec.conflict- : 'merge-native';- const reason = typeof rec.reason === 'string' ? rec.reason : undefined;- const conflictKind =- rec.conflictKind === 'stale-external-write' ? 'stale-external-write' : 'git';- const resolutionOptions = Array.isArray(rec.resolutionOptions)- ? (rec.resolutionOptions as Array<'mine' | 'theirs' | 'content' | 'delete'>)- : (['mine', 'theirs', 'content', 'delete'] as const).slice();- const reasonSuffix = reason ? `, reason: ${reason}` : '';- const text = `Conflict stages for ${file} (shape: ${shape}, conflict: ${conflict}${reasonSuffix}; strategies: ${resolutionOptions.join(', ')}):\n--- base ---\n${base}\n--- ours ---\n${ours}\n--- theirs ---\n${theirs}`;- return textPlusStructured(text, {- content: {- file,- base,- ours,- theirs,- shape,- conflict,- ...(reason === undefined ? {} : { reason }),- conflictKind,- resolutionOptions,- },- });- }-- const result = await httpGet(url, '/api/sync/conflicts');- if (!result.ok) {- return textResult(`Error: ${result.error as string}`, true);- }- const rawConflicts = (result as { conflicts?: unknown }).conflicts;- const conflicts = Array.isArray(rawConflicts) ? rawConflicts : [];- const text =- conflicts.length === 0- ? 'No conflicts tracked.'- : `Tracked conflicts (${conflicts.length}):\n${conflicts- .map((row) => {- const rec = (row ?? {}) as Record<string, unknown>;- const file = typeof rec.file === 'string' ? rec.file : '';- const conflict = typeof rec.conflict === 'string' ? rec.conflict : 'merge-native';- const reason = typeof rec.reason === 'string' ? ` / ${rec.reason}` : '';- return `- ${file} (${conflict}${reason})`;- })- .join('\n')}`;- return textPlusStructured(text, { list: conflicts });- },- );-}diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.tsindex a887e0482..be3285a3b 100644--- a/packages/server/src/mcp/tools/delete.ts+++ b/packages/server/src/mcp/tools/delete.ts@@ -28,15 +28,8 @@ import {} from './verb-schemas.ts';const BASE_DESCRIPTION = [- 'Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset`.',- '',- '- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]',- '- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]',- '- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]',- '- `skill` — `{ name }` deletes a whole SKILL; `{ name, files: ["references/x.md"] }` deletes specific bundle files (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]',- '- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',- '',- 'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.',+ "Delete exactly one document, folder, template, skill or asset. Requires the Hocuspocus server. Irreversible; deleting a doc leaves inbound redlinks. Call links({kind:'backlinks',document}) BEFORE deleting.",+ "document: path or paths array; folder: recursive folder path; template: {path:'<folder>/<name>'}; asset: {path:'<folder>/<file.ext>'}. skill: {name} deletes the whole bundle, or {name,files:['references/x.md']} deletes selected files. Template/skill deletion is attributed and cleans empty .ok/ directories.",].join('\n');const DESCRIPTION = BASE_DESCRIPTION;diff --git a/packages/server/src/mcp/tools/description-contract.uncached.test.ts b/packages/server/src/mcp/tools/description-contract.uncached.test.tsnew file mode 100644index 000000000..8e9dd9b30--- /dev/null+++ b/packages/server/src/mcp/tools/description-contract.uncached.test.ts@@ -0,0 +1,280 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ LINT_PLUGIN_IDS,+ OPEN_KNOWLEDGE_MCP_TOOLS,+ VALIDATION_SOURCES,+} from '@inkeep/open-knowledge-core';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import { afterAll, beforeAll, expect, test } from 'vitest';+import { ConfigSchema } from '../../config/schema.ts';+import { installJsonSchemaDialect, JSON_SCHEMA_DIALECT_2020_12 } from '../json-schema-dialect.ts';+import { registerAllTools } from './index.ts';+import { ROUTED_CWD_DESCRIPTION } from './shared.ts';++const client = new Client({ name: 'description-contract', version: '1' });+let tools: Tool[];++beforeAll(async () => {+ const server = new McpServer({ name: 'description-contract', version: '1' });+ registerAllTools(server, {+ config: ConfigSchema.parse({}),+ resolveCwd: async () => process.cwd(),+ });+ installJsonSchemaDialect(server);+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(st), client.connect(ct)]);+ tools = (await client.listTools()).tools;+});++afterAll(async () => client.close());++function assertBudget(listing: Tool[]): void {+ const failures: string[] = [];+ let total = 0;+ for (const tool of listing) {+ const description = tool.description ?? '';+ const normalized = description.normalize('NFKC').length;+ if (normalized > 2048)+ failures.push(`${tool.name}: ${normalized} NFKC description characters exceeds 2048`);+ total += description.length + JSON.stringify(tool.inputSchema).length;+ }+ if (total > 60_000)+ failures.push(+ `tools/list: ${total} raw description + compact inputSchema characters exceeds 60000`,+ );+ if (failures.length) throw new Error(failures.join('\n'));+}++function description(name: string): string {+ const result = tools.find((tool) => tool.name === name)?.description;+ if (!result) throw new Error(`Missing served description for ${name}`);+ return result;+}++function filesUnder(directory: string): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = join(directory, entry.name);+ return entry.isDirectory() ? filesUnder(path) : entry.isFile() ? [path] : [];+ });+}++const retiredToolAdvice =+ /\bresolve_conflict\b|(?<![\w.])conflicts\s*\(|mcp__[\w-]+__(?:conflicts|resolve_conflict)\b|\b(?:call|use|invoke|run)\s+(?:the\s+)?`conflicts`|`conflicts`(?!\s+(?:outcomes?|arms?)\b)/i;++test('the production registration after dialect conversion meets both budgets', () => {+ expect(tools).toHaveLength(19);+ expect(new Set(tools.map((tool) => tool.name))).toEqual(new Set(OPEN_KNOWLEDGE_MCP_TOOLS));+ for (const tool of tools) expect(tool.inputSchema.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);+ assertBudget(tools);+});++test('the per-tool guard measures normalized JavaScript length and names the offender', () => {+ const tool = tools[0];+ if (!tool) throw new Error('Missing tool fixture');+ expect(() => assertBudget([{ ...tool, description: '\uFB03'.repeat(683) }])).toThrow(+ `${tool.name}: 2049 NFKC description characters exceeds 2048`,+ );+});++test('the aggregate guard counts compact schema text and reports the measured total', () => {+ const fixture: Tool = {+ name: 'schema-growth',+ description: '',+ inputSchema: { type: 'object', description: 'x'.repeat(60_000) },+ };+ const measured = JSON.stringify(fixture.inputSchema).length;+ expect(() => assertBudget([fixture])).toThrow(+ `tools/list: ${measured} raw description + compact inputSchema characters exceeds 60000`,+ );+});++test('routed cwd remains transport-qualified while exec keeps its command-directory contract', () => {+ for (const tool of tools.filter((tool) => tool.name !== 'exec')) {+ expect(tool.inputSchema.properties?.cwd, tool.name).toMatchObject({+ description: ROUTED_CWD_DESCRIPTION,+ });+ }+ expect(description('exec')).toContain('cwd: command paths resolve inside explicit absolute cwd');+ expect(description('exec')).toContain('zero/multiple roots');+ expect(description('exec').slice(0, 500)).toContain('STOP');+});++test('validation family and coverage pins survive on the served descriptions', () => {+ const lint = description('lint');+ const audit = description('audit');+ for (const family of LINT_PLUGIN_IDS) expect(lint).toContain(`\`${family}\``);+ for (const family of VALIDATION_SOURCES) expect(audit).toContain(`\`${family}\``);+ for (const text of [lint, audit]) {+ expect(text).toContain('absent from `ran` was not checked');+ expect(text).toContain('project-wide at 10 warnings');+ expect(text).toContain('omittedWarningCount');+ expect(text).not.toContain('scoped to a folder or file to see what was omitted');+ }+ expect(audit).toContain('may still have contributed findings');+ expect(audit).toContain('document and project-tree OKF checks here');+ expect(lint).toContain('Project-tree OKF checks and link validation run only through');+});++test('formerly CI-skipped navigation, validation and summary pins execute against the listing', () => {+ for (const pin of [+ '`backlinks`',+ '`forward`',+ '`dead`',+ '`orphans`',+ '`hubs`',+ '`suggest`',+ 'sourceDocuments',+ 'mode',+ 'limit',+ ])+ expect(description('links')).toContain(pin);+ for (const pin of ['`document`', 'audit', 'severity', '`fix: true`'])+ expect(description('lint')).toContain(pin);+ for (const pin of ['markdownlint', 'broken', '`links`', 'navigation', '`path`'])+ expect(description('audit')).toContain(pin);+ expect(description('checkpoint')).toContain('project-wide');+ expect(description('restore_version')).toContain('version');+ expect(description('restore_version')).toContain('secrets or PII');+ expect(description('config')).toContain('`install`');+ expect(description('config')).not.toMatch(/action:\s*"(link|unlink|add-root)"/);+});++test('share_link retains its path, kind, cwd and publishing preconditions', () => {+ for (const pin of [+ '`path`',+ '`kind`',+ '`cwd`',+ 'auto-probe',+ 'REQUIRED when `path` is empty',+ 'Publishing is a user act',+ ])+ expect(description('share_link')).toContain(pin);+});++test('retired conflict tools are neither registered nor suggested as callable tools', () => {+ expect(tools.map((tool) => tool.name)).not.toContain('conflicts');+ expect(tools.map((tool) => tool.name)).not.toContain('resolve_conflict');+ for (const tool of tools)+ expect(tool.description, tool.name).not.toMatch(/\bconflicts\s*\(|\bresolve_conflict\b/);+});++const adviceRoot = fileURLToPath(new URL('../../../../../', import.meta.url));++function currentAdviceFiles(root: string): string[] {+ const runtime = [+ 'packages/server/src',+ 'packages/cli/src',+ 'packages/app/src',+ 'packages/core/src',+ ].flatMap((path) =>+ filesUnder(join(root, path)).filter(+ (file) => /\.[cm]?tsx?$/.test(file) && !/\.(?:test|test-helper|spec)\.[cm]?tsx?$/.test(file),+ ),+ );+ const guidance = ['packages/server/assets/skills', 'docs/content'].flatMap((path) =>+ filesUnder(join(root, path)).filter((file) => /\.mdx?$/.test(file)),+ );+ return [...runtime, ...guidance];+}++test('retired tool guidance cannot return in runtime strings, bundled skills or published docs', () => {+ for (const file of currentAdviceFiles(adviceRoot))+ expect(readFileSync(file, 'utf8'), relative(adviceRoot, file)).not.toMatch(retiredToolAdvice);+});++test('the advice guard covers every production surface without scanning historical evidence', () => {+ const files = currentAdviceFiles(adviceRoot).map((file) => relative(adviceRoot, file));+ for (const directory of [+ 'packages/server/src/',+ 'packages/cli/src/',+ 'packages/app/src/',+ 'packages/core/src/',+ 'packages/server/assets/skills/',+ 'docs/content/',+ ])+ expect(+ files.some((file) => file.startsWith(directory)),+ directory,+ ).toBe(true);+ expect(files.every((file) => !/\.(?:test|test-helper|spec)\.[cm]?tsx?$/.test(file))).toBe(true);+ expect(files.every((file) => !/^(?:reports|specs|tmp)\//.test(file))).toBe(true);+});++test('retired guidance guard distinguishes tool calls from ordinary conflict and HTTP language', () => {+ for (const text of [+ 'Call conflicts({})',+ 'Use `conflicts` first',+ 'Invoke the `conflicts` tool',+ 'The `conflicts` MCP tool lists pending conflicts',+ 'Available tools: `conflicts`',+ 'Call resolve_conflict after editing',+ 'mcp__open_knowledge__conflicts',+ 'mcp__open_knowledge__resolve_conflict',+ ])+ expect(text).toMatch(retiredToolAdvice);+ for (const text of [+ 'Resolve conflicts in the app',+ 'The `conflicts` outcome leaves pending changes in place',+ 'The `conflicts` arm is counted separately from `merged`',+ 'GET /api/sync/conflicts',+ 'POST /api/sync/resolve-conflict',+ "new Option('--shared').conflicts('localOnly')",+ ])+ expect(text).not.toMatch(retiredToolAdvice);+});++test('published scope guidance preserves selection, error, empty-scope and truncation contracts', () => {+ const root = new URL('../../../../../', import.meta.url);+ const reference = readFileSync(new URL('docs/content/reference/mcp.mdx', root), 'utf8');+ const overview = readFileSync(+ new URL('docs/content/advanced/content-rules/overview.mdx', root),+ 'utf8',+ );+ for (const pin of [+ 'existing file or directory first',+ '`.mdx` before `.md`',+ 'explicitly supplied document extension must exist as written',+ 'unknown scopes exit 1 (before any `--fix` write)',+ 'valid zero-document scopes exit 0',+ 'zero documents checked and an informational warning',+ 'does not lift per-file caps',+ 'Project-tree OKF findings in MCP audit results remain capped',+ ])+ expect(reference).toContain(pin);+ for (const pin of [+ 'existing file or directory as their scope',+ '`.mdx`, then `.md`',+ 'must exist as written',+ 'exits with code 1, before `--fix` can change files',+ 'zero findings, an informational warning, and exit code 0',+ 'RFC 9457 problem response object',+ 'project-tree OKF findings remain capped',+ ])+ expect(overview).toContain(pin);+});++test('skill router and published reference names and counts equal the actual serving surface', () => {+ const skill = readFileSync(+ new URL('../../../assets/skills/project/SKILL.md', import.meta.url),+ 'utf8',+ );+ const reference = readFileSync(+ new URL('../../../../../docs/content/reference/mcp.mdx', import.meta.url),+ 'utf8',+ );+ const router = skill.split('## Tool index')[1]?.split('**Read `ran`')[0];+ expect(router).toBeDefined();+ expect(router).toContain(`${tools.length} tools`);+ const routerNames = [...(router ?? '').matchAll(/^- `([^`]+)` —/gm)].map((match) => match[1]);+ const referenceNames = [...reference.matchAll(/^\| `([^`]+)` \|/gm)].map((match) => match[1]);+ const served = tools.map((tool) => tool.name).sort();+ expect(routerNames.sort()).toEqual(served);+ expect(referenceNames.sort()).toEqual(served);+ expect(reference).toContain(`**${tools.length} tools**`);+ expect(router).not.toMatch(/\bconflicts\s*\(|\bresolve_conflict\b/);+});diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.tsindex 4de0d599c..c544352e6 100644--- a/packages/server/src/mcp/tools/edit.ts+++ b/packages/server/src/mcp/tools/edit.ts@@ -1,7 +1,6 @@import { existsSync, readFileSync } from 'node:fs';import {type FrontmatterPatch,- renderInventoryList,SKILL_AUTHORING_WARNING_CODES,stripFrontmatter,unwrapFrontmatterFences,@@ -27,6 +26,7 @@ import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shimport {AUTHORING_WARNING_CODE_GLOSS,agentIdentityFields,+ CANONICAL_COMPONENT_GUIDANCE,documentResultBaseShape,HOCUSPOCUS_NOT_RUNNING_ERROR,httpPost,@@ -66,20 +66,16 @@ import {TEMPLATE_PATH_DESCRIBE,} from './verb-schemas.ts';-const BASE_DESCRIPTION = [- 'Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, `template`, or `skill`. Within each: a body edit (`find` + `replace`) OR a metadata patch — not both in one call.',- '',- '- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.',- '- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).',- '- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',- "- `skill` — Edit a SKILL: `{ name, ... }`; body `find`/`replace`/`occurrence?` OR a `description` change (a skill's only metadata leaf). Every recorded copy re-syncs from the source, so there is nothing to re-install.",- '- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, `template`, or `skill` edit. Avoid secrets or PII — persisted to git history.',- '',- 'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).',+const DESCRIPTION = [+ 'Edit exactly one `document`, `folder`, `template`, or `skill`: body find/replace OR metadata, never both in one call. Requires the Hocuspocus server.',+ '`document: {path, find, replace, occurrence?}` edits body only; frontmatter-intersecting finds are rejected. occurrence selects a match (1 = first). `{path, frontmatter}` merge-patches metadata; null deletes a key.',+ "`folder: {path, frontmatter}` patches metadata (no body). `template: {path: '<folder>/<name>', ...}` takes body find/replace/occurrence or frontmatter.",+ '`skill: {name, ...}` takes body find/replace/occurrence OR description (its only metadata leaf). Recorded, unedited copies refresh from the source on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.',+ 'Optional summary: one-line outcome ≤80 chars for any edit, persisted to git history; avoid secrets or PII.',+ 'Read structuredContent.document.warnings: content-divergence/disk-edit-reconciled means re-read with exec; mermaid-parse-error means the edit landed but fix the fence and re-edit.',+ CANONICAL_COMPONENT_GUIDANCE,].join('\n');-const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryList()}`;-interface EditDeps {serverUrl: ServerUrlOrResolver;config: ConfigOrResolver;diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.tsindex 3cb5735c2..7d8690735 100644--- a/packages/server/src/mcp/tools/exec.ts+++ b/packages/server/src/mcp/tools/exec.ts@@ -60,23 +60,12 @@ const SOFT_CAP_BYTES =const BINARY_EXT_RE = /\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i;export const DESCRIPTION = [- '**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)',- '',- 'Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).',- '',- '`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.',- '',- 'Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, subshells, writes, and ALL redirection are rejected, `<` too (read via `cat a.md`, not `< a.md`). For several things use separate exec calls or multiple paths (`cat a b c`).',- '',- "cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",- '',- 'Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.',- '',- 'Examples:',- '- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment',- '- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)',- '- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files',- '- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project',+ 'STOP: with `.ok/`, use exec for in-scope .md/.mdx; native Read/Grep/Glob omit wiki context. Native tools are for source code, non-markdown or projects without .ok/. See the open-knowledge skill for the full rule and escape hatch.',+ 'Read-only bash-like command; returns stdout and enrichedPaths with frontmatter, backlinks/forward links, unresolved comments, shadow-repo activity and git history with human/agent attribution. Unresolved comments are open human review requests: consider before editing and report them.',+ 'Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or pipe per call. No &&, ;, subshells, writes or redirection (including <). Use multiple paths or separate calls.',+ "cwd: command paths resolve inside explicit absolute cwd, or the client's sole advertised root. With zero/multiple roots pass cwd; traversal above it is rejected.",+ 'Stdout provenance: ls <dir>/ labels the directory; single-file cat/head/tail labels its path. Multi-file cat has no header; enrichedPaths still lists files. Piped head/tail preserve upstream provenance.',+ "Examples: exec({command:'cat notes/a.md'}); exec({command:'grep -rn oauth notes/ | head -5'}); exec({command:'ls',cwd:'/abs/project'}).",].join('\n');interface ExecDeps {diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.tsindex c2cd9a14b..d2db61475 100644--- a/packages/server/src/mcp/tools/get-preview-url.ts+++ b/packages/server/src/mcp/tools/get-preview-url.ts@@ -29,24 +29,10 @@ import {} from './shared.ts';const DESCRIPTION = [- 'Resolve the browser-reachable preview URL for an OpenKnowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.',- '',- 'Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.',- '',- 'This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Claude Code Desktop opens its in-app Browser pane with `preview_start({url})` then `navigate({url})` to move; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.',- '',- 'If you are running INSIDE an OpenKnowledge surface — the desktop app’s built-in terminal or its in-app agent panel — the response leads with an `ok open …` steer and returns it as `okOpenCommand`. Run that instead: the user is already looking at the app, so a localhost URL in your reply is noise at best and a dead link at worst. Never paste `url` into your answer in that case.',- '',- 'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.',- '',- 'To open a single markdown file that may live OUTSIDE any Open Knowledge project (a loose file, or a doc in a different git worktree), pass `file` with an absolute path: the tool finds the running session whose content directory contains it and returns that session’s URL, then navigate your in-app browser there. `document`/`folder` are for a doc in the current project; `file` is the out-of-project form.',- '',- '**Parameters:**',- '- `document` (optional) — Extension-less doc path in the current project (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',- '- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',- '- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.',- '- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.',- '- `cwd` (optional) — Project root (see `cwd` description below).',+ 'Get the full browser URL for this project or a document/folder/skill, or an absolute markdown file outside the project. Opening is demand: auto-starts OK under the normal OK_MCP_AUTOSTART gate and waits briefly for UI; cold calls can take seconds. Other tools return route-only previewUrl paths; use this tool for an openable URL, never guess ports or hunt via ok ps/status.',+ 'Choose one: document (extension-less), folder (trailing-slash route), skill:{name,scope?} (project default), or file (absolute .md/.mdx in a loose-file/worktree session). file ignores cwd; other targets use current project. Omit targets for UI root.',+ 'When YOUR host opens URLs, navigate its embedded browser to url; Claude Code Desktop uses preview_start({url}) then navigate({url}). Only a stdio host without a browser tool should open the URL in the system browser. A CLI without a browser can use ok open <doc> for OK Desktop. This tool forces browser access even when Desktop is installed.',+ "INSIDE OK's terminal/agent panel, use returned okOpenCommand instead; never paste url in the answer. If no UI is reachable, returns url:null, baseUrl:null, running:false, autoOpen plus state-specific recovery text (autostart disabled, no spawn authority or UI timeout). Follow it.",].join('\n');interface GetPreviewUrlDeps {diff --git a/packages/server/src/mcp/tools/history.ts b/packages/server/src/mcp/tools/history.tsindex 2ec86ce1e..993fd4bf3 100644--- a/packages/server/src/mcp/tools/history.ts+++ b/packages/server/src/mcp/tools/history.ts@@ -39,20 +39,8 @@ const HistoryEntryOutputSchema = z.object({});const DESCRIPTION = [- '[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.',- 'Returns timeline entries from the shadow repo, sorted by timestamp descending.',- 'Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.',- '',- '**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**',- '- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.',- '- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',- "- `skill` — Skill NAME to query version history for (the skill folder's attributed versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.",- '- `branch` (optional) — Branch name (default: current branch)',- '- `limit` (optional) — Maximum entries to return (default 50, max 200)',- '- `offset` (optional) — Number of entries to skip for pagination (default 0)',- '- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',- '- `author` (optional) — Filter to entries by this author name or email',- '- `excludeAuthor` (optional) — Exclude entries by this author name or email',+ 'Read version history: pass exactly one document, folder or skill. Requires the Hocuspocus server. Returns shadow-repo entries newest first; version is a 40-char SHA for restore_version({document,version}) or restore_version({skill,version}).',+ 'document accepts optional .md/.mdx. folder lists attributed template/frontmatter activity; empty string is project root. skill is a project-scope name; global skills are unversioned. Optional branch (current default), limit (50 default, 200 max), offset (0), kind (checkpoint/upstream/wip), author and excludeAuthor (name/email).',].join('\n');export interface GetHistoryDeps {diff --git a/packages/server/src/mcp/tools/import.ts b/packages/server/src/mcp/tools/import.tsindex 3d9ecf7ea..e6cc94fb8 100644--- a/packages/server/src/mcp/tools/import.ts+++ b/packages/server/src/mcp/tools/import.ts@@ -34,16 +34,8 @@ const KNOWN_CODES: ReadonlySet<string> = new Set<string>([]);const DESCRIPTION = [- '[Requires: Hocuspocus server] Import a skill into this project as versioned content.',- '',- 'Fetches an agentskills.io / skills.sh skill-dir from a `source` and writes it into the vendor-neutral `.agents/skills/<name>/` hub — where it gains history, search, attribution, and cross-harness projection (via `install`) for free. Provenance (source, commit, content hash, publisher) is recorded in `.ok/skills-lock.json`. Scripts are imported as content and are NEVER executed. `add` says where it goes — an import always places the skill somewhere, so `install` afterwards is only for changing WHERE it lives (add/remove/convert/source).',- '',- '**Parameters:**',- '- `source` — paste the full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), or pass `owner/repo[/subpath]` (GitHub), a git URL, or a local / `file://` path.',- '- `skill` — Pick ONE skill when the source bundles several.',- '- `scope` — `project` (default, versioned + shared) or `global` (user-global, unversioned).',- '',- 'On a name collision with an existing skill the import lands under `<name>-imported` (never overwrites). An identical re-import (same content hash) is a no-op.',+ 'Import an external agentskills.io/skills.sh skill as managed content. Requires the Hocuspocus server. source accepts a full skills.sh page URL (including website catalogs), owner/repo[/subpath], git URL, or local/file:// path. skill picks one from a multi-skill source. scope: project (default, versioned/shared) or global (user-wide, unversioned).',+ 'Writes the .agents/skills/<name>/ hub with provenance in .ok/skills-lock.json. Scripts are NEVER executed. add selects editor locations; import always places the skill somewhere. Use install later to change placement/form/source. Name collisions use <name>-imported, never overwrite; identical content-hash re-import is a no-op.',].join('\n');interface ImportDeps {@@ -77,7 +69,7 @@ export function register(server: ServerInstance, deps: ImportDeps): void {.enum(['copy', 'link']).optional().describe(- 'The form for the locations in `add`. "link": a symlink to the source. "copy": an independent folder, auto-refreshed until hand-edited. Omit to follow the form the skill already uses.',+ 'The form for the locations in `add`. "link": a symlink to the source. "copy": an independent folder, refreshed on watcher/startup sync while unedited; hand edits fork it. Omit to follow the form the skill already uses.',),scope: SkillScopeArg.optional(),summary: summaryArgSchema,diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.tsindex 7e95f6f23..be6703b41 100644--- a/packages/server/src/mcp/tools/index.ts+++ b/packages/server/src/mcp/tools/index.ts@@ -6,7 +6,6 @@ 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';import { register as registerDelete } from './delete.ts';import { register as registerEdit } from './edit.ts';import { register as registerExec } from './exec.ts';@@ -18,7 +17,6 @@ import { register as registerLinks } from './links.ts';import { register as registerLint } from './lint.ts';import { register as registerMove } from './move.ts';import { register as registerPalette } from './palette.ts';-import { register as registerResolveConflict } from './resolve-conflict.ts';import { register as registerRestoreVersion } from './restore-version.ts';import { register as registerSearch } from './search.ts';import { register as registerShareLink } from './share-link.ts';@@ -172,16 +170,6 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOisHostedAgent: opts.isHostedAgent,...(opts.serverUrl ? { ensureSingleFileSession: createEnsureSingleFileSession() } : {}),});- registerConflicts(registrationServer, {- serverUrl: opts.serverUrl,- config: opts.config,- resolveCwd: named('conflicts'),- });- registerResolveConflict(registrationServer, {- serverUrl: opts.serverUrl,- config: opts.config,- resolveCwd: named('resolve_conflict'),- });registerShareLink(registrationServer, {serverUrl: opts.serverUrl,diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.tsindex 7019acc14..2b227e639 100644--- a/packages/server/src/mcp/tools/install.ts+++ b/packages/server/src/mcp/tools/install.ts@@ -32,25 +32,12 @@ import { resolveSkillName, SKILL_NAME_DESCRIBE, SkillScopeArg } from './verb-schconst KNOWN_INSTALL_CODES: ReadonlySet<string> = new Set(SKILL_INSTALL_WARNING_CODES);const DESCRIPTION = [- '[Requires: Hocuspocus server] Manage WHERE a skill is available. A skill is ONE real folder (its SOURCE — the skill itself) plus managed copies/symlinks at other locations. `add`/`remove` change the other locations; `mode` flips copies↔symlinks; `source` moves the real folder. There is NO "uninstall everywhere" and no draft state — a skill with no extra locations still lives (and loads) at its source folder; to make a skill stop existing, use `delete`.',- '',- 'Location ids: editor host ids (`claude` | `cursor` | `codex` | `copilot` | `opencode` | `pi`), `agents` (the vendor-neutral `.agents/skills` hub), or a base-relative custom root path containing `/` (e.g. `.team/skills`; home-relative at global scope). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never fanned into your agent context).',- '',- '**Parameters:**',- `- \`name\` — ${SKILL_NAME_DESCRIBE}`,- '- `add` — Locations to ADD the skill to (everything else untouched). Editor ids fan out a copy/symlink; a custom root path places the bundle there. Omitting both `add` and `remove` installs into the project-configured editors.',- '- `remove` — Locations to REMOVE it from (lossless only: a hand-edited fork is refused, never deleted). Works however the agent gets the skill: removing an editor that reads it through a folder alias (its skills folder symlinked into a shared root) automatically unfollows that folder from the root MINUS this skill — the editor keeps its other skills. The SOURCE cannot be removed — its folder is the skill; move it with `source` or use `delete`.',- '- `mode` — `"link"`: a live symlink to the source. `"copy"`: an independent folder, auto-refreshed from the source until hand-edited (a hand-edit forks that copy). Applies ONLY to the locations this call names — the ones in `add`, or the ones in `convert` — and sets no skill-wide default. Omit it on `add` and the new location takes the form the skill already uses. Requires `add` or `convert` — passing `mode` alone is refused rather than silently ignored.',- '- `convert` — Existing locations to change the FORM of, leaving membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.',- "- `source` — Move the skill's REAL folder to this location; the old source becomes a symlink to it. Run alone (not with add/remove).",- '- `scope` — `project` (default, shared via git) or `global` (user-level, every project on this machine).',- '',- '- `skillFolders` — Folder-level topology instead of one skill (the Settings → Folders surface). Run alone; `name` is not used with it. One action per call:',- ' - `{ action: "link", scope, root, target }` — merge the skills folder `root` into `target` and replace `root` with a symlink, so its agent reads everything placed in `target`. Same-content entries drop; a DIFFERENT skill in both folders aborts with a conflict list; an interrupted merge is resumable by re-running. `target` is required — nothing is ever assumed.',- ' - `{ action: "unlink", scope, root, exclude? }` — turn a linked folder back into a real directory holding one per-skill symlink per skill it sees (lossless, reversible). `exclude: ["<skill>"]` leaves named skills out — "this agent should not get that skill": the folder keeps everything else but stops following the root.',- ' - `{ action: "add-root", scope, root }` — declare a NEW custom skills root (base-relative, e.g. ".team/skills"); it becomes a folder row and an install/link target immediately.',- '',- 'Copies auto-refresh when the source changes — you do NOT need to re-run install after editing a skill. After `delete({skill})` every location is removed with the source.',+ 'Manage where a SKILL is available: `{name, add?, remove?, convert?, mode?, source?, scope?}` or `{skillFolders: {...}}` alone. Requires the Hocuspocus server. One real source folder plus managed copies/symlinks; the source still loads with no extra locations. Use delete to remove the skill everywhere.',+ "name is the bundle identity: lowercase letters/digits/hyphens, ≤64 chars. Locations: claude/cursor/codex/copilot/opencode/pi, agents (.agents/skills), or custom root containing '/' such as .team/skills. Custom roots are project-relative, home-relative at global scope. scope: project (default, shared via git) or global (user-wide).",+ 'add/remove change membership; omitting both installs to configured editors. remove cannot remove the source; folder aliases unfollow minus this skill and keep others. Differing copies are preserved; editor removal may succeed and leave them in place.',+ 'mode: link = live symlink for source updates; copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.',+ 'source moves the real folder; its old location becomes a symlink. Run alone, not with add/remove. Source SKILL.md with conflict markers, invalid/missing frontmatter, XML in name/description or reserved open-knowledge* names is refused before projection.',+ "skillFolders runs alone without name. link: {action:'link', scope, root, target}; target required, merge then symlink root; equal entries deduplicate, differing skills abort, interrupted merges can rerun. unlink: {action:'unlink', scope, root, exclude?}; makes a real directory of per-skill symlinks, excluding named skills and retaining others. add-root: {action:'add-root', scope, root}; declares a custom root for install/link.",].join('\n');async function runSkillFolderAction(@@ -111,19 +98,19 @@ export function register(server: ServerInstance, deps: InstallDeps): void {.array(SkillLocationIdSchema).optional().describe(- 'Locations to REMOVE the skill from (lossless only; a hand-edited fork is refused). An editor reading via a folder alias is unfollowed from the shared root minus this skill (it keeps the rest). The SOURCE cannot be removed — its folder IS the skill; use `source` to move it or `delete` to remove the skill.',+ 'Locations to REMOVE the skill from; differing copies are preserved and may remain after success. An editor reading via a folder alias is unfollowed from the shared root minus this skill (it keeps the rest). The SOURCE cannot be removed — its folder IS the skill; use `source` to move it or `delete` to remove the skill.',),convert: z.array(SkillLocationIdSchema).optional().describe(- 'Existing locations to change the FORM of, leaving their membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.',+ 'Existing locations to change the FORM of, leaving their membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a differing copy is refused rather than overwritten.',),mode: z.enum(['copy', 'link']).optional().describe(- 'The form for the locations THIS call touches — the ones in `add`, or the ones in `convert`. "link": a pointer to the source, so nothing can drift. "copy": an independent folder, auto-refreshed from the source until hand-edited. Omit on `add` to follow the form the skill already uses. This does not change locations the call does not name, and sets no skill-wide default. Requires `add` or `convert` — passing `mode` alone is refused rather than silently ignored.',+ 'Form for locations in `add` or `convert`. "link": live pointer to the source. "copy": independent folder, refreshed on watcher/startup sync while unedited; a hand edit forks it. Omit on `add` to inherit the existing form. Other locations stay unchanged; no skill-wide default. Requires `add` or `convert`; `mode` alone is refused.',),source: SkillLocationIdSchema.optional().describe("Move the skill's REAL folder to this location (the old source becomes a symlink — never a removal). Run alone, not combined with add/remove.",diff --git a/packages/server/src/mcp/tools/links.ts b/packages/server/src/mcp/tools/links.tsindex 75f0f56fa..e0fb56add 100644--- a/packages/server/src/mcp/tools/links.ts+++ b/packages/server/src/mcp/tools/links.ts@@ -21,12 +21,10 @@ const LINK_KINDS = ['backlinks', 'forward', 'dead', 'orphans', 'hubs', 'suggest'type LinkKind = (typeof LINK_KINDS)[number];export const DESCRIPTION = [- '[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.',- '',- '- `backlinks` / `forward` / `suggest` — operate on one page; require `document`. `suggest` finds prose mentions of the page not yet wrapped in link syntax. Each mention returns an `excerpt` (a normalized, `…`-trimmed snippet for context — NOT an edit-ready literal) plus an `offset`. To wrap one: re-read the doc (`exec("cat …")`), find the real mention text, and `edit` it into a `[[wiki-link]]`.',- "- `dead` — missing internal link targets corpus-wide; optional `sourceDocuments` filter (OR semantics). This is the raw graph read: unlike `audit`, it still lists unresolved links whose source is a skill document or a lowercase-stemmed `log.md`/`log.mdx` — read those to audit deliberately, never as a repair queue, and never rewrite a log's existing entries to clear one.",- '- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.',- '- `hubs` — most-linked pages; optional `limit` (default 20).',+ 'Read the wiki-link graph. Requires the Hocuspocus server. kind is one value or an array; results merge, failures go in errors. Use audit for validation.',+ '`backlinks`/`forward`/`suggest` require document. suggest finds unlinked prose mentions; excerpt is normalized context, NOT edit-ready text. Re-read with exec, locate the real text using offset, then edit into a wiki-link.',+ '`dead` lists raw unresolved internal targets; sourceDocuments optionally filters with OR semantics. Includes skill docs and lowercase log.md/log.mdx: inspect deliberately, never use as a repair queue or rewrite existing log entries to clear findings.',+ '`orphans` finds disconnected pages; mode incoming/outgoing/both. `hubs` lists most-linked pages; limit defaults 20.',].join('\n');interface BacklinksPayload {diff --git a/packages/server/src/mcp/tools/lint.test.ts b/packages/server/src/mcp/tools/lint.test.tsindex 76b139dbf..07578f30d 100644--- a/packages/server/src/mcp/tools/lint.test.ts+++ b/packages/server/src/mcp/tools/lint.test.ts@@ -333,7 +333,10 @@ describe('lint — audit output cap', () => {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('lint({ document: "doc-00.md" })');+ expect(text).toContain('all document lint findings');expect(text).toContain('… and 2 more files with problems');+ expect(text).toContain('Narrow path to reduce competing files; per-file caps still apply');const shownFileHeaders = text.match(/^doc-\d+\.md:$/gm) ?? [];expect(shownFileHeaders).toHaveLength(AUDIT_FILE_CAP);});diff --git a/packages/server/src/mcp/tools/lint.ts b/packages/server/src/mcp/tools/lint.tsindex 0c3bcacb5..01ae3f725 100644--- a/packages/server/src/mcp/tools/lint.ts+++ b/packages/server/src/mcp/tools/lint.ts@@ -28,19 +28,14 @@ import {resolveProjectServerContext,textPlusStructured,textResult,+ zeroFindingsSummary,} from './shared.ts';export const DESCRIPTION = [- '[Requires: Hocuspocus server] Lint markdown documents and report problems (rule violations); optionally auto-fix them.',- '',- '- `document` given → lint just that doc (extension-less path); `path` is ignored.',- '- `document` omitted → audit every in-scope `.md`/`.mdx` doc; pass `path` to scope to a folder or single file.',- '- `fix: true` (requires `document`) → apply auto-fixable rules to that doc IN PLACE and report what remains.',- '- The result reports `ran`, the enabled document-lint source families selected for the run: `markdownlint`, `frontmatter`, and/or document-level `okf`. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through `audit`.',- '',- "Each violation carries a `source` (the plugin, e.g. markdownlint), a `code` (the engine's native rule id, e.g. MD010), `message`, a 0-based LSP `range`, and `severity` ('error' | 'warning' | 'info' | 'hint'). The audit lists only files that have at least one violation, plus `fileCount`/`errorCount`/`warningCount`. Audit output (text and structured) is capped at 10 files × 10 diagnostics per file and project-wide at 10 warnings, with explicit '… and N more' indicators and `omittedWarningCount` when warnings are dropped; the counts always reflect the full scan — re-run with `path` scoped to a folder or file to see what was omitted. Lint rules are configured in Settings → Plugins (the toggle is committed to `config.yml`; the rules live in the project's native `.markdownlint.*` file).",- '',- 'To auto-fix, pass `fix: true` with `document`: the fix lands through the collaborative document — attributed to you and reflected in the live preview, same as the editor. It fixes auto-fixable rules (e.g. hard tabs, trailing spaces); violations that resist auto-fix need content edits via the `edit`/`write` tools. (`ok lint --fix` from a shell remains the headless/CI path, but it writes on disk unattributed — prefer `fix: true` when the server is running.)',+ 'Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; shell ok lint --fix is the unattributed headless/CI path.',+ 'ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.',+ 'Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.',+ 'Configure lint in Settings → Plugins and native .markdownlint.* rules.',].join('\n');export const LINT_WARNINGS_DESCRIPTION =@@ -351,7 +346,7 @@ async function lintAudit(path: string | undefined, url: string, cwd: string) {const fileCount = data.fileCount ?? 0;const errorCount = data.errorCount ?? 0;const warningCount = data.warningCount ?? 0;- const coverageLines = validationCoverageLines(data.ran);+ const coverageLines = validationCoverageLines(data.ran, fileCount);const shownFiles = files.slice(0, AUDIT_FILE_CAP).map((file) => {const diagnostics = file.diagnostics ?? [];@@ -383,10 +378,7 @@ async function lintAudit(path: string | undefined, url: string, cwd: string) {const scope = path ? ` in ${path}` : '';const warningBlock = degradationBlock('Lint', shownWarnings, omittedWarningCount);if (files.length === 0) {- const summary =- warnings.length > 0- ? `No problems found across ${fileCount} document${fileCount === 1 ? '' : 's'}${scope}, but the lint could not fully complete.`- : `No problems across ${fileCount} document${fileCount === 1 ? '' : 's'}${scope}.`;+ const summary = zeroFindingsSummary('Lint', fileCount, warnings, scope);return textPlusStructured([summary, ...coverageLines, ...warningBlock].join('\n'), structured);}const header = `${files.length} of ${fileCount} document${fileCount === 1 ? '' : 's'}${scope} with problems — ${countSummary(errorCount, warningCount)}:`;@@ -394,14 +386,16 @@ async function lintAudit(path: string | undefined, url: string, cwd: string) {const lines = file.diagnostics.map(formatDiagnosticLine);if (file.omittedDiagnosticCount !== undefined) {lines.push(- ` … and ${file.omittedDiagnosticCount} more problem${file.omittedDiagnosticCount === 1 ? '' : 's'}`,+ ` … and ${file.omittedDiagnosticCount} more problem${file.omittedDiagnosticCount === 1 ? '' : 's'}; use lint({ document: ${JSON.stringify(file.file)} }) for all document lint findings.`,);}return [`${file.file ?? '(unknown)'}:`, ...lines].join('\n');});const footer =omittedFileCount > 0- ? [`… and ${omittedFileCount} more file${omittedFileCount === 1 ? '' : 's'} with problems`]+ ? [+ `… and ${omittedFileCount} more file${omittedFileCount === 1 ? '' : 's'} with problems. Narrow path to reduce competing files; per-file caps still apply.`,+ ]: [];return textPlusStructured([header, ...fileBlocks, ...footer, ...warningBlock, AUDIT_FIX_HINT, ...coverageLines].join(diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.tsindex 725a92ef0..2823cb3c7 100644--- a/packages/server/src/mcp/tools/move.ts+++ b/packages/server/src/mcp/tools/move.ts@@ -40,16 +40,14 @@ export const DROPPED_LOCATIONS_DESCRIPTION ='Skill cross-level move only: locations the skill occupied at the source that the move did not automatically re-project at the destination — the `agents` hub, custom roots, and any editor with no skills root at that level — as `install` location ids. On a SUCCESS they were removed at the source and not re-created at the destination, and the ones the destination level can place (the `agents` hub and custom roots) go back with `install` as `add`, together with `scope` set to the DESTINATION level; an editor with no skills root there cannot be placed at all — `install` accepts its id and projects nothing, so the move\'s own success text names the equivalent (an editor that reads the `agents` hub at that level takes `add: ["agents"]` instead) or states that no destination-level placement exists. Custom roots resolve against that level\'s base — your home directory at the Global level, the project directory at the Project level — not wherever the root lived before the move. On a FAILURE this is instead the set of source-side placements this call had already removed, and whether the skill moved is what `moveState` says: on `nothing-written`, `destination-removed`, `destination-stray` and the two retained states the source is still there, so do not pass these to `install` at the DESTINATION level — re-add them at the SOURCE level, and retry the move only once that state is resolved. On `destination-unreadable` and `partially-applied` the source removal may already have run, so inspect both locations before re-adding anywhere.';const DESCRIPTION = [- '[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.',- '',- '**Parameters:**',- '- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.',- '- `to` — New path. Same shape as `from`.',- '- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.',- `- \`skill\` — Move/rename a SKILL: \`{ from: "<name>", to: "<name>", scope?, toScope? }\` (nested). Within one level (omit \`toScope\`, or \`toScope\` === \`scope\`): renames the skill folder and keeps the SKILL.md \`name\` in sync. ACROSS levels (\`toScope\` differs from \`scope\`): moves the skill between the Project level (this KB) and the Global level (your user home); ${CROSS_LEVEL_TRANSFER_CLAUSE} Mutually exclusive with flat \`from\`/\`to\`.`,- '- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',- '',- `**Errors:** 400 — invalid path / excluded by \`.gitignore\`/\`.okignore\`; 404 — source does not exist; 409 — destination already exists (\`colliding[]\` returned); 500 — a cross-level skill move can leave partial state (source, destination, or both), so it is not a safe blind retry. Every cross-level skill-move failure this handler reports carries a \`moveState\` code whatever its status, and the two refusals that turn on a retained destination copy arrive as 409, not 500 — \`destination-retained-blocking\`, and the \`nothing-written\` collision that carries a \`retentionLedger\` — so read \`moveState\` before retrying regardless of status. The one exception is a response whose \`moveState\`/\`sourceState\`/\`retentionLedger\` triple this build cannot recognise as consistent: all three are withheld and the text says so instead — "The server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination."`,+ 'For .md/.mdx inspection before or after a move in a project with .ok/, use exec; native Read/Grep/Glob omit wiki context.',+ 'Move/rename a document, folder or asset with `{from, to}`, a template with `{template: {from, to}}`, or a skill with `{skill: {from, to, scope?, toScope?}}`. Choose one form. Requires the Hocuspocus server. Document/folder/asset kind is auto-detected.',+ "Paths: docs accept optional .md/.mdx; folders are relative with no leading/trailing slash; assets include the extension. Templates use '<folder>/<name>'; inherited templates cannot move (move their local copy or owning folder). Template moves rewrite no inbound links.",+ 'Links to the moved document keep pointing to it. The old path stops existing; do not leave a redirect or stub.',+ 'Managed moves preserve wiki-link targets and rewrite supported inline Markdown links; renamed assets are reported.',+ 'Skills: scope defaults project; global means your home. Within one scope, rename keeps SKILL.md name in sync. A differing toScope moves between project/global: history does not transfer; supported editor locations are re-projected. Other locations are dropped; on SUCCESS only, use droppedLocations and the response to reinstall at the destination.',+ 'Cross-scope failures can leave partial state. Before retrying or reinstalling, read moveState and recovery text regardless of status. Never remove either copy without comparing source/destination when the outcome is missing or inconsistent.',+ 'Optional summary: one-line outcome ≤80 chars. If omitted, defaults to "Renamed X → Y". Avoid secrets or PII; persisted to git history. Invalid/excluded paths, missing sources and existing destinations are refused; collisions report colliding[].',].join('\n');interface RenameMapping {@@ -158,7 +156,9 @@ export function register(server: ServerInstance, deps: MoveDeps): void {to: z.string().optional()- .describe('New path. All inbound wiki-links + inline links are rewritten automatically.'),+ .describe(+ 'New path. Links keep their intended targets; supported inline links are rewritten.',+ ),template: z.object({ from: z.string(), to: z.string() }).optional()diff --git a/packages/server/src/mcp/tools/mutation-descriptions.test.ts b/packages/server/src/mcp/tools/mutation-descriptions.test.tsnew file mode 100644index 000000000..b8bec2065--- /dev/null+++ b/packages/server/src/mcp/tools/mutation-descriptions.test.ts@@ -0,0 +1,174 @@+import { getAgentCanonicalDescriptors } from '@inkeep/open-knowledge-core';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { afterAll, beforeAll, expect, test } from 'vitest';+import { ConfigSchema } from '../../config/schema.ts';+import { installJsonSchemaDialect } from '../json-schema-dialect.ts';+import { register as registerEdit } from './edit.ts';+import { register as registerInstall } from './install.ts';+import { register as registerMove } from './move.ts';+import { register as registerPalette } from './palette.ts';+import { register as registerRestoreVersion } from './restore-version.ts';+import { register as registerWrite } from './write.ts';++const names = ['write', 'edit', 'move', 'install', 'restore_version'];+const client = new Client({ name: 'mutation-contract-test', version: '1' });+let tools: Awaited<ReturnType<Client['listTools']>>['tools'];++beforeAll(async () => {+ const server = new McpServer({ name: 'mutation-contract-test', version: '1' });+ const deps = {+ config: ConfigSchema.parse({ content: { dir: '.' } }),+ resolveCwd: async () => process.cwd(),+ serverUrl: '',+ };+ for (const register of [+ registerWrite,+ registerEdit,+ registerMove,+ registerInstall,+ registerPalette,+ registerRestoreVersion,+ ]) {+ register(server, deps);+ }+ installJsonSchemaDialect(server);+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);+ tools = (await client.listTools()).tools;+});++afterAll(async () => client.close());++function description(name: string): string {+ const tool = tools.find((item) => item.name === name);+ if (!tool?.description) throw new Error(`Missing served description for ${name}`);+ return tool.description;+}++test.each(names)(+ '%s serves its complete contract within the normalized description limit',+ (name) => {+ expect(description(name).normalize('NFKC').length, name).toBeLessThanOrEqual(2048);+ },+);++test.each(names)('%s preserves the transport-qualified cwd parameter', (name) => {+ const schema = tools.find((item) => item.name === name)?.inputSchema;+ expect(schema?.properties?.cwd).toMatchObject({+ description:+ 'Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.',+ });+});++test.each(['write', 'edit', 'move'])(+ '%s keeps persisted-summary privacy visible before action',+ (name) => {+ expect(description(name)).toContain('secrets or PII');+ expect(description(name)).toContain('≤80 chars');+ expect(description(name)).toContain('git history');+ },+);++test('move keeps its identity promise and default summary in the actual listing', () => {+ expect(description('move')).toMatch(+ /^For \.md\/\.mdx inspection before or after a move in a project with \.ok\/, use exec; native Read\/Grep\/Glob omit wiki context\./,+ );+ expect(description('move')).toContain(+ 'Links to the moved document keep pointing to it. The old path stops existing; do not leave a redirect or stub.',+ );+ expect(description('move')).toContain('If omitted');+ expect(description('move')).toContain('Renamed X → Y');+ expect(description('move')).toContain('moveState');+ expect(description('move')).toContain('on SUCCESS only');+});++test('write retains critical guidance even if a client strips parameter descriptions', () => {+ const text = description('write');+ for (const pin of [+ 'Nested paths such as `guides/overview` can be documents',+ 'Use `folder` only for separate pages',+ 'content and template are exclusive',+ 'Existing docs require position',+ 'frontmatter with literal content forces replace, even with append/prepend',+ 'append/prepend/edit bypass this refusal',+ 'Peers are per MCP connection',+ 'top-level is ignored',+ 'base64 content or local source path',+ ]) {+ expect(text).toContain(pin);+ }+});++test.each(['write', 'edit'])(+ '%s serves every canonical id and a reachable palette lookup',+ async (name) => {+ const text = description(name);+ const ids = getAgentCanonicalDescriptors().map((descriptor) => descriptor.name);+ const inventory = text.split('\n').find((line) => line.startsWith('Canonical ids:'));+ expect(inventory).toBeDefined();+ expect(inventory?.match(/^Canonical ids: ([^.]+)\./)?.[1].split(', ')).toEqual(ids);+ expect(inventory).not.toContain('MermaidFence');+ expect(inventory).toContain('palette({components:[ids]})');+ expect(inventory).toContain('Other JSX stays raw MDX when no canonical fits');+ const result = await client.callTool({ name: 'palette', arguments: { components: ids } });+ expect(result.isError).not.toBe(true);+ expect(result.structuredContent).toMatchObject({+ componentDetails: ids.map((id) =>+ expect.objectContaining({ id, description: expect.any(String), params: expect.any(Array) }),+ ),+ notFound: [],+ components: expect.arrayContaining([+ expect.objectContaining({ id: 'Callout', example: expect.stringContaining('> [!NOTE]') }),+ expect.objectContaining({ id: 'Mermaid', example: expect.stringContaining('```mermaid') }),+ ]),+ embedPatterns: expect.arrayContaining([+ expect.objectContaining({ snippet: expect.stringContaining('```html preview') }),+ ]),+ tokens: expect.arrayContaining([expect.objectContaining({ name: '--chart-1' })]),+ });+ },+);++test('install teaches copy refresh and divergence behavior before parameter descriptions are stripped', () => {+ const text = description('install');+ for (const pin of [+ 'link = live symlink for source updates',+ 'copy = separate folder, refreshed on watcher/startup sync while unedited',+ 'Hand-edited copies fork; differing copies are preserved and cannot be converted',+ 'editor removal may succeed and leave them in place',+ ]) {+ expect(text).toContain(pin);+ }+ const schema = tools.find((item) => item.name === 'install')?.inputSchema;+ expect(schema?.properties?.mode).toMatchObject({+ description: expect.stringContaining('refreshed on watcher/startup sync while unedited'),+ });+ expect(schema?.properties?.remove).toMatchObject({+ description: expect.stringContaining(+ 'differing copies are preserved and may remain after success',+ ),+ });+ expect(schema?.properties?.convert).toMatchObject({+ description: expect.stringContaining('a differing copy is refused'),+ });+ expect(JSON.stringify({ description: text, inputSchema: schema })).not.toMatch(+ /not refreshed after source edits|Hand-edited forks are refused/,+ );+});++test.each(['edit', 'restore_version'])('%s keeps skill copy expectations accurate', (name) => {+ expect(description(name)).toContain('unedited copies refresh');+ expect(description(name)).toContain('watcher/startup sync');+ expect(description(name)).toContain('Hand-edited copies are preserved');+});++test('install describes preserved differing copies without attributing an edit to the copy', () => {+ const schema = tools.find((item) => item.name === 'install')?.outputSchema;+ expect(schema?.properties?.warningCodes).toMatchObject({+ description: expect.stringContaining(+ '`place-fork-refused`: a copy differing from the current source was left alone rather than deleted.',+ ),+ });+});diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.tsindex d600b3ca5..bdc0b28b5 100644--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts@@ -1,7 +1,10 @@import { mkdirSync, mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { RE_LINT_FAILED_WARNING_PREFIX } from '@inkeep/open-knowledge-core';+import {+ AUDIT_EMPTY_SCOPE_WARNING,+ RE_LINT_FAILED_WARNING_PREFIX,+} from '@inkeep/open-knowledge-core';import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';@@ -138,7 +141,6 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no'palette','config','preview_url',- 'resolve_conflict','search','share_link','history',@@ -146,7 +148,6 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no'restore_version','delete','move',- 'conflicts','exec','edit','write',@@ -274,6 +275,92 @@ describe('audit and lint emitted coverage validates against the client schema',});}+ test.each([+ { name: 'audit', register: registerAudit },+ { name: 'lint', register: registerLint },+ ])('$name keeps empty-scope information distinct from degradation', async ({ register }) => {+ const cwd = newProject();+ const captured = captureRegistration(register, {+ config: BASE_CONFIG,+ resolveCwd: async () => cwd,+ serverUrl: 'http://127.0.0.1:31337',+ });+ const unknownWarning = 'No documents were checked: source could not be read.';+ for (const warnings of [+ [AUDIT_EMPTY_SCOPE_WARNING],+ [AUDIT_EMPTY_SCOPE_WARNING, unknownWarning],+ ]) {+ const payload = {+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings,+ ran: ['markdownlint'],+ };+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => Response.json(payload)),+ );+ const result = await captured.handler({ path: 'empty' });+ expect(result.structuredContent).toMatchObject(payload);+ const text = result.content[0]?.text ?? '';+ expect(text).toContain(+ 'No documents were checked in empty; this scope contains no admitted documents.',+ );+ expect(text).toContain('Checks selected: markdownlint; no document checks ran.');+ expect(text).not.toContain('No problems');+ if (warnings.length === 1) expect(text).not.toContain('incomplete');+ else {+ expect(text).toContain('incomplete — 1 warning');+ expect(text).toContain(unknownWarning);+ }+ const validate = new AjvJsonSchemaValidator().getValidator(+ compileOutputSchemaForClient(captured.cfg.outputSchema),+ );+ const validation = validate(result.structuredContent) as {+ valid: boolean;+ errorMessage?: string;+ };+ expect(validation.valid, validation.errorMessage).toBe(true);+ }+ });++ test.each([+ { name: 'audit', register: registerAudit },+ { name: 'lint', register: registerLint },+ ])(+ '$name reports a refused zero-document scope as incomplete, not empty',+ async ({ name, register }) => {+ const cwd = newProject();+ const captured = captureRegistration(register, {+ config: BASE_CONFIG,+ resolveCwd: async () => cwd,+ serverUrl: 'http://127.0.0.1:31337',+ });+ const refused = 'refusing audit scope under a hidden path segment: .ok';+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () =>+ Response.json({+ files: [],+ fileCount: 0,+ errorCount: 0,+ warningCount: 0,+ warnings: [refused],+ ran: ['markdownlint'],+ }),+ ),+ );+ const text = (await captured.handler({ path: 'private' })).content[0]?.text ?? '';+ expect(text).toContain(+ `No problems found across 0 documents in private, but the ${name} could not fully complete.`,+ );+ expect(text).toContain(` ⚠ ${refused}`);+ expect(text).not.toContain('No documents were checked');+ },+ );+test('audit text distinguishes clean, findings, empty selection, and degradation', async () => {const captured = captureRegistration(registerAudit, {config: BASE_CONFIG,diff --git a/packages/server/src/mcp/tools/palette.ts b/packages/server/src/mcp/tools/palette.tsindex 57dcb34aa..e14233399 100644--- a/packages/server/src/mcp/tools/palette.ts+++ b/packages/server/src/mcp/tools/palette.ts@@ -11,22 +11,10 @@ import type { ConfigOrResolver, ServerInstance } from './shared.ts';import { outputSchemaWithText, ROUTED_CWD_DESCRIPTION, textPlusStructured } from './shared.ts';const DESCRIPTION = [- '[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.',- '',- 'Three sections:',- '- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.',- '- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.',- '- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed. **Inside SVG, route theme tokens through `style="..."` rather than presentation attributes** — `<circle style="fill: var(--chart-1)">` works; `<circle fill="var(--chart-1)">` silently falls back to black in Safari / older Chromium because CSS `var()` is not a valid SVG `<paint>` value per the W3C spec.',- '',- '**These delimiters are live syntax in ordinary prose, not just inside the constructs above:** `==highlight==`, `$inline math$` / `$$block math$$`, `%%comment%%` and `<!-- comment -->` (both hidden from readers), `~~strikethrough~~`. An accidental pair silently formats — or, for the comment forms, HIDES — the text between it. To keep a pair literal, either wrap it in an inline code span (`` `==x==` ``, `` `$5` ``), which always works and reads as code, or backslash-escape either delimiter (`\\==x\\==`, `\\$5`, `\\%\\%note\\%\\%`, `\\<!-- note -->`) to keep it as running prose. `~~` is the exception: escape both tildes (`\\~\\~x\\~\\~`), because a one-sided `\\~~x~~` renders right but gets rewritten to the two-sided form on save.',- '',- 'External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.',- '',- 'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',- '',- '**Parameters:**',- '- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.',- '- `cwd` (optional) — Project root (see `cwd` description below).',+ 'Read the authoring palette: markdown-native components/examples/guidance, themed html preview embedPatterns (charts, stat cards, SVG, interactive controls), and CSS tokens. No running OK server needed. Optional components:[ids] adds full JSX props in componentDetails plus notFound; ids are case-sensitive, max 32. cwd selects project.',+ 'Prefer native forms: > [!NOTE], <details>, mermaid fences, $math$. For interactive HTML/JS/CSS use html preview starters and var(--chart-1)/var(--foreground) tokens for light/dark themes. Inside SVG use style="fill: var(--chart-1)", not a fill presentation attribute.',+ 'Delimiters are live even in ordinary prose: ==highlight==, $inline math$/$$block math$$, %%comment%% and <!-- comment --> (HIDES text), ~~strikethrough~~. Keep literal pairs in an inline code span or backslash-escape either delimiter. For ~~ escape BOTH tildes on both sides; one-sided escaping is rewritten on save.',+ 'Preview iframes have open network access for external HTTPS resources/fetch/fonts/maps. They are sandboxed null-origin frames and cannot access the knowledge base, cookies or auth.',].join('\n');interface GetAuthoringPaletteDeps {diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.tsindex 2c10d677a..a80dac901 100644--- a/packages/server/src/mcp/tools/registry.test.ts+++ b/packages/server/src/mcp/tools/registry.test.ts@@ -12,6 +12,8 @@ const BASE_CONFIG: Config = ConfigSchema.parse({});const EXPECTED_TOOLS = OPEN_KNOWLEDGE_MCP_TOOLS;const RETIRED_TOOL_NAMES = [+ 'conflicts',+ 'resolve_conflict','graph_view','get_backlinks','get_forward_links',@@ -112,8 +114,6 @@ const OK_AUTO_APPROVED_TOOLS = ['edit','checkpoint','restore_version',- 'conflicts',- 'resolve_conflict','lint','audit',] as const;diff --git a/packages/server/src/mcp/tools/resolve-conflict.test.ts b/packages/server/src/mcp/tools/resolve-conflict.test.tsdeleted file mode 100644index 1654db913..000000000--- a/packages/server/src/mcp/tools/resolve-conflict.test.ts+++ /dev/null@@ -1,247 +0,0 @@-import { mkdtemp, rm } from 'node:fs/promises';-import { tmpdir } from 'node:os';-import { resolve } from 'node:path';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';-import { type Config, ConfigSchema } from '../../config/schema.ts';-import { register } from './resolve-conflict.ts';-import { HOCUSPOCUS_NOT_RUNNING_ERROR, type ServerInstance } from './shared.ts';--interface ToolResult {- content: Array<{ type: 'text'; text: string }>;- structuredContent?: Record<string, unknown>;- isError?: boolean;-}--interface RegisteredTool {- name: string;- config: {- description?: string;- annotations?: {- readOnlyHint?: boolean;- idempotentHint?: boolean;- destructiveHint?: boolean;- };- };- handler: (args: Record<string, unknown>) => Promise<ToolResult>;-}--function createCapturingServer() {- const registrations: RegisteredTool[] = [];- const server = {- registerTool(- name: string,- config: RegisteredTool['config'],- handler: RegisteredTool['handler'],- ) {- registrations.push({ name, config, handler });- },- } as unknown as ServerInstance;- return { server, registrations };-}--function getTool(registrations: RegisteredTool[], name: string): RegisteredTool {- const tool = registrations.find((r) => r.name === name);- expect(tool).toBeDefined();- return tool as RegisteredTool;-}--const originalFetch = globalThis.fetch;-let tmpDir: string;-const BASE_CONFIG: Config = ConfigSchema.parse({});--beforeEach(async () => {- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-resolve-conflict-'));-});--afterEach(async () => {- globalThis.fetch = originalFetch;- await rm(tmpDir, { recursive: true, force: true });-});--function makeDeps(serverUrl: string | undefined) {- return {- serverUrl,- config: BASE_CONFIG,- resolveCwd: async () => tmpDir,- };-}--describe('resolve_conflict MCP tool', () => {- test('declares destructiveHint: true + idempotentHint: false annotations (D11)', () => {- const { server, registrations } = createCapturingServer();- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');-- expect(tool.config.annotations).toMatchObject({- destructiveHint: true,- idempotentHint: false,- });- });-- test('description warns about the D10 best-effort non-atomic contract', () => {- const { server, registrations } = createCapturingServer();- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');-- expect(tool.config.description).toContain('conflicts({ kind: "list" })');- expect(tool.config.description).toContain('best-effort');- expect(tool.config.description).toContain('non-atomic');- expect(tool.config.description).toContain('DESTRUCTIVE');- });-- test('description names both refusals that share the 422 and the field telling them apart', () => {- const { server, registrations } = createCapturingServer();- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');-- expect(tool.config.description).toContain('urn:ok:error:unresolved-conflict-markers');- expect(tool.config.description).toContain('`refusal`');- expect(tool.config.description).toContain('markers-in-content');- expect(tool.config.description).toContain('strategy-not-offered');- expect(tool.config.description).toContain('resolutionOptions');- });-- test('strategy=theirs posts a body without content', async () => {- const { server, registrations } = createCapturingServer();- const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];- globalThis.fetch = (async (input, init) => {- fetchCalls.push({ input, init });- return new Response(JSON.stringify({ ok: true }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- });- }) as typeof fetch;-- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- const result = await tool.handler({ file: 'notes/a.md', strategy: 'theirs' });-- expect(fetchCalls).toHaveLength(1);- expect(fetchCalls[0]?.input).toBe('http://localhost:4321/api/sync/resolve-conflict');- expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({- file: 'notes/a.md',- strategy: 'theirs',- });- expect(result.isError).toBeUndefined();- expect(result.structuredContent).toMatchObject({ ok: true, file: 'notes/a.md' });- expect(result.content[0]?.text).toContain('theirs');- });-- test('strategy=mine posts a body without content', async () => {- const { server, registrations } = createCapturingServer();- const fetchCalls: Array<{ init?: RequestInit }> = [];- globalThis.fetch = (async (_input, init) => {- fetchCalls.push({ init });- return new Response(JSON.stringify({ ok: true }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- });- }) as typeof fetch;-- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- const result = await tool.handler({ file: 'a.md', strategy: 'mine' });-- expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({- file: 'a.md',- strategy: 'mine',- });- expect(result.isError).toBeUndefined();- });-- test.each(['merged-by-hand', ''])('strategy=content forwards exact bytes %j', async (content) => {- const { server, registrations } = createCapturingServer();- const fetchCalls: Array<{ init?: RequestInit }> = [];- globalThis.fetch = (async (_input, init) => {- fetchCalls.push({ init });- return new Response(JSON.stringify({ ok: true }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- });- }) as typeof fetch;-- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- const result = await tool.handler({- file: 'a.md',- strategy: 'content',- content,- });-- expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({- file: 'a.md',- strategy: 'content',- content,- });- expect(result.isError).toBeUndefined();- });-- test('commit failure (500) surfaces as structured error to the agent', async () => {- const { server, registrations } = createCapturingServer();- globalThis.fetch = (async () =>- new Response(- JSON.stringify({- type: 'urn:ok:error:internal-server-error',- title: 'Failed to resolve conflict.',- status: 500,- }),- { status: 500, headers: { 'Content-Type': 'application/problem+json' } },- )) as typeof fetch;-- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- const result = await tool.handler({ file: 'a.md', strategy: 'theirs' });-- expect(result.isError).toBe(true);- expect(result.content[0]?.text).toContain('Failed to resolve conflict');- expect(result.structuredContent).toMatchObject({ ok: false, file: 'a.md' });- });-- test('uses the shared Hocuspocus-not-running error when no server URL is available', async () => {- const { server, registrations } = createCapturingServer();- register(server, makeDeps(undefined));- const tool = getTool(registrations, 'resolve_conflict');- const result = await tool.handler({ file: 'a.md', strategy: 'theirs' });-- expect(result.isError).toBe(true);- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);- });-- test('strategy=delete posts a body without content (DU "stay deleted" / UD "accept deletion")', async () => {- const { server, registrations } = createCapturingServer();- const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];- globalThis.fetch = (async (input, init) => {- fetchCalls.push({ input, init });- return new Response(JSON.stringify({ ok: true }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- });- }) as typeof fetch;-- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- // biome-ignore lint/suspicious/noExplicitAny: pinning the new strategy variant pre-fix- const result = await tool.handler({ file: 'foo.md', strategy: 'delete' as any });-- expect(fetchCalls).toHaveLength(1);- expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({- file: 'foo.md',- strategy: 'delete',- });- expect(result.isError).toBeUndefined();- expect(result.structuredContent).toMatchObject({ ok: true, file: 'foo.md' });- });-- test("tool's input schema enum admits 'delete' alongside the existing three strategies", () => {- const { server, registrations } = createCapturingServer();- register(server, makeDeps('http://localhost:4321'));- const tool = getTool(registrations, 'resolve_conflict');- const inputSchema = (- tool.config as unknown as {- inputSchema?: { strategy?: { options?: readonly string[] } };- }- ).inputSchema;- expect(inputSchema?.strategy?.options).toBeDefined();- expect(inputSchema?.strategy?.options).toContain('delete');- });-});diff --git a/packages/server/src/mcp/tools/resolve-conflict.ts b/packages/server/src/mcp/tools/resolve-conflict.tsdeleted file mode 100644index 5f7681125..000000000--- a/packages/server/src/mcp/tools/resolve-conflict.ts+++ /dev/null@@ -1,110 +0,0 @@-import { z } from 'zod';-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';-import {- HOCUSPOCUS_NOT_RUNNING_ERROR,- httpPost,- outputSchemaWithText,- ROUTED_CWD_DESCRIPTION,- resolveProjectServerContext,- textPlusStructured,- textResult,-} from './shared.ts';--const DESCRIPTION = [- '[Requires: Hocuspocus server] Resolve a tracked conflict by writing the chosen content to disk. Only the strategies listed in `resolutionOptions` on `conflicts({ kind: "content" })` apply.',- '',- 'Strategy:',- '- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.',- '- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.',- '- `content` — writes the exact provided `content` bytes (e.g. a per-hunk merged result, the live Y.Text shown in the DiffView, or an explicit empty string). Use `delete` to remove the file.',- '- `delete` — runs `git rm <file>`, which stages the removal rather than committing it on its own. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',- '',- 'Those git mechanics are the `merge-native` kind (a git merge left unmerged stages); its merge is committed once it was the last tracked `merge-native` conflict, and other kinds do not hold that commit back. On a `working-tree` conflict (a pull-only overlay collision pinned to an origin blob) nothing is committed: `mine` keeps the overlay verbatim, `theirs` restores the pinned origin blob. On a `reconcile` conflict (OK\'s own merge of editor and disk) the chosen bytes land on disk and in the loaded document with no git command, and `mine` uses the latest marker-free live Y.Text, falling back to the captured editor stage when the document is unloaded or contains markers; `theirs` uses the disk stage captured at detection — for `reason: "stale-external-write"`, the current local content and the rejected older save. `resolutionOptions` drops `theirs` when a `reconcile` conflict\'s `theirs` side is raw marker text (`reason` of `disk-markers` or `refused-conflict-markers`), and drops `content` for `refused-too-large`.',- '',- 'Returns 200 on success. 404 (`urn:ok:error:no-conflict-tracked`) means no conflict is tracked for that path — it may have been resolved by another session, or the path may be stale; re-read `conflicts({ kind: "list" })` rather than inferring that your resolution was saved. 422 (`urn:ok:error:unresolved-conflict-markers`) carries a `refusal` field telling two cases apart: `markers-in-content` means the `content` you sent still contains a `<<<<<<< … >>>>>>>` block — a permanent rejection of those bytes, so resolve every region before retrying rather than re-sending; `strategy-not-offered` means your strategy is not among the `resolutionOptions` the same body echoes — pick one from that list. 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',- '',- '**DESTRUCTIVE:** this modifies the working tree, and a `merge-native` resolve also creates a git commit once it was the last tracked `merge-native` conflict.',- '',- '**Parameters:**',- '- `file` — Relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',- "- `strategy` — One of `mine` | `theirs` | `content` | `delete`, narrowed by the conflict's `resolutionOptions`.",- '- `content` — Required when `strategy === "content"`; an empty string keeps an empty file. Ignored otherwise.',-].join('\n');--interface ResolveConflictDeps {- serverUrl: ServerUrlOrResolver;- config: ConfigOrResolver;- resolveCwd: (explicit?: string) => Promise<string>;-}--const OutputSchema = outputSchemaWithText({- ok: z.boolean(),- file: z.string(),-});--export function register(server: ServerInstance, deps: ResolveConflictDeps): void {- server.registerTool(- 'resolve_conflict',- {- description: DESCRIPTION,- inputSchema: {- file: z- .string()- .min(1)- .describe(- 'Relative-to-projectDir path WITH .md or .mdx extension (e.g. `notes/sso.md`).',- ),- strategy: z- .enum(['mine', 'theirs', 'content', 'delete'])- .describe(- "Resolution strategy, narrowed by the conflict's `resolutionOptions`. `content` requires the `content` arg. On a `merge-native` conflict, `delete` runs `git rm`; on the other kinds it removes the file with no git command. Use `delete` for delete-vs-modify (DU/UD) shapes where one stage is missing.",- ),- content: z- .string()- .optional()- .describe(- 'Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.',- ),- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),- },- outputSchema: OutputSchema,- annotations: {- readOnlyHint: false,- idempotentHint: false,- destructiveHint: true,- },- },- async (args: {- file: string;- strategy: 'mine' | 'theirs' | 'content' | 'delete';- content?: string;- cwd?: string;- }) => {- const context = await resolveProjectServerContext(- deps.resolveCwd,- deps.config,- deps.serverUrl,- args.cwd,- );- if (!context.ok) return textResult(`Error: ${context.error}`, true);- const { url } = context;- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);-- const body: Record<string, unknown> = {- file: args.file,- strategy: args.strategy,- };- if (args.content !== undefined) body.content = args.content;-- const result = await httpPost(url, '/api/sync/resolve-conflict', body);- if (!result.ok) {- const error = result.error as string;- const detail = typeof result.detail === 'string' ? result.detail : undefined;- const message = detail ? `${error} — ${detail}` : error;- return textPlusStructured(`Error: ${message}`, { ok: false, file: args.file }, true);- }- const text = `Resolved conflict on ${args.file} (strategy: ${args.strategy}).`;- return textPlusStructured(text, { ok: true, file: args.file });- },- );-}diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.tsindex 9e966d992..55adcd4c9 100644--- a/packages/server/src/mcp/tools/restore-version.ts+++ b/packages/server/src/mcp/tools/restore-version.ts@@ -23,15 +23,8 @@ import {} from './shared.ts';export const DESCRIPTION = [- '[Requires: Hocuspocus server] Restore a DOCUMENT (CRDT, append-only) or a SKILL (fs-direct) to a historical version. Pass EXACTLY ONE of `document` or `skill`.',- '',- '**Parameters:**',- '- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped). Append-only via the CRDT layer; all connected editors see the change live.',- '- `skill` — The skill NAME to restore (PROJECT-scope skills only — global skills are unversioned). Rewrites the skill folder to the target version (fs-direct); every recorded copy re-syncs from it, so there is nothing to re-install.',- '- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).',- '- `summary` — Optional one-line summary (≤80 chars). Avoid secrets or PII — persisted to git history.',- '',- 'A response may include `structuredContent.warnings` (kind `content-divergence`) when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.',+ 'Restore exactly one document or skill to version (40-char SHA from history). Requires the Hocuspocus server. document accepts optional .md/.mdx; restore is append-only through CRDT and visible to connected editors. skill is a PROJECT-scope name (global is unversioned); its folder is rewritten. Recorded, unedited copies refresh on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.',+ 'Optional summary ≤80 chars; avoid secrets or PII, persisted to git history. content-divergence in structuredContent.warnings means restore landed but bytes differ: re-read with exec to see the converged result.',].join('\n');export interface RestoreVersionDeps {diff --git a/packages/server/src/mcp/tools/search.ts b/packages/server/src/mcp/tools/search.tsindex cc918b3cc..749fda45f 100644--- a/packages/server/src/mcp/tools/search.ts+++ b/packages/server/src/mcp/tools/search.ts@@ -31,24 +31,10 @@ import {const log = getLogger('mcp:search');export const DESCRIPTION = [- '[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).',- '',- 'NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.',- '',- 'When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.',- '',- 'Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only).',- '',- 'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',- '',- '**Parameters:**',- '- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.',- '- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.',- '- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.',- '- `limit` (optional) — Max rows; default 20, max 100.',- '- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.',- '',- 'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.',+ 'Ranked search across ALL non-ignored files and folders. Requires the Hocuspocus server. All file name/path values are indexed; only markdown bodies are indexed. Run in parallel with exec grep for exhaustive literal content search, especially code/config/data.',+ 'Pass query; intent full_text (default) includes bodies, omnibar searches title/path/folders. scopes: page/folder/file/content; defaults follow intent. limit: 20 default, 100 max. Ranking combines title boost, BM25 and recency; hits include signals, and pages include snippets (other files are name-only).',+ 'When workspace semantic search is enabled, full_text adds embeddings by default; query and matching content go to the configured provider. Set semantic:false for lexical-only/no embedding egress. Response semantic reports coverage.',+ 'ready:false means an incomplete cold index, not an authoritative empty result. Wait 2–3 seconds before retrying; after 2–3 retries use exec grep. If the server is down, follow recovery text; exec grep is the server-free search fallback.',].join('\n');interface SearchDeps {diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.tsindex d61cc8eef..10206ae55 100644--- a/packages/server/src/mcp/tools/share-link.ts+++ b/packages/server/src/mcp/tools/share-link.ts@@ -26,18 +26,8 @@ import {type ShareKind = 'doc' | 'folder';const DESCRIPTION = [- "[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",- '',- 'Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.',- '',- '**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.',- '',- '**Parameters:**',- '- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',- "- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.",- '- `cwd` (optional) — Project root (see `cwd` description below).',- '',- '**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin.',+ 'Build a shareable GitHub-substrate URL for a teammate to receive a doc/folder subtree in OpenKnowledge, pinned to current branch. Requires the Hocuspocus server. Read-only, no commits/pushes/fetch. Publishing is a user act: agents do NOT publish; a missing remote returns Share-wizard guidance.',+ '`path` is content-relative, docs accept .md/.mdx, empty string means root folder. `kind` doc/folder is optional for auto-probe (.mdx → .md → directory); REQUIRED when `path` is empty (use folder). Optional `cwd` selects project. Requires a named branch, GitHub/GH Enterprise origin, and branch already pushed.',].join('\n');export interface ShareLinkDeps {diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.tsindex 83a7405e4..964677ea8 100644--- a/packages/server/src/mcp/tools/shared.ts+++ b/packages/server/src/mcp/tools/shared.ts@@ -4,6 +4,8 @@ import {AdvisoryWarningSchema,BrokenLinkSchema,BrokenLinkSuppressionSchema,+ getAgentCanonicalDescriptors,+ isAuditEmptyScopeWarning,SERVER_TIMEOUT_ERROR_PREFIX,SERVER_UNREACHABLE_ERROR_PREFIX,UNREADABLE_WARNINGS_TEXT,@@ -32,7 +34,13 @@ export function agentIdentityFields(identity: AgentIdentity | undefined): Record: {};}export const ROUTED_CWD_DESCRIPTION =- 'Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).';+ 'Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.';++export const CANONICAL_COMPONENT_GUIDANCE = `Canonical ids: ${getAgentCanonicalDescriptors()+ .map((descriptor) => descriptor.name)+ .join(+ ', ',+ )}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`;const SUMMARY_TRANSPORT_CAP = 200;@@ -596,7 +604,7 @@ export const AUTHORING_WARNING_CODE_GLOSS ='`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.';export const INSTALL_WARNING_CODE_GLOSS =- '`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.';+ '`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.';export const AUDIT_FILE_CAP = 10;export const AUDIT_FILE_DIAGNOSTIC_CAP = 10;@@ -626,15 +634,30 @@ export function degradationBlock(shown: readonly string[],omitted = 0,): string[] {- const total = shown.length + omitted;+ const degraded = shown.filter((warning) => !isAuditEmptyScopeWarning(warning));+ const total = degraded.length + omitted;if (total === 0) return [];return [`${kind} incomplete — ${total} warning${total === 1 ? '' : 's'} (findings may be partial):`,- ...shown.map((warning) => ` ⚠ ${warning}`),+ ...degraded.map((warning) => ` ⚠ ${warning}`),...(omitted > 0 ? [` … and ${omitted} more warning${omitted === 1 ? '' : 's'}`] : []),];}+export function zeroFindingsSummary(+ kind: 'Lint' | 'Audit',+ fileCount: number,+ warnings: readonly string[],+ scope: string,+): string {+ if (fileCount === 0 && warnings.some(isAuditEmptyScopeWarning))+ return `No documents were checked${scope}; this scope contains no admitted documents.`;+ const documents = `${fileCount} document${fileCount === 1 ? '' : 's'}${scope}`;+ return warnings.length > 0+ ? `No problems found across ${documents}, but the ${kind.toLowerCase()} could not fully complete.`+ : `No problems across ${documents}.`;+}+export interface FormattableDiagnostic {severity?: string;range?: { start?: { line?: number } };diff --git a/packages/server/src/mcp/tools/skill-target.test.ts b/packages/server/src/mcp/tools/skill-target.test.tsindex b04bb061f..b3e6b1820 100644--- a/packages/server/src/mcp/tools/skill-target.test.ts+++ b/packages/server/src/mcp/tools/skill-target.test.ts@@ -65,7 +65,9 @@ describe('skill verb tools — name grammar short-circuits before the network',toName: 'trip-log',})) as ToolResult;expect(r.isError).toBe(true);- expect(text(r)).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);+ expect(text(r)).toContain(HOCUSPOCUS_NOT_RUNNING_ERROR);+ expect(text(r)).toContain('moveState: nothing-written');+ expect(text(r)).toContain('safe to retry once the refusal is addressed');});test('moveSkillCrossScope rejects an invalid name before the network', async () => {@@ -159,6 +161,110 @@ describe('moveSkillCrossScope — delegates to the canonical /api/skill/move-scotoName,}) as Promise<ToolResult>;+ test.each(['nothing-written', 'destination-removed'])(+ '%s names the validated outcome and teaches when retry is safe',+ async (moveState) => {+ mockFetch(() => ({ ok: false, status: 500, error: 'Move failed.', moveState }));+ const result = await move('trip-log');+ expect(text(result)).toContain(`moveState: ${moveState}`);+ expect(text(result)).toContain('safe to retry');+ expect(result.structuredContent).toMatchObject({ moveState });+ },+ );++ test.each(['Delete or rename it first; this move will not overwrite it.', 'SAME_STORAGE'])(+ 'a verified refusal preserves its detail and permits retry after repair: %s',+ async (detail) => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ type: 'urn:ok:error:doc-already-exists',+ error: 'A global skill named "trip-log" already exists.',+ detail,+ moveState: 'nothing-written',+ }));+ const result = await move('trip-log');+ expect(text(result)).toContain('moveState: nothing-written');+ expect(text(result)).toContain(detail);+ expect(text(result)).toContain('safe to retry once the refusal is addressed');+ expect(text(result)).not.toContain('occupant is unverified');+ },+ );++ test.each([400, 409, 500])('a missing state stays unknown even with HTTP %s', async (status) => {+ mockFetch(() => ({ ok: false, status, error: 'Move failed.' }));+ const result = await move('trip-log');+ expect(text(result)).toContain('Do not remove either copy before comparing');+ expect(text(result)).not.toContain('safe to retry');+ expect(result.structuredContent).not.toHaveProperty('moveState');+ });++ test.each([+ { moveState: 'destination-stray', detail: 'Remove the stray destination before retrying.' },+ {+ moveState: 'destination-retained',+ sourceState: 'intact',+ detail: 'The source was intact at removal. Remove the duplicate destination before retrying.',+ },+ {+ moveState: 'destination-retained',+ sourceState: 'lossy',+ detail: 'Recover missing source files from the retained copy before removing either copy.',+ },+ {+ moveState: 'destination-retained',+ sourceState: 'unknown',+ detail: 'Compare both locations before removing either.',+ },+ {+ moveState: 'destination-retained-blocking',+ sourceState: 'intact',+ detail:+ 'The source was intact at the earlier failed removal; compare current contents before removing the duplicate.',+ },+ {+ moveState: 'destination-retained-blocking',+ sourceState: 'lossy',+ detail: 'Recover missing source files from the retained copy before removing either copy.',+ },+ {+ moveState: 'destination-retained-blocking',+ sourceState: 'unknown',+ detail: 'Compare both locations before removing either.',+ },+ {+ moveState: 'nothing-written',+ retentionLedger: 'unreadable',+ detail: 'The retention ledger is unreadable; compare both copies before deleting anything.',+ },+ {+ moveState: 'nothing-written',+ retentionLedger: 'occupant-unverifiable',+ detail: 'The occupant is unverifiable; compare both copies before deleting anything.',+ },+ {+ moveState: 'destination-unreadable',+ detail: 'Do not retry. Restore the skill from a backup or project history.',+ },+ {+ moveState: 'partially-applied',+ detail:+ 'Inspect source and destination; preserve remaining copies and recover missing files.',+ },+ ])(+ 'preserves the guarded recovery for $moveState / $sourceState / $retentionLedger',+ async (outcome) => {+ mockFetch(() => ({ ok: false, status: 500, error: 'Move failed.', ...outcome }));+ const result = await move('trip-log');+ expect(text(result)).toContain(`moveState: ${outcome.moveState}`);+ expect(text(result)).toContain(outcome.detail);+ expect(text(result).split(outcome.detail)).toHaveLength(2);+ expect(text(result)).not.toContain('safe to retry');+ const { detail: _, ...fields } = outcome;+ expect(result.structuredContent).toMatchObject(fields);+ },+ );+test.each(['unreadable', 'future-ledger-reason'])('an inconsistent retained result cannot advertise an intact source: %s',async (retentionLedger) => {@@ -390,7 +496,8 @@ describe('moveSkillCrossScope — delegates to the canonical /api/skill/move-scoconst error = 'Cannot move to project scope.';mockFetch(() => ({ ok: false, status: 400, error, detail: 'NO_PROJECT_ROOT' }));const result = await move('fishing-log');- expect(text(result)).toBe(`Error: ${error} (NO_PROJECT_ROOT)`);+ expect(text(result)).toContain(`Error: ${error} (NO_PROJECT_ROOT)`);+ expect(text(result)).toContain('missing, unrecognized or inconsistent move outcome');expect(result.structuredContent).toMatchObject({ ok: false, error });});});diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.tsindex 6fc3b1220..6969c95fc 100644--- a/packages/server/src/mcp/tools/skill-target.ts+++ b/packages/server/src/mcp/tools/skill-target.ts@@ -7,6 +7,7 @@ import {interpretSkillMoveFailure,normalizeApiWarnings,SKILL_AUTHORING_WARNING_CODES,+ type SkillMoveFailureOutcome,type SkillScope,} from '@inkeep/open-knowledge-core';import type { AgentIdentity } from '../agent-identity.ts';@@ -310,6 +311,29 @@ export function crossScopeMoveSuccessText(input: {return parts.join(' ');}+function crossScopeMoveFailureText(detail: string, outcome: SkillMoveFailureOutcome): string {+ if (outcome.kind === 'unverified' || outcome.moveState === undefined) {+ return `${detail}\nThe server returned a missing, unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination. Do not retry until the outcome is verified.`;+ }+ const lines = [detail, `moveState: ${outcome.moveState}.`];+ if (outcome.moveState === 'nothing-written') {+ if (outcome.retentionLedger !== undefined) {+ lines.push(+ `retentionLedger: ${outcome.retentionLedger}. Compare the source and destination before deleting either copy or retrying.`,+ );+ } else {+ lines.push(+ 'This call changed neither location. It is safe to retry once the refusal is addressed; this does not rule out damage from an earlier call.',+ );+ }+ } else if (outcome.moveState === 'destination-removed') {+ lines.push(+ 'The failed destination copy was removed and the source is intact. It is safe to retry.',+ );+ }+ return lines.join('\n');+}+export async function moveSkillCrossScope(url: string | undefined,input: {@@ -321,7 +345,7 @@ export async function moveSkillCrossScope() {const refuse = (error: string) =>textPlusStructured(- error,+ crossScopeMoveFailureText(error, { kind: 'coherent', moveState: 'nothing-written' }),{ ok: false, kind: 'skill', error, moveState: 'nothing-written' as const },true,);@@ -346,9 +370,7 @@ export async function moveSkillCrossScope(const outcome = interpretSkillMoveFailure(moved);const detail = errorTextWithDetail({ ...moved, error });return textPlusStructured(- outcome.kind === 'unverified'- ? `${detail}\nThe server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination.`- : detail,+ crossScopeMoveFailureText(detail, outcome),{ok: false,kind: 'skill',diff --git a/packages/server/src/mcp/tools/skills.ts b/packages/server/src/mcp/tools/skills.tsindex c89e083f5..2f21e6d5d 100644--- a/packages/server/src/mcp/tools/skills.ts+++ b/packages/server/src/mcp/tools/skills.ts@@ -120,7 +120,7 @@ const SkillLocationEntryOutputSchema = z.object({role: z.enum(['source', 'copy', 'symlink']).describe(- 'source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.',+ 'source = the REAL folder (the skill itself); copy = independent folder, refreshed from the source on watcher/startup sync while unedited (hand edits fork it); symlink = live link to the source.',),audience: z.array(z.string())@@ -205,19 +205,9 @@ const SkillMarketplaceResultOutputSchema = z.object({});const DESCRIPTION = [- '[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).',- '',- 'This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.',- '',- 'Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.',- '',- "OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",- '',- '**Four modes:**',- '- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.',- '- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.',- "- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).",- "- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`).",+ 'Read-only skill discovery. Requires the Hocuspocus server. query searches the skills.sh marketplace and returns import-ready name/source/description/publisher/install-count rows. Import a chosen row with import({source,skill:name}); external rows are not managed or active editor content until imported/projected.',+ 'Omit name to list Project and Global managed skills with scope/description/hosts. name reads description/body plus a bundle files list (path/kind, no inline text); name+file reads one reference/script/bundle file. Optional scope; name-only prefers Project. Address skills by name/scope, never raw .ok/ paths or native cat.',+ 'Built-in open-knowledge* runtime skills are already in your skill list; do not fetch them here. Use write/edit/delete/move/install for changes.',].join('\n');export interface SkillsToolDeps {diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.tsindex 9f51184e7..745fb504e 100644--- a/packages/server/src/mcp/tools/write.test.ts+++ b/packages/server/src/mcp/tools/write.test.ts@@ -287,7 +287,7 @@ describe('write({ document }) relaying a concurrent-overwrite refusal', () => {expect(result.isError).toBe(true);expect(result.content[0]?.text).toBe(- `Error: ${CONCURRENT_OVERWRITE_REFUSED_TITLE} (${CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS}) Retry after ${CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS}s.`,+ `Error: ${CONCURRENT_OVERWRITE_REFUSED_TITLE} (${CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS}) Retry after ${CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS}s. Wait and retry, or use edit for a targeted change.`,);});@@ -300,6 +300,7 @@ describe('write({ document }) relaying a concurrent-overwrite refusal', () => {expect(result.content[0]?.text).toContain(`Retry after ${CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS}s.`,);+ expect(result.content[0]?.text).toContain('or use edit');});});describe('write — an asset upload whose request to the server fails', () => {diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 7f2b7b69d..c0668e1e4 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -7,7 +7,6 @@ import {instantiateDoc,normalizeBridge,parseFrontmatterYaml,- renderInventoryFooter,SKILL_AUTHORING_WARNING_CODES,serializeFrontmatterMap,stripFrontmatter,@@ -19,6 +18,7 @@ import {formatBrokenLinkSuppressionBrief,formatBrokenLinkSuppressionLine,} from '../../broken-link-suppression.ts';+import { CONCURRENT_OVERWRITE_REFUSED_TYPE } from '../../concurrent-overwrite-refused-error.ts';import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';import { mergePatch } from '../../content/frontmatter-merge.ts';import { parentFolderOf } from '../../content/nested-folder-rules.ts';@@ -42,6 +42,7 @@ import {AUTHORING_WARNING_CODE_GLOSS,agentIdentityFields,apiTarget,+ CANONICAL_COMPONENT_GUIDANCE,docExtensionOnDisk,documentResultBaseShape,HOCUSPOCUS_NOT_RUNNING_ERROR,@@ -82,22 +83,18 @@ import {TEMPLATE_PATH_DESCRIBE,} from './verb-schemas.ts';-const BASE_DESCRIPTION = [- 'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).',- '',- '- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. A replace is refused when another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. Peers are told apart per MCP connection. Writers sharing one connection are not refused against each other; there is no `agentId` to send. The MCP connection records you as a peer, while your own recent write does not arm the refusal against your follow-up `replace`. A recent change from a connected editor refuses a `replace` too. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.',- '- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.',- '- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',- '- `skill` — Create or overwrite an agent SKILL: reusable agent guidance you author in OK and `install` into your editors. A NEW skill lands at the project\'s default skill home (e.g. `.agents/skills/<name>/`); an existing one is edited at its real folder. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.',- '- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',- '- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.',- '- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.',- '',- 'Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit).',+const DESCRIPTION = [+ 'Create/replace exactly one `document`, `folder`, `template`, `skill`, or `asset`; use `documents` for an ordered batch. Requires the Hocuspocus server.',+ 'Nested paths such as `guides/overview` can be documents; put all requested blocks in one `document.content`. Use `folder` only for separate pages.',+ '`document: {path, content|template, frontmatter?, position?}`: content and template are exclusive. Existing docs require position: replace/append/prepend; new docs default replace. frontmatter with literal content forces replace, even with append/prepend. Recent edits by another writer can refuse replace; follow the recovery response; append/prepend/edit bypass this refusal. Peers are per MCP connection; own writes and writers sharing a connection do not refuse each other; connected editors can. No agentId is needed.',+ "`folder: {path, frontmatter?}` creates NEW folders; edit existing ones. `template: {path: '<folder>/<name>', content, frontmatter: {title, description?, tags?}}` creates reusable doc templates.",+ '`skill: {name, description, body, scope?}` writes agent guidance; lowercase letters/digits/hyphens name is identity, description is when to use it. New skills use the default skill home; existing ones keep their real folder. Use install for editors.',+ '`asset: {path, content|source}` uploads binary image/file: base64 content or local source path. `documents` takes document specs and reports each result.',+ 'Optional summary: one-line outcome ≤80 chars, persisted to git history; avoid secrets or PII. Batches need per-entry summary; top-level is ignored.',+ 'Read response warnings: content-divergence/disk-edit-reconciled means re-read; mermaid-parse-error means the write landed but fix the fence.',+ CANONICAL_COMPONENT_GUIDANCE,].join('\n');-const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;-interface WriteDeps {serverUrl: ServerUrlOrResolver;config: ConfigOrResolver;@@ -319,10 +316,14 @@ async function writeOneDoc(typeof result.retryAfterSeconds === 'number'? ` Retry after ${result.retryAfterSeconds}s.`: '';+ const recovery =+ result.type === CONCURRENT_OVERWRITE_REFUSED_TYPE+ ? ' Wait and retry, or use edit for a targeted change.'+ : '';return {docName,ok: false,- error: `${detail ? `${String(result.error)} (${detail})` : String(result.error)}${retryAfter}`,+ error: `${detail ? `${String(result.error)} (${detail})` : String(result.error)}${retryAfter}${recovery}`,};}diff --git a/packages/server/src/project-skill-router-contract.test.ts b/packages/server/src/project-skill-router-contract.test.tsnew file mode 100644index 000000000..e9c246558--- /dev/null+++ b/packages/server/src/project-skill-router-contract.test.ts@@ -0,0 +1,250 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';++const skill = readFileSync(join(import.meta.dirname, '../assets/skills/project/SKILL.md'), 'utf8');++const safetyAnchors = [+ '## STOP — native tools on in-scope `.md` / `.mdx`',+ '## Grounding — every factual claim needs a source (MUST)',+ '## Linking — standard markdown links (MUST)',+ '**Read the folder before writing (MUST).**',+ '**Use a template when one fits (MUST).**',+ '**When recurring per-doc properties emerge (MUST).**',+ '**Preview / open a doc — determine your ONE surface FIRST (once per session).**',+ '**Persist incrementally — the knowledge base IS your checkpoint (MUST).**',+];++const routingRules = [+ {+ name: 'markdown reads and source-code escape',+ anchor: '1. **Reads:**',+ required: [+ '`exec("cat …")`',+ '`exec("ls -A …")`',+ '`exec("grep …")`',+ '`search` for ranked retrieval',+ 'never on in-scope `.md` / `.mdx`',+ ],+ },+ {+ name: 'body and metadata writes',+ anchor: '2. **Writes:**',+ required: [+ 'edit({ document: { path, frontmatter } })',+ '`null` deletes a key',+ 'Body find/replace is body-only',+ 'one-line `summary`',+ ],+ },+ {+ name: 'preview surface selection',+ anchor: '3. **Preview / open a doc',+ required: [+ 'Stop at first match',+ '`OK_DESKTOP_TERMINAL` or `OK_HOSTED_AGENT`',+ '`ok open <name>`',+ 'in-app browser',+ '`preview_url`, then open/navigate',+ "Don't `preview_screenshot` to confirm edits",+ ],+ },+ {+ name: 'direct questions before persistence',+ anchor: '4. **Direct questions:**',+ required: [+ '`search` / `exec` + a cited chat answer',+ 'Persist only when durable + multi-doc + not already covered, and *offer* first',+ ],+ },+ {+ name: 'skill source routing',+ anchor: '5. **Authoring or improving a skill**',+ required: [+ 'STOP and invoke **`/open-knowledge-write-skill`**',+ 'Author through `write({ skill })`, never a document path',+ 'Read/edit via `skills` and `edit({ skill })`',+ 'Never hand-edit a non-source copy',+ ],+ },+ {+ name: 'validation coverage and link authority',+ anchor: '**Read `ran`**',+ required: [+ 'a family absent from `ran` was not checked',+ '`[]` means no checks were selected',+ 'For link VALIDATION use audit; links reports relationships',+ ],+ },+ {+ name: 'skill placement and move recovery',+ anchor: 'Skill placement is separate from skill content:',+ required: [+ 'removing an installed copy does not delete the skill',+ 'history resets',+ '`droppedLocations` (success: re-add with install)',+ 'Read the returned outcome before recovery',+ 'self-only (does NOT cascade)',+ ],+ },+ {+ name: 'markdown MCP-only routing',+ anchor: '**Route every in-scope markdown read and write',+ required: [+ "through OK's MCP tools — never your host's native file tools",+ 'Native `Edit` / `sed` / direct `Write`',+ 'native reads skip frontmatter, backlinks',+ ],+ },+ {+ name: 'tool discovery before declaring MCP unavailable',+ anchor: '**Not seeing `exec` is NOT the escape hatch.**',+ required: [+ 'Registration is the test, not top-level-symbol visibility',+ 'run tool discovery for `open-knowledge` first',+ ],+ },+ {+ name: 'narrow and visible native-tool fallback',+ anchor: '**Escape hatch.**',+ required: [+ 'allowed **only** when, after running tool discovery',+ 'no OpenKnowledge MCP server is registered',+ 'immediately after you actually invoked an MCP call and it failed',+ 'begin a user-visible sentence with `OpenKnowledge MCP unavailable:`',+ ],+ },+ {+ name: 'incremental persistence',+ anchor: '**Persist incrementally',+ required: [+ 'write completed work to the KB as you finish each unit',+ 'Never hold finished findings only in your context',+ 'Create the target doc early',+ ],+ },+ {+ name: 'local evidence for factual claims',+ anchor: '- **Every factual claim MUST',+ required: ['cite its source at the point of claim', 'No unsourced speculation'],+ },+ {+ name: 'ingest before citing external sources',+ anchor: '- **Closed loop.**',+ required: [+ 'pulled in by the ingest procedure, then cited locally',+ '**not** a citation',+ 'every leaf is a local doc',+ ],+ },+ {+ name: 'link resolution after writes',+ anchor: 'Link every noun-phrase',+ required: [+ 'Every link must resolve to a doc that exists',+ 'After every `write`/`edit`, read `brokenLinks`: fix reported `href`s',+ '`brokenLinkSuppression` withheld reserved-log findings; those are not yours to repair',+ '`audit` is authoritative',+ ],+ },+ {+ name: 'folder context before writes',+ anchor: '- **Read the folder before writing (MUST).**',+ required: [+ 'call `exec("ls -A <folder>")` once per folder per session',+ '`templates_available`',+ ],+ },+ {+ name: 'template selection',+ anchor: '- **Use a template when one fits (MUST).**',+ required: [+ 'write({ document: { path, template } })',+ 'inherited templates count',+ 'Skip only when none match or the user asked for free-form',+ ],+ },+ {+ name: 'template defaults instead of cascading folder metadata',+ anchor: '- **When recurring per-doc properties emerge (MUST).**',+ required: ['write({ template })', 'Folder frontmatter does not cascade values into docs'],+ },+ {+ name: 'tracked conflict recovery in the app',+ anchor: 'For a conflict refusal,',+ required: [+ "follow the tool's recovery instructions",+ '`references/conflict-resolution.md`',+ 'ask the user to resolve tracked conflicts in the app',+ ],+ },+ {+ name: 'procedure and log contracts',+ anchor: "Don't chain silently:",+ required: [+ 'let the user drive ingest → research → consolidate',+ "a procedure's STOP gates override",+ 'After any turn that changes KB content, check for a `log.md` and follow its contract',+ ],+ },+ {+ name: 'content scope and worktree routing',+ anchor: 'OK looks for documents under',+ required: [+ 'resolved `content.dir`',+ '`.gitignore` and `.okignore`',+ 'not excluded is an OpenKnowledge document',+ "Pass the worktree's absolute path as `cwd`",+ ],+ },+];++function assertRoutingRule(text: string, rule: (typeof routingRules)[number]): void {+ const paragraph = text.split('\n').find((line) => line.startsWith(rule.anchor));+ expect(paragraph, rule.name).toBeDefined();+ for (const required of rule.required) expect(paragraph, rule.name).toContain(required);+}++describe('project skill tool selection and safety contract', () => {+ test.each(routingRules)('retains the $name instructions, beyond their heading', (rule) => {+ assertRoutingRule(skill, rule);+ });++ test.each(routingRules)(+ 'removing a $name instruction is detected even with its heading',+ (rule) => {+ const paragraph = skill.split('\n').find((line) => line.startsWith(rule.anchor));+ if (paragraph === undefined) throw new Error(`Missing rule: ${rule.name}`);+ for (const required of rule.required) {+ const incomplete = skill.replace(paragraph, paragraph.replaceAll(required, ''));+ expect(incomplete).toContain(rule.anchor);+ expect(() => assertRoutingRule(incomplete, rule), required).toThrow();+ }+ },+ );++ test.each(safetyAnchors)('retains %s in the core skill', (anchor) => {+ expect(skill).toContain(anchor);+ });++ test('keeps one worked call for every content verb and teaching-error recovery', () => {+ for (const call of [+ 'write({ document: { path, content } })',+ 'edit({ document: { path, find, replace } })',+ 'delete({ document })',+ 'move({ from, to })',+ ])+ expect(skill).toContain(call);+ expect(skill).toContain('Read it and retry with that shape');+ });++ test('keeps the tool router compact and delegates calling contracts', () => {+ const router = skill.split('## Tool index')[1]?.split('**Self-correcting on misuse:')[0];+ expect(router).toBeDefined();+ expect(router).toContain('calling contracts live in tool descriptions and input schemas');+ expect(Buffer.byteLength(router ?? '', 'utf8')).toBeLessThanOrEqual(2_000);+ expect(skill).not.toContain('## Reads — examples');+ expect(skill).not.toContain('## Server lifecycle');+ expect(skill).toContain('references/conflict-resolution.md');+ });+});diff --git a/packages/server/src/project-wiki-link-lookup.ts b/packages/server/src/project-wiki-link-lookup.tsnew file mode 100644index 000000000..75a6f21ae--- /dev/null+++ b/packages/server/src/project-wiki-link-lookup.ts@@ -0,0 +1,17 @@+import {+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ parseGlobalSkillBundleDoc,+ toWikiLinkSlug,+ type WikiLinkLookupIndex,+} from '@inkeep/open-knowledge-core';++export function buildProjectWikiLinkLookup(docNames: Iterable<string>): WikiLinkLookupIndex {+ const pages = new Set(docNames);+ const projectPages = new Set([...pages].filter((page) => !parseGlobalSkillBundleDoc(page)));+ return {+ pages,+ pagesBySlug: buildPagesBySlugIndex(projectPages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(projectPages, toWikiLinkSlug),+ };+}diff --git a/packages/server/src/relative-content-path.ts b/packages/server/src/relative-content-path.tsnew file mode 100644index 000000000..8e7b65cfa--- /dev/null+++ b/packages/server/src/relative-content-path.ts@@ -0,0 +1,7 @@+export function isValidRelativeContentPath(path: string): boolean {+ if (!path || path.startsWith('/') || path.includes('\\') || path.includes('\x00')) {+ return false;+ }++ return path.split('/').every((segment) => segment && segment !== '.' && segment !== '..');+}diff --git a/packages/server/src/remote-mcp.test.ts b/packages/server/src/remote-mcp.test.tsindex 965ae0a0d..601cc0c8c 100644--- a/packages/server/src/remote-mcp.test.ts+++ b/packages/server/src/remote-mcp.test.ts@@ -210,16 +210,7 @@ async function listToolNames(port: number, gateHeaders: Record<string, string>):return (tools ?? []).map((t) => t.name);}-const WRITE_TOOLS = [- 'write',- 'edit',- 'delete',- 'move',- 'install',- 'checkpoint',- 'restore_version',- 'resolve_conflict',-];+const WRITE_TOOLS = ['write', 'edit', 'delete', 'move', 'install', 'checkpoint', 'restore_version'];function attemptCollabUpgrade(port: number,diff --git a/packages/server/src/seed/skill-pack-list-drift.test.ts b/packages/server/src/seed/skill-pack-list-drift.test.tsindex ea9d16f9e..56294f8b7 100644--- a/packages/server/src/seed/skill-pack-list-drift.test.ts+++ b/packages/server/src/seed/skill-pack-list-drift.test.ts@@ -22,8 +22,10 @@ function readSkillBundle(): string {describe('project SKILL.md starter-pack awareness list', () => {test('lists exactly the packs in STARTER_PACK_IDS (drift guard)', () => {const skill = readSkillBundle();- const listed = [...skill.matchAll(PACK_BULLET_RE)].map((m) => m[1]);- expect(listed.length).toBeGreaterThan(0);+ const packSection = skill.split(/^## Starter packs[^\n]*\n/m)[1]?.split(/^## /m)[0];+ expect(packSection).toBeDefined();+ const listed = [...(packSection ?? '').matchAll(PACK_BULLET_RE)].map((m) => m[1]);+ expect(listed).toHaveLength(STARTER_PACK_IDS.length);expect(new Set(listed)).toEqual(new Set(STARTER_PACK_IDS));});diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.tsindex 6d472a5a8..1cfe2107e 100644--- a/packages/server/src/services/skill-install-ops.ts+++ b/packages/server/src/services/skill-install-ops.ts@@ -592,7 +592,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillInconst cls = classifyInPlaceDest(absDir, canonAbs, inPlaceEntry.contentHash);if (cls === 'different') {warnings.push(- `The copy at ${rel} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`,+ `The copy at ${rel} differs from the current source and was preserved. Inspect both versions before removing it.`,);warningCodes.push('place-fork-refused');continue;diff --git a/packages/server/src/suggest-links.test.ts b/packages/server/src/suggest-links.test.tsindex 10fcf9ea0..996eb04f3 100644--- a/packages/server/src/suggest-links.test.ts+++ b/packages/server/src/suggest-links.test.ts@@ -1,6 +1,6 @@import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { Hocuspocus } from '@hocuspocus/server';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import type * as Y from 'yjs';@@ -44,6 +44,78 @@ describe('suggestLinks', () => {loggerFactory.reset();});+ test('canonical wiki spellings suppress linked labels while unrelated prose remains suggestible', async () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-suggest-resolved-'));+ const hocuspocus = new Hocuspocus({ quiet: true });+ try {+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'notes/beta.md'), '# Beta\n');+ writeFileSync(+ join(root, 'source.md'),+ [+ '[[beta|Beta]]',+ '[[NOTES/BETA|Beta]]',+ '[[beta.md|Beta]]',+ '[[notes/beta.mdx#intro|Beta]]',+ 'Plain Beta remains useful.',+ ].join('\n'),+ );+ const result = await suggestLinks({+ hocuspocus,+ fileIndex: buildFileIndex(root, ['notes/beta', 'source']),+ docName: 'notes/beta',+ });+ expect(result.mentions).toEqual([+ expect.objectContaining({ source: 'source', excerpt: 'Plain Beta remains useful.' }),+ ]);+ writeFileSync(join(root, 'source.md'), '[[missing|Beta]]\n');+ const edited = await suggestLinks({+ hocuspocus,+ fileIndex: buildFileIndex(root, ['notes/beta', 'source']),+ docName: 'notes/beta',+ });+ expect(edited.mentions).toEqual([+ expect.objectContaining({ source: 'source', excerpt: 'Beta' }),+ ]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test('bundle-relative wiki links suppress only mentions of the target in their own bundle', async () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-suggest-bundle-'));+ const hocuspocus = new Hocuspocus({ quiet: true });+ const bundle = '.agents/skills/demo';+ const pages = {+ [`${bundle}/references/beta`]: '# Beta\n',+ [`${bundle}/SKILL`]: '[[references/beta.md#intro|Beta]]\nPlain Beta remains useful.\n',+ [`${bundle}/references/nested/guide`]: '[[references/beta|Beta]]\n',+ '.agents/skills/other/references/beta': '# Other target\n',+ '.agents/skills/other/SKILL': '[[references/beta|Beta]]\n',+ };+ try {+ for (const [name, body] of Object.entries(pages)) {+ const path = join(root, `${name}.md`);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, body);+ }+ const result = await suggestLinks({+ hocuspocus,+ fileIndex: buildFileIndex(root, Object.keys(pages)),+ docName: `${bundle}/references/beta`,+ });+ expect(result.mentions).toEqual([+ expect.objectContaining({+ source: `${bundle}/SKILL`,+ excerpt: 'Plain Beta remains useful.',+ }),+ expect.objectContaining({ source: '.agents/skills/other/SKILL', excerpt: 'Beta' }),+ ]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+test('returns a plain unlinked mention from the admitted disk corpus', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-suggest-links-'));const contentDir = join(projectDir, 'content');diff --git a/packages/server/src/suggest-links.ts b/packages/server/src/suggest-links.tsindex a5358d762..05f4a4c05 100644--- a/packages/server/src/suggest-links.ts+++ b/packages/server/src/suggest-links.ts@@ -1,10 +1,18 @@import { readFile } from 'node:fs/promises';import type { Document, Hocuspocus } from '@hocuspocus/server';-import { resolveInternalHref, stripFrontmatter, toWikiLinkSlug } from '@inkeep/open-knowledge-core';+import {+ resolveInternalHref,+ resolveSkillBundleWikiTarget,+ resolveWikiLinkTargetDocName,+ stripFrontmatter,+ toWikiLinkSlug,+ type WikiLinkLookupIndex,+} from '@inkeep/open-knowledge-core';import type { FileIndexEntry } from './file-watcher.ts';import { readMarkdownLinkAt, readWikiLinkAt } from './link-syntax.ts';import { getLogger } from './logger.ts';import { extractPageIdentity, type PageIdentity } from './page-identity.ts';+import { buildProjectWikiLinkLookup } from './project-wiki-link-lookup.ts';const log = getLogger('suggest-links');@@ -316,18 +324,13 @@ function contiguousOffsets(start: number, text: string): number[] {return offsets;}-function wikiLinkResolvesToTarget(target: string, targetDocName: string): boolean {- const trimmed = target.trim();- if (!trimmed) return false;- return trimmed === targetDocName || toWikiLinkSlug(trimmed) === targetDocName;-}-function scanLineForMentions(line: string,lineStartOffset: number,sourceDocName: string,targetDocName: string,labels: readonly SearchLabel[],+ lookup: WikiLinkLookupIndex,): Array<{ excerpt: string; offset: number }> {let flatText = '';const plainSegments: PlainSegment[] = [];@@ -406,7 +409,12 @@ function scanLineForMentions(const wikiLink = readWikiLink(line, index);if (wikiLink) {const label = wikiLink.label;- if (wikiLinkResolvesToTarget(wikiLink.target, targetDocName)) {+ if (+ resolveWikiLinkTargetDocName(+ resolveSkillBundleWikiTarget(wikiLink.target, sourceDocName) ?? wikiLink.target,+ lookup,+ ) === targetDocName+ ) {appendNonMatchableText(label);} else {appendMatchableText(@@ -463,6 +471,7 @@ function scanMarkdownForMentions(sourceDocName: string,targetDocName: string,labels: readonly SearchLabel[],+ lookup: WikiLinkLookupIndex,): Array<{ excerpt: string; offset: number }> {const { frontmatter, body } = stripFrontmatter(markdown);const bodyStartOffset = frontmatter.length;@@ -494,6 +503,7 @@ function scanMarkdownForMentions(sourceDocName,targetDocName,labels,+ lookup,),);}@@ -570,6 +580,7 @@ export async function suggestLinks(options: SuggestLinksOptions): Promise<Sugges.filter((candidateDocName) => candidateDocName !== docName).sort((left, right) => left.localeCompare(right));+ const lookup = buildProjectWikiLinkLookup(fileIndex.keys());const mentionsBySource = new Map<string, SuggestLinksMention[]>();let truncated = false;@@ -595,6 +606,7 @@ export async function suggestLinks(options: SuggestLinksOptions): Promise<SuggessourceDocName,docName,searchLabels,+ lookup,).map((mention) => ({source: sourceDocName,excerpt: mention.excerpt,diff --git a/packages/server/src/validation-coverage-contract.uncached.test.ts b/packages/server/src/validation-coverage-contract.uncached.test.tsindex 5bd7a50b0..449840ed7 100644--- a/packages/server/src/validation-coverage-contract.uncached.test.ts+++ b/packages/server/src/validation-coverage-contract.uncached.test.ts@@ -54,6 +54,12 @@ function mcpReferenceRow(tool: string): string {}describe('validation coverage source contract', () => {+ test('narrowing an audit scope does not promise to remove per-file caps', () => {+ for (const description of [LINT_DESCRIPTION, AUDIT_DESCRIPTION]) {+ expect(description).not.toContain('scoped to a folder or file to see what was omitted');+ }+ });+test('OKF documents every parser reservation neutralized by generated indexes', () => {const executable = Array.from({ length: 0xf8ff - 0xe000 + 1 }, (_, offset) => 0xe000 + offset).filter((codepoint) => isMutatingParserReservation(String.fromCodePoint(codepoint)))