Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

OK: MCP tool surface redesign to 17 native CRUD verbs (#1625)

tim-inkeep78fe4dd19154
diff --git a/docs/content/advanced/folders-and-templates.mdx b/docs/content/advanced/folders-and-templates.mdx
index 106b9db34..a32254d0b 100644
--- a/docs/content/advanced/folders-and-templates.mdx
+++ b/docs/content/advanced/folders-and-templates.mdx
@@ -116,7 +116,7 @@ Folder *properties* do not behave this way: they describe only their own folder
Agents create documents from templates the same way you do. Through MCP, an agent calls:
```text
-write_document({ docName: "posts/launch", template: "blog-post" })
+write({ document: { path: "posts/launch", template: "blog-post" } })
```
Open Knowledge finds the `blog-post` template the same way the New File dialog does: the agent gets the one that applies to `posts/`. The template's **starter content** becomes the new document; the template's own name and description stay behind as template info and are not copied into the document.
@@ -130,10 +130,10 @@ You never have to edit these files by hand (the folder overview page is the fron
- A folder's own properties live in `<folder>/.ok/frontmatter.yml` (open-shape: any keys; `title` / `description` / `tags` are the conventional ones).
- Templates live in `<folder>/.ok/templates/<name>.md`.
-A folder only gets a `.ok/` directory once you give it a description or its first template; folders with nothing special stay plain. See the [Configuration reference](/docs/reference/configuration#folder-properties) for the file formats, and the [MCP reference](/docs/reference/mcp) for the `folder_config` and `write_document` tools that set the same things from an AI agent.
+A folder only gets a `.ok/` directory once you give it a description or its first template; folders with nothing special stay plain. See the [Configuration reference](/docs/reference/configuration#folder-properties) for the file formats, and the [MCP reference](/docs/reference/mcp) for the `write` and `edit` tools (with `folder` and `template` targets) that set the same things from an AI agent.
## See also
- [Editor](/docs/features/editor): the Properties panel and the file sidebar.
- [Configuration](/docs/reference/configuration): the `.ok/` file formats behind these settings.
-- [MCP reference](/docs/reference/mcp): the `write_document` tool and templates.
+- [MCP reference](/docs/reference/mcp): the `write` tool and templates.
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 62b75dd2a..bb3a861f2 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -40,7 +40,7 @@ The **Scope** column says which file a setting belongs in: **project** → `.ok/
## Folder properties
-A folder's own metadata lives in that folder's `.ok/` directory, not in `config.yml`: its own open-shape frontmatter (any keys; `title` / `description` / `tags` are the conventional ones) in `.ok/frontmatter.yml`, and its templates in `.ok/templates/`. Folder properties describe only their own folder: they are not inherited by the docs inside it. (Templates do resolve leaf-to-root, so a root template is available in every subfolder.) Set them from the editor's **Folder properties** pane, or via the `folder_config` MCP tool. See [Folders and templates](/docs/advanced/folders-and-templates#folder-properties) for the full walkthrough.
+A folder's own metadata lives in that folder's `.ok/` directory, not in `config.yml`: its own open-shape frontmatter (any keys; `title` / `description` / `tags` are the conventional ones) in `.ok/frontmatter.yml`, and its templates in `.ok/templates/`. Folder properties describe only their own folder: they are not inherited by the docs inside it. (Templates do resolve leaf-to-root, so a root template is available in every subfolder.) Set them from the editor's **Folder properties** pane, or via the `edit({ folder })` / `write({ folder })` MCP tools. See [Folders and templates](/docs/advanced/folders-and-templates#folder-properties) for the full walkthrough.
## Ignore patterns
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index c8ca3c5e3..62ed0866f 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -3,7 +3,9 @@ title: MCP
description: Tools the Open Knowledge MCP server exposes to AI agents.
---
-The MCP server gives AI agents structured access to your knowledge base. Only `exec` is truly server-free: its shell-style reads run fs-direct against the disk and work even when the editor is down. Every other read tool (`search`, `links`, `get_history`, etc.) and all write tools route through the Hocuspocus server, which Open Knowledge starts for you on the first write.
+The MCP server gives AI agents structured access to your knowledge base. Two reads are server-free: `exec` (shell-style reads, fs-direct against the disk) and `preview_url` (reads `ui.lock` directly) both work even when the editor is down. Every other read tool (`search`, `links`, `history`, etc.) and all write tools route through the Hocuspocus server, which Open Knowledge starts for you on the first write.
+
+The surface is **17 tools**. Three of the four write verbs — `write`, `edit`, `delete` — are native CRUD operations polymorphic over a target (`document`, `folder`, `template`, `asset`): per-target fields nest inside the address key (`write({ document: { path, content } })`), and you pass exactly one target per call. `move` is the fourth write verb but takes flat `from`/`to` paths and auto-detects whether the path is a document, folder, or asset (no `template` target).
## Tools
@@ -11,56 +13,57 @@ The MCP server gives AI agents structured access to your knowledge base. Only `e
| --- | --- |
| `exec` | Read-only shell (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`); reads return frontmatter, backlinks, and recent history. Fs-direct; works without the server. |
| `search` | Ranked workspace search (title boost + body BM25 + recency; same engine the cmd-K palette uses) |
-| `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 |
-| `get_history` | Version timeline for a doc |
-| `get_config` | Read `.ok/config.yml` |
-| `get_components` | Details for the canonical authoring components |
-| `get_preview_url` | Resolve the browser-reachable preview URL. Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
-| `write_document` | Write a doc body and/or frontmatter. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend` |
-| `edit_document` | Find-and-replace inside a doc body |
-| `edit_frontmatter` | Set, create, or delete frontmatter properties (JSON Merge Patch) |
-| `delete_document` | Delete a doc |
-| `rename` | Rename a doc or folder and rewrite every affected link |
-| `version` | `action` selects: `save` a project checkpoint, or `rollback` a doc to an earlier version |
-| `folder_config` | `action` selects: `set-rule` (folder's own frontmatter, open-shape like a doc's), `write-template`, or `delete-template` |
-| `ingest` | Capture an external URL or file as reference material |
-| `research` | Gather sources and write provisional findings |
-| `consolidate` | Promote research into a canonical article |
-| `discover` | Set up an existing repo: extract conventions, seed folder rules and templates |
-| `list_conflicts` | List every doc currently tracked in a merge-conflict state. Returns each doc's `lifecycle: { status, reason }` so you can detect conflict state proactively |
-| `get_conflict_content` | Read the base / ours / theirs stages of a conflicted doc |
-| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content`) and commit |
+| `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 |
+| `history` | Version timeline for a doc. Each entry carries a `version` (commit SHA) you pass to `restore_version` |
+| `config` | Read the effective merged config (`config({ key: "appearance.theme" })` for a sub-tree; omit `key` for the whole config) |
+| `palette` | Markdown-native authoring forms, themed `html preview` embed starters, and theme tokens. Pass `components` for the canonical components' full JSX prop schemas |
+| `preview_url` | Resolve the browser-reachable preview URL. Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
+| `share_link` | Build a GitHub-substrate share URL for a doc to send to a teammate (read-only against `.git/`; never publishes) |
+| `write` | Create or overwrite a `document`, `folder`, `template`, 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` |
+| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), or a `template` |
+| `delete` | Delete a `document` (one path or an array), `folder`, `template`, or `asset` |
+| `move` | Move or rename a `document`, `folder`, or `asset` and rewrite every affected link |
+| `checkpoint` | Save a project-wide version snapshot — a single restore point. Returns its `version` |
+| `restore_version` | Restore one document to a historical `version` (the SHA from `history` or `checkpoint`) |
+| `conflicts` | Read GitHub-sync merge conflicts. `kind: "list"` enumerates tracked conflicts; `kind: "content"` returns one file's base / ours / theirs stages |
+| `resolve_conflict` | Write a chosen resolution (`mine` / `theirs` / `content` / `delete`) and commit |
+| `workflow` | Procedural guides. `kind` selects: `ingest` (capture a source), `research` (gather + write provisional findings), `consolidate` (promote research to a canonical article), or `discover` (onboard an existing repo) |
+
+## 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: { … } }` (with any `contentDivergence`), and a batch returns `{ documents: [ … ] }`. The uniform preview envelope (`previewUrl`, `previewUrlSource`, `warning`) always stays at the top level — every tool surfaces it the same way. `conflicts` and `links` nest the same way under their `kind`.
## Instantiating from a template
-`write_document` accepts a `template` argument that resolves against the cascade of templates available for the target document's parent folder, using the same folder-up walk the [Folders and templates](/docs/advanced/folders-and-templates#templates) page describes. The template body becomes the new document's content; the template's own info block (its name and description) is stripped, so it doesn't bleed onto the document. Document-shaped frontmatter belongs *in the body*; see [Give new documents their own properties](/docs/advanced/folders-and-templates#give-new-documents-their-own-properties).
+`write` accepts a `template` field on the `document` target — `write({ document: { path, template } })` — that resolves against the cascade of templates available for the target document's parent folder, using the same folder-up walk the [Folders and templates](/docs/advanced/folders-and-templates#templates) page describes. The template body becomes the new document's content; the template's own info block (its name and description) is stripped, so it doesn't bleed onto the document.
-`template` and `markdown` are mutually exclusive: passing both errors with `TEMPLATE_AND_MARKDOWN_BOTH_SET`. With `template`, `position` is forced to `replace` (initial create semantics).
+`content` and `template` are mutually exclusive. With `template`, `position` is forced to `replace` (initial create semantics).
## Editing frontmatter
-Use `edit_frontmatter` for frontmatter edits: it applies a JSON Merge Patch (set or create a key with a value, delete a key by passing `null`). `edit_document` is body-only and refuses find/replace patterns that touch frontmatter; `write_document` with `position: "replace"` is the only write mode that includes the `---\n…\n---` block (other positions ignore any frontmatter in the payload).
+Use `edit({ document: { path, frontmatter } })` for frontmatter edits: it applies a JSON Merge Patch (set or create a key with a value, delete a key by passing `null`). A document body find/replace (`edit({ document: { path, find, replace } })`) is body-only and refuses patterns that touch frontmatter; `write` with `position: "replace"` is the only write mode that includes the `---\n…\n---` block (other positions ignore any frontmatter in the payload). Folders and templates take frontmatter the same way: `edit({ folder: { path, frontmatter } })`.
## Edit summaries
-The write tools (`write_document`, `edit_document`, `edit_frontmatter`, `rename`, `version`) accept an optional `summary` describing the intent of the edit, e.g. `"Fixed token-refresh race"`. Summaries appear on the document's timeline so readers can scan recent agent activity.
+The write tools (`write`, `edit`, `move`, `checkpoint`) accept an optional `summary` describing the intent of the edit, e.g. `"Fixed token-refresh race"`. Summaries appear on the document's timeline so readers can scan recent agent activity.
Cap is 80 characters. Avoid secrets and PII; summaries persist to git history.
## Conflict-aware writes
-Every mutating tool (`write_document`, `edit_document`, `edit_frontmatter`, `delete_document`, `rename`, `version`, `folder_config`, and agent undo) refuses to mutate a doc whose GitHub-sync state is `conflict`.
+Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses to mutate a doc whose GitHub-sync state is `conflict`.
-To recover, call `get_conflict_content` to inspect the merge stages, then `resolve_conflict` with one of:
+To recover, call `conflicts({ kind: "content", file })` to inspect the merge stages, then `resolve_conflict` with one of:
-- `mine`: write the `git show :2:<file>` stage (your committed version, last commit before the merge).
-- `theirs`: write the `git show :3:<file>` stage (their committed version).
+- `mine`: resolve to your committed version (stage 2 — runs `git checkout --ours <file>` then `git add`).
+- `theirs`: resolve to their committed version (stage 3 — runs `git checkout --theirs <file>` then `git add`).
- `content`: write the exact bytes you supply (for example, a merged result you composed by reading both stages).
+- `delete`: `git rm` the file (for delete-vs-modify shapes where one stage is missing).
-To detect conflict state proactively without waiting for a 409, call `list_conflicts`; it enumerates every conflicted doc with its `lifecycle: { status, reason }`.
+To detect conflict state proactively without waiting for a 409, call `conflicts({ kind: "list" })`; it enumerates every conflicted doc with its `lifecycle: { status, reason }`. `exec("cat …")` also returns that `lifecycle` field for any doc.
## Preview links
-Read 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`, terminal `open <url>`) call `get_preview_url` to resolve the full URL once per session. The editor refocuses automatically on subsequent writes.
+Read 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`, terminal `open <url>`) call `preview_url` to resolve the full URL once per session. The editor refocuses automatically on subsequent writes.
-`get_preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](/docs/reference/configuration) preference. The write tools (`write_document`, `edit_document`, `edit_frontmatter`) 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.
+`preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](/docs/reference/configuration) 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.
diff --git a/docs/content/workflows/entity-vault.mdx b/docs/content/workflows/entity-vault.mdx
index 158136979..0c3fce928 100644
--- a/docs/content/workflows/entity-vault.mdx
+++ b/docs/content/workflows/entity-vault.mdx
@@ -23,7 +23,7 @@ Open Knowledge scaffolds and edits that Markdown. Garry Tan's [`gbrain`](https:/
| --- | --- | --- |
| Markdown files | Creates, edits, reviews, templates, folder guidance | Imports/syncs as source material |
| Human correction | WYSIWYG/source editor, activity attribution, version checkpoints | Sees corrections after import/sync |
-| Agent writes | OK MCP tools (`write_document`, `edit_document`, `links`, `version`, `search`, `exec`) | GBrain MCP/skills if you choose to run them separately |
+| Agent writes | OK MCP tools (`write`, `edit`, `links`, `checkpoint`, `search`, `exec`) | GBrain MCP/skills if you choose to run them separately |
| Search/retrieval | OK project search and graph tooling | PGLite/Postgres, embeddings, hybrid retrieval, graph/index automation |
| Interop contract | Plain Markdown + Git | `gbrain import` / `gbrain sync --repo` |
diff --git a/docs/content/workflows/karpathy-llm-wiki.mdx b/docs/content/workflows/karpathy-llm-wiki.mdx
index 22fa13586..c66473559 100644
--- a/docs/content/workflows/karpathy-llm-wiki.mdx
+++ b/docs/content/workflows/karpathy-llm-wiki.mdx
@@ -3,9 +3,9 @@ title: Karpathy's LLM wiki workflow
description: Build a source-grounded knowledge base where an LLM agent curates the wiki from the raw material you feed it. Every claim traces back to a preserved source. Maps directly to the Knowledge base starter pack.
---
-A persistent, compounding knowledge base where you bring the raw material and the LLM does the summarization, cross-referencing, and maintenance. The pattern is Andrej Karpathy's, from [his April 2026 gist on LLM-curated wikis](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). Open Knowledge ships the **Knowledge base** starter pack as a direct implementation, with one extension Karpathy doesn't formalize: **the wiki layer is split** into `research/` (status: provisional) and `articles/` (status: canonical), with the `consolidate` MCP tool as the explicit promotion step, so premature canonicalization becomes a thing you opt into rather than something that drifts in.
+A persistent, compounding knowledge base where you bring the raw material and the LLM does the summarization, cross-referencing, and maintenance. The pattern is Andrej Karpathy's, from [his April 2026 gist on LLM-curated wikis](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). Open Knowledge ships the **Knowledge base** starter pack as a direct implementation, with one extension Karpathy doesn't formalize: **the wiki layer is split** into `research/` (status: provisional) and `articles/` (status: canonical), with the `consolidate` workflow as the explicit promotion step, so premature canonicalization becomes a thing you opt into rather than something that drifts in.
-The point of this guide is to show how **Open Knowledge's features compose** to make the pattern feel native: the starter-pack picker scaffolds the layout in one click; per-folder templates + agent-readable folder frontmatter teach the LLM the conventions (Karpathy's centralized `CLAUDE.md` / `AGENTS.md` schema, distributed per-folder); the three workflow MCP tools (`ingest`, `research`, `consolidate`) cover the sources → provisional → canonical pipeline; the WYSIWYG editor + CRDT keep editing frictionless; the activity panel attributes every write; the `links` tool keeps the source graph clean. Every step uses three or four of these together. That's the product.
+The point of this guide is to show how **Open Knowledge's features compose** to make the pattern feel native: the starter-pack picker scaffolds the layout in one click; per-folder templates + agent-readable folder frontmatter teach the LLM the conventions (Karpathy's centralized `CLAUDE.md` / `AGENTS.md` schema, distributed per-folder); the `workflow` tool's three pipeline kinds (`ingest`, `research`, `consolidate`) cover the sources → provisional → canonical pipeline; the WYSIWYG editor + CRDT keep editing frictionless; the activity panel attributes every write; the `links` tool keeps the source graph clean. Every step uses three or four of these together. That's the product.
## Who this is for
@@ -88,7 +88,7 @@ The **Knowledge base** pack scaffolds Karpathy's pattern with one significant ad
| Karpathy | Open Knowledge |
|---|---|
-| `raw/` (verbatim sources, immutable) | `external-sources/` (OK's name; same role) + `clip` template + `ingest` MCP tool |
+| `raw/` (verbatim sources, immutable) | `external-sources/` (OK's name; same role) + `clip` template + `ingest` workflow |
| `wiki/` (single LLM-owned layer) | **Split**: `research/` (provisional, status:`provisional`, sources cited) + `articles/` (canonical, status:`canonical`, supersedes chain); `consolidate` promotes |
| `log.md` (append-only record) | `log.md` at project root, written by the pack |
| `index.md` (static content catalog) | Provided dynamically via `exec` (`ls`) + the file sidebar. The agent reads folder frontmatter + per-doc metadata on every list call, so a static index isn't required. You can still hand-write `index.md` if you prefer. |
@@ -121,7 +121,7 @@ If you accepted the desktop app's first-launch offer to wire up your agent assis
> list the workflow tools available
```
-You should see `mcp__open-knowledge__ingest`, `mcp__open-knowledge__research`, and `mcp__open-knowledge__consolidate`, alongside the standard reads/writes (`exec`, `search`, `write_document`, `links`, etc.). The three workflow tools cover the sources → provisional → canonical pipeline described in the mapping table above.
+You should see `mcp__open-knowledge__workflow` (its `kind` covers `ingest` / `research` / `consolidate` / `discover`), alongside the standard reads/writes (`exec`, `search`, `write`, `links`, etc.). The workflow guides cover the sources → provisional → canonical pipeline described in the mapping table above.
### 4. Ingest the five sources
@@ -147,7 +147,7 @@ Your agent uses `exec("ls external-sources/")` to read frontmatter and per-file
> research the agent-framework question; synthesize the five sources in external-sources/
```
-The `research` tool spins up a step-by-step research flow: it confirms scoping, lists what's covered by the existing sources, identifies gaps (maybe one source you haven't ingested yet), and produces a `research/agent-framework-evaluation.md` with `status: provisional` and a `sources:` array listing the five paths.
+Running `workflow({ kind: "research", topic: "agent-framework evaluation" })` spins up a step-by-step research flow: it confirms scoping, lists what's covered by the existing sources, identifies gaps (maybe one source you haven't ingested yet), and produces a `research/agent-framework-evaluation.md` with `status: provisional` and a `sources:` array listing the five paths.
Every claim in the log cites a specific source path. You can now ask:
@@ -161,11 +161,11 @@ The agent reads `research/agent-framework-evaluation.md` first, follows the cita
The pack doesn't just create three folders. It scaffolds the **agent-readable schema layer** that makes the LLM behave per Karpathy's conventions without you hand-writing a `CLAUDE.md`.
-Each folder gets a `.ok/frontmatter.yml` (the agent reads it on every `exec` directory listing) plus a `.ok/templates/<name>.md` (the agent picks it on every `write_document({ template })` call). `external-sources/.ok/frontmatter.yml`, for example, opens with:
+Each folder gets a `.ok/frontmatter.yml` (the agent reads it on every `exec` directory listing) plus a `.ok/templates/<name>.md` (the agent picks it on every `write({ document: { template } })` call). `external-sources/.ok/frontmatter.yml`, for example, opens with:
> Raw sources SAVED verbatim, not just cited. Produced by `ingest`... Immutable after capture. No analysis in these files; that belongs in `research/`.
-Result: the agent learns each layer's discipline without a separate prompt or skills file. `research/` and `articles/` carry analogous descriptions. This is Karpathy's centralized `CLAUDE.md` schema, distributed per-folder, so schema lives closest to the agent action. Customize via `mcp__open-knowledge__folder_config`.
+Result: the agent learns each layer's discipline without a separate prompt or skills file. `research/` and `articles/` carry analogous descriptions. This is Karpathy's centralized `CLAUDE.md` schema, distributed per-folder, so schema lives closest to the agent action. Customize via `mcp__open-knowledge__edit` (with a `folder` target).
## The consolidate step, deferred
@@ -175,9 +175,9 @@ You don't consolidate yet in our scenario; the team hasn't decided. Maybe in two
> consolidate the agent-framework research into a canonical article
```
-The `consolidate` tool starts with a STOP gate asking whether the decision is actually made. If yes, it writes `articles/agent-framework-evaluation.md` with `status: canonical` and a `supersedes:` chain pointing back to the research log. That `research/` doc isn't deleted; it's superseded, so the evidence chain stays intact.
+The `workflow` tool's `consolidate` kind starts with a STOP gate asking whether the decision is actually made. If yes, it writes `articles/agent-framework-evaluation.md` with `status: canonical` and a `supersedes:` chain pointing back to the research log. That `research/` doc isn't deleted; it's superseded, so the evidence chain stays intact.
-**What just composed.** Five sources became one canonical article via: the **Knowledge base starter pack** (three folders, three templates, agent-readable folder frontmatter, one click), the **three workflow MCP tools** (`ingest`/`research`/`consolidate` mapping 1:1 to Karpathy's layers), the **agent activity panel** (every fetch + write attributed), the **wikilink graph + frontmatter `sources:` arrays** (citation chain audit-able doc by doc), and the **WYSIWYG editor** (review and refine without leaving the same surface). The same vault, the same product, the whole stack working as one thing.
+**What just composed.** Five sources became one canonical article via: the **Knowledge base starter pack** (three folders, three templates, agent-readable folder frontmatter, one click), the **`workflow` tool's three pipeline kinds** (`ingest`/`research`/`consolidate` mapping 1:1 to Karpathy's layers), the **agent activity panel** (every fetch + write attributed), the **wikilink graph + frontmatter `sources:` arrays** (citation chain audit-able doc by doc), and the **WYSIWYG editor** (review and refine without leaving the same surface). The same vault, the same product, the whole stack working as one thing.
## The promotion rhythm
@@ -189,7 +189,7 @@ When to use each tool, and when *not* to:
| You searched the web yourself to ground a claim | `ingest` | Closed-loop: the KB doesn't cite the live web, only local docs |
| You're synthesizing 2+ sources into an answer | `research` | Provisional article, citations required, status:provisional |
| Team decided; this is the canonical position | `consolidate` | Writes status:canonical with supersedes chain |
-| You just want to write a note | `write_document` | Not every doc needs the workflow (scratch notes, project pages, runbooks) |
+| You just want to write a note | `write` | Not every doc needs the workflow (scratch notes, project pages, runbooks) |
| You ran a one-off query and the answer's useful | Save the chat to a new doc in `research/` | Per Karpathy: *"valuable query results become new wiki pages"*; don't let them die in chat history |
**Anti-pattern: consolidating too early.** If you `consolidate` before the team has actually decided, you'll be rewriting canonical articles every week. Status `provisional` exists for a reason. Keep things in `research/` until decisions are real.
@@ -201,8 +201,8 @@ When to use each tool, and when *not* to:
| When | Do | Composes |
|---|---|---|
| **As sources arrive** | `ingest` (30 sec per source) | MCP tool + `external-sources/.ok/` frontmatter + `clip` template + agent activity panel |
-| **Weekly** | A `research` pass to synthesize recent ingests; ask the agent to flag contradictions | `research` MCP tool + folder frontmatter discipline + wikilink graph |
-| **Per-decision** | `consolidate` to canonical | `consolidate` MCP tool + supersedes chain + `articles/` template |
+| **Weekly** | A `research` pass to synthesize recent ingests; ask the agent to flag contradictions | `research` workflow + folder frontmatter discipline + wikilink graph |
+| **Per-decision** | `consolidate` to canonical | `consolidate` workflow + supersedes chain + `articles/` template |
| **Monthly** | *"find stale claims in `articles/`, orphans, missing cross-refs"* | `links` (orphans, dead links, backlinks) |
The compounding move: end each ingest session with one synthesis query. The answer becomes a `research/` doc. The wiki grows.
diff --git a/packages/app/scripts/audit-strings/extract.ts b/packages/app/scripts/audit-strings/extract.ts
index 90bc984b4..cc46e081d 100644
--- a/packages/app/scripts/audit-strings/extract.ts
+++ b/packages/app/scripts/audit-strings/extract.ts
@@ -138,7 +138,7 @@ const VIEW_GROUP_RULES: Array<[RegExp, string]> = [
[/^components\/Frontmatter/, 'Property Panel'],
[/^components\/Template/, 'Templates'],
[/^components\/Graph/, 'DocPanel / Graph'],
- [/^components\/FolderDefaults/, 'Settings'],
+ [/^components\/FolderProperties/, 'Settings'],
[/^components\/Folder/, 'Folder overview'],
[/^components\/EmptyEditor/, 'Empty state'],
[/^components\/Empty/, 'Empty state'],
diff --git a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
index 57a2479cb..e8fbd1234 100644
--- a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
+++ b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
@@ -107,7 +107,7 @@ describe('AddPropertyRow — typing target stays focused after type change (Prop
});
});
-describe('AddPropertyRow — typing target stays focused after type change (FolderDefaultsCard consumer)', () => {
+describe('AddPropertyRow — typing target stays focused after type change (FolderPropertiesCard consumer)', () => {
afterEach(() => {
cleanup();
});
diff --git a/packages/app/src/components/FolderOverview.tsx b/packages/app/src/components/FolderOverview.tsx
index 928d4efd1..839b739bd 100644
--- a/packages/app/src/components/FolderOverview.tsx
+++ b/packages/app/src/components/FolderOverview.tsx
@@ -2,7 +2,7 @@ import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
import { ArrowDown, ArrowUp, ArrowUpDown, File, Folder, FolderOpen, Plus } from 'lucide-react';
import { useState } from 'react';
-import { FolderDefaultsCard } from '@/components/FolderDefaultsCard';
+import { FolderPropertiesCard } from '@/components/FolderPropertiesCard';
import {
buildFolderOverviewData,
type FolderOverviewEntry,
@@ -175,7 +175,7 @@ export function FolderOverview({ folderPath }: { folderPath: string }) {
</Button>
</div>
</div>
- <FolderDefaultsCard
+ <FolderPropertiesCard
folderPath={folderPath}
state={folderConfig}
onChange={refreshFolderConfig}
diff --git a/packages/app/src/components/FolderDefaultsCard.tsx b/packages/app/src/components/FolderPropertiesCard.tsx
similarity index 95%
rename from packages/app/src/components/FolderDefaultsCard.tsx
rename to packages/app/src/components/FolderPropertiesCard.tsx
index 68a05a468..82bca94e4 100644
--- a/packages/app/src/components/FolderDefaultsCard.tsx
+++ b/packages/app/src/components/FolderPropertiesCard.tsx
@@ -32,7 +32,7 @@ interface Props {
onChange: () => void;
}
-export function FolderDefaultsCard({ folderPath, state, onChange }: Props) {
+export function FolderPropertiesCard({ folderPath, state, onChange }: Props) {
const { t } = useLingui();
const [collapsed, setCollapsed] = useState(false);
const [adding, setAdding] = useState<AddDraft | null>(null);
@@ -211,12 +211,7 @@ export function FolderDefaultsCard({ folderPath, state, onChange }: Props) {
<CollapsibleContent>
<div className="px-2 py-2">
<p className="px-1 pb-2 text-sm text-muted-foreground">
- <Trans>
- What this folder is about — give it a title, description, tags, or any properties
- you like, just like a doc has. This describes the folder itself; it is not copied
- into the docs inside it. To start new docs in this folder with a ready-made set of
- properties, add a template instead.
- </Trans>
+ <Trans>A title, description, tags — anything that describes this folder.</Trans>
</p>
{orderedKeys.length === 0 && !adding ? (
<p className="px-1 py-1 text-sm text-muted-foreground">
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 4036a0b60..5919a9923 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -1272,6 +1272,7 @@
],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
"ehLu5O": ["Open in Terminal, ", ["hint"]],
+ "eiXVx8": ["Properties that describe this folder."],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
"ensWZc": ["or start from scratch <0/>"],
"euc6Ns": ["Duplicate"],
@@ -1352,6 +1353,7 @@
"hGmuTc": ["Docs tagged #", ["tagDocsName"]],
"hHMv6l": ["Delete block"],
"hJu2pH": ["This folder already has files. Add a name to create a new subfolder inside it."],
+ "hSBIG-": ["A title, description, tags — anything that describes this folder."],
"hSySVc": ["Install handoff failed: ", ["msg"]],
"hXUWyd": ["Value is required"],
"hXbSxc": ["Asset: ", ["title"]],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index f37952342..c52d1bfdb 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -37,7 +37,7 @@ msgstr "\"{docName}\" doesn't exist."
msgid "\"{docName}\" took too long. Check your connection."
msgstr "\"{docName}\" took too long. Check your connection."
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "\"{trimmed}\" already exists here"
msgstr "\"{trimmed}\" already exists here"
@@ -443,6 +443,10 @@ msgstr "A short line shown under the name in the template list."
msgid "A template named <0>{trimmedSlug}</0> already exists here. Saving creates a local copy that overrides it for this folder."
msgstr "A template named <0>{trimmedSlug}</0> already exists here. Saving creates a local copy that overrides it for this folder."
+#: src/components/FolderPropertiesCard.tsx
+msgid "A title, description, tags — anything that describes this folder."
+msgstr "A title, description, tags — anything that describes this folder."
+
#: src/editor/slash-command/items.tsx
msgid "Above"
msgstr "Above"
@@ -487,7 +491,7 @@ msgstr "Add"
#~ msgid "Add a blank field"
#~ msgstr "Add a blank field"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Add a property"
msgstr "Add a property"
@@ -2169,7 +2173,7 @@ msgstr "Failed to load file"
msgid "Failed to load file (HTTP {status})"
msgstr "Failed to load file (HTTP {status})"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Failed to load folder properties: {message}"
msgstr "Failed to load folder properties: {message}"
@@ -2429,7 +2433,7 @@ msgstr "Folder name"
msgid "Folder name: {detail}"
msgstr "Folder name: {detail}"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Folder properties"
msgstr "Folder properties"
@@ -3252,7 +3256,7 @@ msgstr "Name can’t be empty, \".\", \"..\", or contain / or \\"
msgid "Name cannot be empty"
msgstr "Name cannot be empty"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
#: src/components/PropertyPanel.tsx
msgid "Name is required"
msgstr "Name is required"
@@ -3591,7 +3595,7 @@ msgstr "Not detected"
msgid "Not installed"
msgstr "Not installed"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr "Nothing set yet."
@@ -4296,6 +4300,10 @@ msgstr "Properties"
#~ msgid "Properties that describe this folder itself — any properties you like, just like a doc's. They don't flow into the docs inside it; to give new docs starting properties, add a template."
#~ msgstr "Properties that describe this folder itself — any properties you like, just like a doc's. They don't flow into the docs inside it; to give new docs starting properties, add a template."
+#: src/components/FolderPropertiesCard.tsx
+#~ msgid "Properties that describe this folder."
+#~ msgstr "Properties that describe this folder."
+
#: src/components/PropertyPanel.tsx
msgid "Property \"{trimmed}\" already exists"
msgstr "Property \"{trimmed}\" already exists"
@@ -4464,7 +4472,7 @@ msgstr "Remove {projectName} from recent projects"
msgid "Remove {tag}"
msgstr "Remove {tag}"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Remove failed: {error}"
msgstr "Remove failed: {error}"
@@ -4696,7 +4704,7 @@ msgstr "Save"
msgid "Save changes"
msgstr "Save changes"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Save failed: {error}"
msgstr "Save failed: {error}"
@@ -5847,7 +5855,7 @@ msgstr "Use letters, digits, <0>-</0> or <1>_</1> only."
msgid "User"
msgstr "User"
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Value is required"
msgstr "Value is required"
@@ -5932,9 +5940,9 @@ msgstr "What is this knowledge base for?"
#~ msgid "What should the AI do? (optional)"
#~ msgstr "What should the AI do? (optional)"
-#: src/components/FolderDefaultsCard.tsx
-msgid "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
-msgstr "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
+#: src/components/FolderPropertiesCard.tsx
+#~ msgid "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
+#~ msgstr "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
#: src/components/settings/SettingsDialogBody.tsx
msgid "When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 544a730b2..029368954 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -1272,6 +1272,7 @@
],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
"ehLu5O": ["Ōƥēń ĩń Ţēŕḿĩńàĺ, ", ["hint"]],
+ "eiXVx8": ["Ƥŕōƥēŕţĩēś ţĥàţ ďēśćŕĩƀē ţĥĩś ƒōĺďēŕ."],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
"ensWZc": ["ōŕ śţàŕţ ƒŕōḿ śćŕàţćĥ <0/>"],
"euc6Ns": ["Ďũƥĺĩćàţē"],
@@ -1352,6 +1353,7 @@
"hGmuTc": ["Ďōćś ţàĝĝēď #", ["tagDocsName"]],
"hHMv6l": ["Ďēĺēţē ƀĺōćķ"],
"hJu2pH": ["Ţĥĩś ƒōĺďēŕ àĺŕēàďŷ ĥàś ƒĩĺēś. Àďď à ńàḿē ţō ćŕēàţē à ńēŵ śũƀƒōĺďēŕ ĩńśĩďē ĩţ."],
+ "hSBIG-": ["À ţĩţĺē, ďēśćŕĩƥţĩōń, ţàĝś — àńŷţĥĩńĝ ţĥàţ ďēśćŕĩƀēś ţĥĩś ƒōĺďēŕ."],
"hSySVc": ["Ĩńśţàĺĺ ĥàńďōƒƒ ƒàĩĺēď: ", ["msg"]],
"hXUWyd": ["Vàĺũē ĩś ŕēǫũĩŕēď"],
"hXbSxc": ["Àśśēţ: ", ["title"]],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index cdf878487..98ef89634 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -37,7 +37,7 @@ msgstr ""
msgid "\"{docName}\" took too long. Check your connection."
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "\"{trimmed}\" already exists here"
msgstr ""
@@ -438,6 +438,10 @@ msgstr ""
msgid "A template named <0>{trimmedSlug}</0> already exists here. Saving creates a local copy that overrides it for this folder."
msgstr ""
+#: src/components/FolderPropertiesCard.tsx
+msgid "A title, description, tags — anything that describes this folder."
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Above"
msgstr ""
@@ -482,7 +486,7 @@ msgstr ""
#~ msgid "Add a blank field"
#~ msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Add a property"
msgstr ""
@@ -2164,7 +2168,7 @@ msgstr ""
msgid "Failed to load file (HTTP {status})"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Failed to load folder properties: {message}"
msgstr ""
@@ -2424,7 +2428,7 @@ msgstr ""
msgid "Folder name: {detail}"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Folder properties"
msgstr ""
@@ -3247,7 +3251,7 @@ msgstr ""
msgid "Name cannot be empty"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
#: src/components/PropertyPanel.tsx
msgid "Name is required"
msgstr ""
@@ -3586,7 +3590,7 @@ msgstr ""
msgid "Not installed"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Nothing set yet."
msgstr ""
@@ -4291,6 +4295,10 @@ msgstr ""
#~ msgid "Properties that describe this folder itself — any properties you like, just like a doc's. They don't flow into the docs inside it; to give new docs starting properties, add a template."
#~ msgstr ""
+#: src/components/FolderPropertiesCard.tsx
+#~ msgid "Properties that describe this folder."
+#~ msgstr ""
+
#: src/components/PropertyPanel.tsx
msgid "Property \"{trimmed}\" already exists"
msgstr ""
@@ -4459,7 +4467,7 @@ msgstr ""
msgid "Remove {tag}"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Remove failed: {error}"
msgstr ""
@@ -4691,7 +4699,7 @@ msgstr ""
msgid "Save changes"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Save failed: {error}"
msgstr ""
@@ -5842,7 +5850,7 @@ msgstr ""
msgid "User"
msgstr ""
-#: src/components/FolderDefaultsCard.tsx
+#: src/components/FolderPropertiesCard.tsx
msgid "Value is required"
msgstr ""
@@ -5927,9 +5935,9 @@ msgstr ""
#~ msgid "What should the AI do? (optional)"
#~ msgstr ""
-#: src/components/FolderDefaultsCard.tsx
-msgid "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
-msgstr ""
+#: src/components/FolderPropertiesCard.tsx
+#~ msgid "What this folder is about — give it a title, description, tags, or any properties you like, just like a doc has. This describes the folder itself; it is not copied into the docs inside it. To start new docs in this folder with a ready-made set of properties, add a template instead."
+#~ msgstr ""
#: src/components/settings/SettingsDialogBody.tsx
msgid "When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
diff --git a/packages/app/tests/integration/mcp-http.test.ts b/packages/app/tests/integration/mcp-http.test.ts
index 4fed35522..65894e4c2 100644
--- a/packages/app/tests/integration/mcp-http.test.ts
+++ b/packages/app/tests/integration/mcp-http.test.ts
@@ -66,14 +66,20 @@ test('POST /mcp serves MCP JSON-RPC over Streamable HTTP', async () => {
const toolNames = toolsBody.result?.tools?.map((tool) => tool.name) ?? [];
expect(toolNames).toContain('exec');
expect(toolNames).toContain('search');
- expect(toolNames).toContain('write_document');
- expect(toolNames).toContain('edit_frontmatter');
+ expect(toolNames).toContain('write');
+ expect(toolNames).toContain('edit');
+ expect(toolNames).toContain('delete');
+ expect(toolNames).toContain('move');
expect(toolNames).toContain('links');
- expect(toolNames).toContain('rename');
- expect(toolNames).toContain('version');
- expect(toolNames).toContain('folder_config');
+ expect(toolNames).toContain('checkpoint');
+ expect(toolNames).toContain('restore_version');
+ expect(toolNames).toContain('conflicts');
+ expect(toolNames).toContain('palette');
expect(toolNames).not.toContain('read_document');
- expect(toolNames).not.toContain('frontmatter_patch');
+ expect(toolNames).not.toContain('write_document');
+ expect(toolNames).not.toContain('folder_config');
+ expect(toolNames).not.toContain('version');
+ expect(toolNames).not.toContain('list_conflicts');
} finally {
await server.cleanup();
}
diff --git a/packages/app/tests/integration/mcp-rename-real-roundtrip.test.ts b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
similarity index 92%
rename from packages/app/tests/integration/mcp-rename-real-roundtrip.test.ts
rename to packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
index 75dd539d9..f55f82b7f 100644
--- a/packages/app/tests/integration/mcp-rename-real-roundtrip.test.ts
+++ b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ConfigSchema } from '@inkeep/open-knowledge-server';
-import { register as registerRename } from '../../../server/src/mcp/tools/rename';
+import { register as registerMove } from '../../../server/src/mcp/tools/move';
import type { ServerInstance } from '../../../server/src/mcp/tools/shared';
import { awaitFileWatcherIndexed, createRestartableServer } from './test-harness';
@@ -47,8 +47,8 @@ afterEach(async () => {
}
});
-describe('MCP rename tools — real roundtrip against live OK server (QA-004 / QA-005)', () => {
- test('QA-004: rename_folder posts to live /api/rename-path → folder + backlinks rewrite on disk', async () => {
+describe('MCP move tool — real roundtrip against live OK server (QA-004 / QA-005)', () => {
+ test('QA-004: move (folder) posts to live /api/rename-path → folder + backlinks rewrite on disk', async () => {
const server = await createRestartableServer();
cleanups.push(() => server.shutdown());
@@ -69,12 +69,12 @@ describe('MCP rename tools — real roundtrip against live OK server (QA-004 / Q
]);
const { server: mcp, registrations } = createCapturingServer();
- registerRename(mcp, {
+ registerMove(mcp, {
serverUrl: `http://localhost:${server.port}`,
config: BASE_CONFIG,
resolveCwd: async () => server.contentDir,
});
- const tool = getTool(registrations, 'rename');
+ const tool = getTool(registrations, 'move');
const result = await tool.handler({
from: 'articles',
@@ -108,7 +108,7 @@ describe('MCP rename tools — real roundtrip against live OK server (QA-004 / Q
expect(indexBody).not.toContain('[[articles/a]]');
}, 60_000);
- test('QA-005: rename_document posts to live /api/rename-path with kind:file → backlinks rewrite', async () => {
+ test('QA-005: move (document) posts to live /api/rename-path with kind:file → backlinks rewrite', async () => {
const server = await createRestartableServer();
cleanups.push(() => server.shutdown());
@@ -120,12 +120,12 @@ describe('MCP rename tools — real roundtrip against live OK server (QA-004 / Q
]);
const { server: mcp, registrations } = createCapturingServer();
- registerRename(mcp, {
+ registerMove(mcp, {
serverUrl: `http://localhost:${server.port}`,
config: BASE_CONFIG,
resolveCwd: async () => server.contentDir,
});
- const tool = getTool(registrations, 'rename');
+ const tool = getTool(registrations, 'move');
const result = await tool.handler({
from: 'auth',
diff --git a/packages/app/tests/integration/mcp-session-identity.test.ts b/packages/app/tests/integration/mcp-session-identity.test.ts
index 41cc7e622..ee73aa2c8 100644
--- a/packages/app/tests/integration/mcp-session-identity.test.ts
+++ b/packages/app/tests/integration/mcp-session-identity.test.ts
@@ -81,7 +81,17 @@ async function callWriteDocument(
jsonrpc: '2.0',
id: rpcId,
method: 'tools/call',
- params: { name: 'write_document', arguments: args },
+ params: {
+ name: 'write',
+ arguments: {
+ document: {
+ path: args.docName,
+ content: args.markdown,
+ ...(args.position ? { position: args.position } : {}),
+ },
+ ...(args.cwd ? { cwd: args.cwd } : {}),
+ },
+ },
}),
});
expect(res.status).toBe(200);
diff --git a/packages/cli/src/config/loader.test.ts b/packages/cli/src/config/loader.test.ts
index 0691fd2b0..00826a9f0 100644
--- a/packages/cli/src/config/loader.test.ts
+++ b/packages/cli/src/config/loader.test.ts
@@ -211,7 +211,7 @@ appearance:
const msg = caught?.message ?? '';
expect(msg).toContain('folders');
expect(msg).toContain('.ok/');
- expect(msg).toContain('folder_config');
+ expect(msg).toContain('edit({ folder');
const expectedPath = resolve(testDir, OK_DIR, 'config.yml');
expect(msg).toMatch(new RegExp(`${expectedPath.replace(/[/\\.]/g, '\\$&')}:\\d+:\\d+`));
});
diff --git a/packages/core/src/config/removed-keys.ts b/packages/core/src/config/removed-keys.ts
index d54b018cb..b70945bfe 100644
--- a/packages/core/src/config/removed-keys.ts
+++ b/packages/core/src/config/removed-keys.ts
@@ -32,7 +32,7 @@ export const REMOVED_KEYS: readonly RemovedKey[] = [
redirect: [
'folders is no longer a top-level config field.',
"A folder's own frontmatter (open-shape, like a doc's) lives in nested `<folder>/.ok/frontmatter.yml`; new-doc starting properties come from templates in `<folder>/.ok/templates/`.",
- 'Edit via the folder overview in the editor sidebar, or the `folder_config` MCP tool.',
+ 'Edit via the folder overview in the editor sidebar, or `edit({ folder: { path, frontmatter } })` via the MCP.',
MIGRATE_HINT,
].join(' '),
},
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index d8a90b9b3..2abdc3a8f 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -1,5 +1,4 @@
import { z } from 'zod';
-import { FrontmatterPatchSchema } from '../frontmatter/schema.ts';
import { fieldRegistry } from './field-registry.ts';
export const DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST: readonly string[] = Object.freeze([
@@ -16,15 +15,6 @@ export const DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST: readonly string[] = Object.fr
export const DEFAULT_SPANS_MAX_BYTES = 52_428_800;
export const DEFAULT_LOGS_MAX_BYTES = 26_214_400;
-export const FolderRuleSchema = z.looseObject({
- match: z
- .string()
- .min(1, "`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),
- frontmatter: FrontmatterPatchSchema,
-});
-
-export type FolderRule = z.infer<typeof FolderRuleSchema>;
-
export const ConfigSchema = z.looseObject({
content: z
.looseObject({
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e24a6691b..ce580297e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -122,8 +122,6 @@ export {
DEFAULT_LOGS_MAX_BYTES,
DEFAULT_SPANS_MAX_BYTES,
DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,
- type FolderRule,
- FolderRuleSchema,
} from './config/schema.ts';
export { getLeafFieldMeta, resolveLeafSchema } from './config/schema-leaf.ts';
export { CONFIG_SCHEMA_MAJOR, CONFIG_SCHEMA_MAJOR_PATH } from './config/schema-version.ts';
@@ -628,12 +626,8 @@ export {
RenamePathRequestSchema,
type RenamePathSuccess,
RenamePathSuccessSchema,
- type RenameRequest,
- RenameRequestSchema,
type RenameRewrittenDoc,
RenameRewrittenDocSchema,
- type RenameSuccess,
- RenameSuccessSchema,
type RescueEntryFlat,
RescueEntryFlatSchema,
type RescueEntryTimeline,
diff --git a/packages/core/src/registry/projection.test.ts b/packages/core/src/registry/projection.test.ts
index e14b2c654..dc229972d 100644
--- a/packages/core/src/registry/projection.test.ts
+++ b/packages/core/src/registry/projection.test.ts
@@ -159,9 +159,9 @@ describe('renderInventoryFooter (FR-1)', () => {
expect(text).not.toContain('`MermaidFence`');
});
- test('carries the look-up pointer to get_components', () => {
+ test('carries the look-up pointer to palette', () => {
const text = renderInventoryFooter();
- expect(text).toContain('get_components');
+ expect(text).toContain('palette');
});
test('mentions fenced code blocks as a separate authoring path (not a component)', () => {
diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.ts
index c3ea70ed6..600f63382 100644
--- a/packages/core/src/registry/projection.ts
+++ b/packages/core/src/registry/projection.ts
@@ -188,7 +188,7 @@ export function renderInventoryFooter(): string {
const lines = lite.map((entry) => `- \`${entry.id}\` (${entry.kind}) — ${entry.description}`);
return [
'',
- "**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `get_components({ ids })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `get_authoring_palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader's light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",
+ "**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `palette({ components: [ids] })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader's light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",
'',
...lines,
].join('\n');
diff --git a/packages/core/src/schemas/api/_shared.ts b/packages/core/src/schemas/api/_shared.ts
index 0c0658d23..4f6da3cb7 100644
--- a/packages/core/src/schemas/api/_shared.ts
+++ b/packages/core/src/schemas/api/_shared.ts
@@ -10,8 +10,6 @@ function checkDocName(value: string, ctx: z.RefinementCtx): void {
export const safeDocNameField = z.string().superRefine(checkDocName).optional();
-export const requiredSafeDocNameField = z.string().min(1).superRefine(checkDocName);
-
export const agentIdentityFields = {
agentId: z.string().optional(),
agentName: z.string().optional(),
diff --git a/packages/core/src/schemas/api/history.ts b/packages/core/src/schemas/api/history.ts
index b226e1aab..2fcd288fe 100644
--- a/packages/core/src/schemas/api/history.ts
+++ b/packages/core/src/schemas/api/history.ts
@@ -1,7 +1,7 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
-import { agentIdentityFields } from './_shared.ts';
+import { agentIdentityFields, summaryField } from './_shared.ts';
export const SaveVersionWriterSchema = z
.object({
@@ -15,6 +15,7 @@ export type SaveVersionWriter = z.infer<typeof SaveVersionWriterSchema>;
export const SaveVersionRequestSchema = z
.object({
writers: z.array(SaveVersionWriterSchema).optional(),
+ summary: summaryField,
...agentIdentityFields,
})
.loose() satisfies StandardSchemaV1;
diff --git a/packages/core/src/schemas/api/pages.test.ts b/packages/core/src/schemas/api/pages.test.ts
index bbec1d3a2..b31cebbbf 100644
--- a/packages/core/src/schemas/api/pages.test.ts
+++ b/packages/core/src/schemas/api/pages.test.ts
@@ -17,9 +17,7 @@ import {
RenamedDocMappingSchema,
RenamePathRequestSchema,
RenamePathSuccessSchema,
- RenameRequestSchema,
RenameRewrittenDocSchema,
- RenameSuccessSchema,
RollbackRequestSchema,
RollbackSuccessSchema,
TrashCleanupRequestSchema,
@@ -216,38 +214,6 @@ describe('HeadingEntrySchema and PageHeadingsSuccessSchema', () => {
});
});
-describe('RenameRequestSchema', () => {
- test('parses a valid rename', () => {
- const result = RenameRequestSchema.safeParse({ docName: 'a', newDocName: 'b' });
- expect(result.success).toBe(true);
- });
- test('rejects empty docName', () => {
- expect(RenameRequestSchema.safeParse({ docName: '', newDocName: 'b' }).success).toBe(false);
- });
- test('rejects empty newDocName', () => {
- expect(RenameRequestSchema.safeParse({ docName: 'a', newDocName: '' }).success).toBe(false);
- });
- test('rejects structurally-invalid newDocName (same contract as the write path)', () => {
- for (const newDocName of ['.foo', 'a/', ' leading', 'x\ty', '..']) {
- expect(RenameRequestSchema.safeParse({ docName: 'a', newDocName }).success).toBe(false);
- }
- });
- test('accepts optional summary', () => {
- expect(
- RenameRequestSchema.safeParse({
- docName: 'a',
- newDocName: 'b',
- summary: 'optional summary',
- }).success,
- ).toBe(true);
- });
- test('rejects non-string summary', () => {
- expect(
- RenameRequestSchema.safeParse({ docName: 'a', newDocName: 'b', summary: 42 }).success,
- ).toBe(false);
- });
-});
-
describe('RenameRewrittenDocSchema', () => {
test('parses a valid entry', () => {
expect(RenameRewrittenDocSchema.safeParse({ docName: 'a', rewrites: 5 }).success).toBe(true);
@@ -257,21 +223,6 @@ describe('RenameRewrittenDocSchema', () => {
});
});
-describe('RenameSuccessSchema', () => {
- test('parses success with no rewrites', () => {
- expect(RenameSuccessSchema.safeParse({ renamed: [], rewrittenDocs: [] }).success).toBe(true);
- });
- test('parses success with summary', () => {
- expect(
- RenameSuccessSchema.safeParse({
- renamed: [{ fromDocName: 'a', toDocName: 'b' }],
- rewrittenDocs: [{ docName: 'c', rewrites: 1 }],
- summary: { value: 'Renamed a → b' },
- }).success,
- ).toBe(true);
- });
-});
-
describe('RenamePathRequestSchema', () => {
test('parses a valid file rename', () => {
expect(
diff --git a/packages/core/src/schemas/api/pages.ts b/packages/core/src/schemas/api/pages.ts
index 4f92abed8..8813af26b 100644
--- a/packages/core/src/schemas/api/pages.ts
+++ b/packages/core/src/schemas/api/pages.ts
@@ -1,6 +1,6 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
-import { agentIdentityFields, requiredSafeDocNameField, summaryField } from './_shared.ts';
+import { agentIdentityFields, summaryField } from './_shared.ts';
import { ContentDivergenceWarningSchema, SummaryResponseFieldSchema } from './agent-write.ts';
export const RenamedDocMappingSchema = z
@@ -109,16 +109,6 @@ export const PageHeadingsSuccessSchema = z
.loose() satisfies StandardSchemaV1;
export type PageHeadingsSuccess = z.infer<typeof PageHeadingsSuccessSchema>;
-export const RenameRequestSchema = z
- .object({
- docName: requiredSafeDocNameField,
- newDocName: requiredSafeDocNameField,
- summary: summaryField,
- ...agentIdentityFields,
- })
- .loose() satisfies StandardSchemaV1;
-export type RenameRequest = z.infer<typeof RenameRequestSchema>;
-
export const RenameRewrittenDocSchema = z
.object({
docName: z.string().min(1),
@@ -127,15 +117,6 @@ export const RenameRewrittenDocSchema = z
.loose() satisfies StandardSchemaV1;
export type RenameRewrittenDoc = z.infer<typeof RenameRewrittenDocSchema>;
-export const RenameSuccessSchema = z
- .object({
- renamed: z.array(RenamedDocMappingSchema),
- rewrittenDocs: z.array(RenameRewrittenDocSchema),
- summary: SummaryResponseFieldSchema.optional(),
- })
- .loose() satisfies StandardSchemaV1;
-export type RenameSuccess = z.infer<typeof RenameSuccessSchema>;
-
export const RenamePathRequestSchema = z
.object({
kind: z.enum(['file', 'folder', 'asset']),
diff --git a/packages/server/assets/skills/packs/entity-vault/SKILL.md b/packages/server/assets/skills/packs/entity-vault/SKILL.md
index a2ea6c7a6..65b5a4ecd 100644
--- a/packages/server/assets/skills/packs/entity-vault/SKILL.md
+++ b/packages/server/assets/skills/packs/entity-vault/SKILL.md
@@ -45,4 +45,4 @@ This pack ships the Markdown half (folders + templates + this skill); OK is the
## Templates
-Create with `write_document({ template: "<name>", … })`. Templates carry the structure (including the compiled-truth / `--- timeline ---` separator) plus short inline reminders at the point of use; this skill holds the full convention, so prefer it as the canonical reference if the two ever disagree.
+Create with `write({ document: { path: "<path>", template: "<name>" } })`. Templates carry the structure (including the compiled-truth / `--- timeline ---` separator) plus short inline reminders at the point of use; this skill holds the full convention, so prefer it as the canonical reference if the two ever disagree.
diff --git a/packages/server/assets/skills/packs/knowledge-base/SKILL.md b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
index cd2bfe552..dc70b32c3 100644
--- a/packages/server/assets/skills/packs/knowledge-base/SKILL.md
+++ b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
@@ -1,6 +1,6 @@
---
name: open-knowledge-pack-knowledge-base
-description: "How to work in a Knowledge Base project (the `knowledge-base` starter pack). Read when the project has the three-layer source-grounded layout — `external-sources/` → `research/` → `articles/` — wired to the ingest / research / consolidate MCP tools. Carries the pack's workflow, per-folder rules, status flows, and log discipline so this guidance does NOT live inside template bodies or log.md. Complements the platform `open-knowledge` skill; does not replace it."
+description: "How to work in a Knowledge Base project (the `knowledge-base` starter pack). Read when the project has the three-layer source-grounded layout — `external-sources/` → `research/` → `articles/` — wired to the `workflow` MCP tool's ingest / research / consolidate kinds. Carries the pack's workflow, per-folder rules, status flows, and log discipline so this guidance does NOT live inside template bodies or log.md. Complements the platform `open-knowledge` skill; does not replace it."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server. Installed project-local by `ok seed --pack knowledge-base`."
metadata:
pack: "knowledge-base"
@@ -23,7 +23,7 @@ research/ provisional analysis (produced by `research`)
articles/ canonical, decided knowledge (produced by `consolidate`)
```
-The loop is **ingest → research → consolidate**. Every downstream claim traces upstream to a preserved source. Cite local paths in `external-sources/`, never bare web URLs — the KB must survive link rot.
+The loop is **ingest → research → consolidate** — each a `workflow({ kind })` guide you invoke (`workflow({ kind: 'ingest' })`, etc.). Every downstream claim traces upstream to a preserved source. Cite local paths in `external-sources/`, never bare web URLs — the KB must survive link rot.
## Per-folder rules
@@ -46,7 +46,7 @@ When a new article supersedes an older one, add the older article's path to the
There is a `log.md` at the project root. **Append one dated entry after any turn that creates, edits, or restructures content** — one entry per turn, not per file. Silent edits break the audit trail.
-Log: `ingest` runs (new sources), `research` / `consolidate` runs (provisional or canonical articles), direct `write_document` / `edit_document` / rename / delete outside the three loop tools, `discover` runs, folder restructures, and `.ok/config.yml` changes.
+Log: `ingest` runs (new sources), `research` / `consolidate` runs (provisional or canonical articles), direct `write` / `edit` / `move` / `delete` outside the three loop tools, `discover` runs, folder restructures, and `.ok/config.yml` changes.
**Reference docs as markdown links, not bare paths** — `[path/to/doc](./path/to/doc.md)`, so the entry shows up in `links({ kind: "backlinks" })` for those docs. A bare path string does not register in the graph.
@@ -63,4 +63,4 @@ Entry shape:
## Templates
-Each folder has a starter template (`clip`, `research-log`, `article`). Create with `write_document({ template: "<name>", docName, … })`. Templates carry only structure (headings + frontmatter scaffold) — the meaning of each field and section is described above, not repeated inside the document body.
+Each folder has a starter template (`clip`, `research-log`, `article`). Create with `write({ document: { path, template: "<name>" } })`. Templates carry only structure (headings + frontmatter scaffold) — the meaning of each field and section is described above, not repeated inside the document body.
diff --git a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
index 0058e0c0a..bfeebc722 100644
--- a/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
+++ b/packages/server/assets/skills/packs/software-lifecycle/SKILL.md
@@ -40,4 +40,4 @@ guides/ how-to / onboarding / runbooks (referenced throughout)
## Templates
-Create docs with `write_document({ template: "<name>", … })`. Templates carry only structure (headings + frontmatter scaffold); what each section is for is described above, not repeated in the document body.
+Create docs with `write({ document: { path, template: "<name>" } })`. Templates carry only structure (headings + frontmatter scaffold); what each section is for is described above, not repeated in the document body.
diff --git a/packages/server/assets/skills/packs/worldbuilding/SKILL.md b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
index c541c0f65..ba391591f 100644
--- a/packages/server/assets/skills/packs/worldbuilding/SKILL.md
+++ b/packages/server/assets/skills/packs/worldbuilding/SKILL.md
@@ -30,4 +30,4 @@ This project is a fiction encyclopedia. The graph is the product: characters, se
## Templates
-Create with `write_document({ template: "<name>", … })`. Templates carry only structure; section meaning is described here, not inside the document body.
+Create with `write({ document: { path, template: "<name>" } })`. Templates carry only structure; section meaning is described here, not inside the document body.
diff --git a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
index 3af0e540f..0374f4b5f 100644
--- a/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
+++ b/packages/server/assets/skills/packs/writing-pipeline/SKILL.md
@@ -27,4 +27,4 @@ published/ shipped work; treat as immutable
## Templates
-Create with `write_document({ template: "<name>", … })`. Templates carry only structure; section meaning lives here, not in the document body.
+Create with `write({ document: { path, template: "<name>" } })`. Templates carry only structure; section meaning lives here, not in the document body.
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 379222810..679994448 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -1,6 +1,6 @@
---
name: open-knowledge
-description: "MUST invoke before reading or editing any `.md` / `.mdx` file, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write_document`, `edit_document`, and the rest). This skill is installed into the repository by `ok init`, so its presence alone means this is an Open Knowledge project — its runtime contract governs every markdown file here, with no need to probe for a `.ok/` directory. Authoritative agent-runtime contract; supersedes the overlapping MCP server `instructions` echo."
+description: "MUST invoke before reading or editing any `.md` / `.mdx` file, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, and the rest). This skill is installed into the repository by `ok init`, so its presence alone means this is an Open Knowledge project — its runtime contract governs every markdown file here, with no need to probe for a `.ok/` directory. Authoritative agent-runtime contract; supersedes the overlapping MCP server `instructions` echo."
compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
metadata:
version: "0.9.1"
@@ -18,20 +18,27 @@ Open Knowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. T
## TL;DR — the 90% case
1. **Reads:** `exec("cat …")` for a single doc, `exec("ls -A …")` for a directory (with 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` for new or full-replace, `edit_document` for body-only find/replace, `edit_frontmatter` for 1-2 frontmatter keys (JSON Merge Patch — preferred). Full frontmatter rewrites use `write_document({ position: "replace" })`. `edit_document` rejects frontmatter (HTTP 400). Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write — it's the timeline change-note (see §Writing).
-3. **Preview:** every OK read/write response carries a route-only `previewUrl` (`/#/<doc>`, no host:port). If you have a `preview_*` tool, call `preview_start("open-knowledge-ui")`; if you have an in-app browser, call `get_preview_url` once for the full browser URL and navigate to it; on the Claude Code CLI (no browser tool), run `ok open <doc>` to open it in the OK Desktop app. Surface to the user on a `start-ui` warning (no UI running). Don't `preview_screenshot` to confirm edits — the CRDT tool response is the confirmation.
-4. **Workflow tools** (`ingest` / `research` / `consolidate` / `discover`) return procedural guides, not data. Use them when the work fits the layer; follow their numbered steps.
+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 — frontmatter goes through the `frontmatter` patch. Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write — it's the timeline change-note (see §Writing).
+3. **Preview:** every OK read/write response carries a route-only `previewUrl` (`/#/<doc>`, no host:port). If you have a `preview_*` tool, call `preview_start("open-knowledge-ui")`; if you have an in-app browser, call `preview_url` once for the full browser URL and navigate to it; on the Claude Code CLI (no browser tool), run `ok open <doc>` to open it in the OK Desktop app. Surface to the user on a `start-ui` warning (no UI running). Don't `preview_screenshot` to confirm edits — the CRDT tool response is the confirmation.
+4. **Workflow guides** — `workflow({ kind: 'ingest' | 'research' | 'consolidate' | 'discover' })` returns a procedural guide, not data. Use it when the work fits the layer; follow the numbered steps.
Everything below is depth. Read on demand.
-## Tool index — 23 tools
+## Tool index — 17 tools
The full MCP surface, grouped by risk-level. Every tool's `kind` / `action` set is single-risk-level (never a read and a write behind one discriminator).
-- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `get_history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`), `get_config` (resolved config), `get_components` (canonical component JSX schemas), `get_authoring_palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens), `get_preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc or folder; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).
-- **Writes** — `write_document` (new or full-replace; supports `template:` instantiation), `edit_document` (body-only find/replace), `edit_frontmatter` (1-2 keys via RFC 7396 JSON Merge Patch — preferred), `delete_document`, `rename` (probes file vs folder; rewrites referrers), `version` (`action: 'save'|'rollback'`), `folder_config` (`action: 'set-rule'|'write-template'|'delete-template'`). `set-rule` writes a folder's own frontmatter (open-shape, like a doc's); `write-template`/`delete-template` manage the folder's templates (what new docs start with).
-- **GitHub-sync conflicts** — `list_conflicts` (enumerate), `get_conflict_content` (base/ours/theirs stages + lifecycle), `resolve_conflict` (write a chosen resolution + commit; destructive). Mutating writes against a doc in conflict return RFC 9457 `urn:ok:error:doc-in-conflict` (409); `exec("cat …")` returns `lifecycle: {status, reason} | null` so you can detect the state proactively. See *Conflict-aware writes*.
-- **Workflow** — `ingest`, `research`, `consolidate`, `discover` (return procedural guides, not data).
+- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`, or an array of those for a one-call audit, e.g. `links({ kind: ["dead", "orphans", "hubs"] })`), `config` (resolved config), `palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens; pass `components` for the canonical component JSX schemas), `preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc or folder; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).
+- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `asset` (Pattern B: per-target fields nested inside the address key; pass EXACTLY ONE target):
+ - `write` — create/overwrite a `document` (supports `document.template` instantiation), create a `folder` (with open-shape frontmatter), create a `template`, or upload an `asset`.
+ - `edit` — modify a `document` (body find/replace OR frontmatter merge-patch), a `folder` (frontmatter merge-patch), or a `template`. (No asset — binary has no text body.)
+ - `delete` — remove a `document` (name or array), `folder`, `template`, or `asset`.
+ - `move` — move/rename a `document`, `folder`, or `asset`; rewrites referrers.
+ The OUTPUT mirrors the input: `write`/`edit`/`delete` nest their result under the same target key you passed (`{ document: {…} }` / `{ folder: {…} }` / `{ template: {…} }` / `{ asset: {…} }`, or `{ documents: [...] }` for a batch). The preview envelope (`previewUrl`, `warning`, `previousPreviewUrl`) stays at the top level — same for every tool.
+ Plus `checkpoint` (save a named version) and `restore_version` (roll a doc back to a prior version). A folder's own frontmatter is open-shape exactly like a doc's (self-only, does NOT cascade into child docs); templates are what new docs in a folder start with.
+ **Self-correcting on misuse:** the few constraints JSON Schema can't express — "pass exactly one target", "`find` needs a `replace`", body-XOR-frontmatter — are enforced by a *teaching error*: a wrong call returns `isError: true` with a one-line message naming the exact corrective shape. Read it and retry with that shape; don't guess.
+- **GitHub-sync conflicts** — `conflicts` (`kind: 'list'` to enumerate, `kind: 'content'` for base/ours/theirs stages + lifecycle), `resolve_conflict` (write a chosen resolution + commit; destructive). Mutating writes against a doc in conflict return RFC 9457 `urn:ok:error:doc-in-conflict` (409); `exec("cat …")` returns `lifecycle: {status, reason} | null` so you can detect the state proactively. See *Conflict-aware writes*.
+- **Workflow** — `workflow` (`kind: 'ingest' | 'research' | 'consolidate' | 'discover'`; returns procedural guides, not data).
Tools NOT in OK MCP (they belong to your agent host): `preview_start`, `preview_screenshot`, `WebFetch`, `WebSearch`, native `Read` / `Grep` / `Glob` / `Edit`. The STOP rule below governs which of those you may use on in-scope markdown.
@@ -45,7 +52,7 @@ When this workspace has Open Knowledge MCP configured, do **not** use your host'
- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.
- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.
-Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK's tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.
+Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK's tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`) and returns raw stdout plus enriched metadata per file. One command or a pipe (`|`) per call — it is NOT a shell, so `&&` / `;` / redirects are rejected; list several dirs with `ls -A a b c` or make separate calls.
**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client's documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.
@@ -70,10 +77,10 @@ The user watches your edits land in a live browser preview. Open it once at sess
**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.
-- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `get_preview_url({ armPaneTarget: true, docName })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target's route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = '#/specs/foo/SPEC'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can't move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don't read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don't "fix" `launch.json`.
-- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex's built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `get_preview_url` once for the **exact** target (`docName` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.
-- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.
-- **Honor `autoOpen`** (on `get_preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.
+- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target's route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = '#/specs/foo/SPEC'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can't move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don't read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don't "fix" `launch.json`.
+- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex's built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.
+- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.
+- **Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.
**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc's `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.
@@ -81,12 +88,12 @@ The user watches your edits land in a live browser preview. Open it once at sess
1. You opened/navigated earlier this session → don't reopen.
2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.
-3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).
+3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `preview_url` → in-app browser).
4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don't loop on retries.
Warnings fire at most once per session in the fresh-start case.
-**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don't carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.
+**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don't carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` reports `running: false` + `url: null` when no UI is running.
If you see `"Hocuspocus server is not running"`, run `ok start` and retry.
@@ -98,17 +105,19 @@ OK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port
## Writing
-Call `write_document` / `edit_document` as soon as you have content. Native `Edit` / `sed` / direct `Write` on in-scope markdown is forbidden — it bypasses the CRDT and loses agent attribution in the shadow repo.
+Call `write` / `edit` as soon as you have content. Native `Edit` / `sed` / direct `Write` on in-scope markdown is forbidden — it bypasses the CRDT and loses agent attribution in the shadow repo.
-**Pass a `summary` on every content write (SHOULD).** `write_document`, `edit_document`, and `edit_frontmatter` each take a one-line `summary` (≤80 chars) describing the user-facing outcome of the change — "Add gear list and permit info", not "edited trip doc". It renders as a bullet under your name in the document timeline and is the only human-readable change-note persisted to the shadow-repo history; omit it and the timeline shows *that* you wrote but not *what changed*. Write it from the reader's perspective, keep it specific, and avoid secrets or PII (it lands in git history). Each entry in the batch `docs:` form carries its own `summary`.
+**Pass a `summary` on every content write (SHOULD).** `write`, `edit`, and `move` each take a one-line `summary` (≤80 chars) describing the user-facing outcome of the change — "Add gear list and permit info", not "edited trip doc". It renders as a bullet under your name in the document timeline and is the only human-readable change-note persisted to the shadow-repo history; omit it and the timeline shows *that* you wrote but not *what changed*. Write it from the reader's perspective, keep it specific, and avoid secrets or PII (it lands in git history). Each entry in the batch `documents:` form carries its own `summary`.
-**Content-divergence warning (Site A gate).** `write_document` and `edit_document` responses may include a content-divergence warning when the converged Y.Text doesn't match the bytes the payload composed to (concurrent peer left residue, or — rare — a primitive regression). The write still landed; on this signal, re-read the doc (`exec("cat <path>")`) to see what actually converged before continuing. Single-doc shape: `structuredContent.contentDivergence = { kind: "content-divergence", intendedBytes, actualBytes, byteDelta, hint }`. Batch shape: per-doc `structuredContent.documents[].contentDivergence` with the same fields. Distinct from the preview-attach `warning` field (`action: "attach-preview-once" | "start-ui"`) — separate keys, can coexist.
+**Reach for visual structure where it aids comprehension.** Default to the right OK primitive over flat prose: a Callout (`> [!NOTE]`) for a key caveat, a ` ```mermaid ` diagram for a process or relationship, a table for options or comparisons, an `html preview` chart for numbers. **Call the `palette` MCP tool as you draft** (and `palette({ components })` for a canonical's JSX schema) — it returns copy-ready markdown-native forms, themed `html preview` embed starters, and the theme tokens, so the visual lands themed and in the content graph instead of hand-rolled. Don't decorate — use a visual only when it carries the point better than prose would. Full catalog: §Components.
-To author an MDX doc (the KB renders MDX/JSX components), pass a `.mdx` `docName` on the create: `write_document({ docName: "guides/widget.mdx", markdown, position: "replace" })` lands `guides/widget.mdx`. A `.md` or extension-less `docName` lands `.md`. An existing doc keeps its on-disk extension regardless of the suffix you pass — changing it in place isn't available via the MCP today.
+**Content-divergence warning (Site A gate).** `write` and `edit` responses may include a content-divergence warning when the converged Y.Text doesn't match the bytes the payload composed to (concurrent peer left residue, or — rare — a primitive regression). The write still landed; on this signal, re-read the doc (`exec("cat <path>")`) to see what actually converged before continuing. Single-doc shape: `structuredContent.document.contentDivergence = { kind: "content-divergence", intendedBytes, actualBytes, byteDelta, hint }` (the result nests under the `document` target key, mirroring the input). Batch shape: per-doc `structuredContent.documents[].contentDivergence` with the same fields. Distinct from the preview-attach `warning` field (`action: "attach-preview-once" | "start-ui"`), which stays at the top level — separate keys, can coexist.
-To delete a doc, call `delete_document` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible — call `version({ action: "save" })` first if you may need to roll back (restore via `version({ action: "rollback" })`; list snapshots via `get_history`), and `links({ kind: "backlinks", docName })` first if you want to fix referrers that will become redlinks. To move or rename a doc instead of delete + rewrite, use `rename({ from, to })` — it auto-detects file vs folder and rewrites incoming references atomically.
+To author an MDX doc (the KB renders MDX/JSX components), pass a `.mdx` path on the create: `write({ document: { path: "guides/widget.mdx", content, position: "replace" } })` lands `guides/widget.mdx`. A `.md` or extension-less path lands `.md`. An existing doc keeps its on-disk extension regardless of the suffix you pass — changing it in place isn't available via the MCP today.
-**If `edit_document` returns "Text not found" on text you can verify exists on disk** (via `exec("cat …")`), the MCP session is likely stale (e.g., after a folder rename or server restart). Treat this as the escape-hatch trigger from the STOP block: prefix your next user-visible sentence with `Open Knowledge MCP unavailable:` and report the inconsistency. Don't loop on retries — the symptom is structural, not transient.
+To delete a doc, call `delete({ document })` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible — call `checkpoint()` first if you may need to roll back (it snapshots the whole project; afterwards restore the doc via `restore_version({ document, version })`, finding the `version` in `history`), and `links({ kind: "backlinks", document })` first if you want to fix referrers that will become redlinks. To move or rename a doc instead of delete + rewrite, use `move({ from, to })` — it auto-detects document vs folder vs asset and rewrites incoming references atomically.
+
+**If `edit` returns "Text not found" on text you can verify exists on disk** (via `exec("cat …")`), the MCP session is likely stale (e.g., after a folder rename or server restart). Treat this as the escape-hatch trigger from the STOP block: prefix your next user-visible sentence with `Open Knowledge MCP unavailable:` and report the inconsistency. Don't loop on retries — the symptom is structural, not transient.
## Conflict-aware writes
@@ -119,23 +128,23 @@ Projects with GitHub sync enabled may carry docs in a merge-conflict state. The
"type": "urn:ok:error:doc-in-conflict",
"title": "Document is in conflict.",
"status": 409,
- "detail": "The document is in a merge-conflict state. Call get_conflict_content + resolve_conflict before retrying.",
+ "detail": "The document is in a merge-conflict state. Call conflicts({ kind: 'content' }) + resolve_conflict before retrying.",
"file": "notes/sso.md",
- "resolutionOptions": ["mine", "theirs", "content"]
+ "resolutionOptions": ["mine", "theirs", "content", "delete"]
}
```
-The gate covers `write_document`, `edit_document`, `delete_document`, `rename`, `version` (`action: 'rollback'`), `folder_config` (`action: 'write-template'|'delete-template'`), and agent undo. You cannot route around it by writing content that byte-matches one of the merge stages — the gate refuses on lifecycle state, not on body equality.
+The 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 merge stages — the gate refuses on lifecycle state, not on body equality.
**Detect proactively.** `exec("cat <path>.md")` always returns `lifecycle: {status, reason} | null` alongside the body. When `status === 'conflict'`, switch to the resolution flow before attempting any mutation.
**Resolution flow.** Three tools compose:
-1. `list_conflicts()` → enumerate every doc currently tracked in conflict.
-2. `get_conflict_content({ file })` → fetch `base` / `ours` / `theirs` stages plus the doc's `lifecycleStatus`. `ours` reflects the live Y.Text (what the human user sees in the editor) when the doc is loaded server-side and is marker-free; falls back to `git show :2:<file>` otherwise (e.g. after an editor reopen seeded markers into Y.Text).
-3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes and commit. Strategies: `mine` writes `git show :2:`, `theirs` writes `git show :3:`, `content` writes the bytes you supply.
+1. `conflicts({ kind: 'list' })` → enumerate every doc currently tracked in conflict.
+2. `conflicts({ kind: 'content', file })` → returns `{ content: { base, ours, theirs, shape, lifecycleStatus } }` (the result nests under the `content` kind key). `ours` reflects the live Y.Text (what the human user sees in the editor) when the doc is loaded server-side and is marker-free; falls back to `git show :2:<file>` otherwise (e.g. after an editor reopen seeded markers into Y.Text).
+3. `resolve_conflict({ file, strategy, content? })` → write the chosen bytes and commit. Strategies: `mine` runs `git checkout --ours` (your committed stage 2), `theirs` runs `git checkout --theirs` (their stage 3), `content` writes the bytes you supply, `delete` runs `git rm` (for delete-modify / modify-delete shapes where a stage is missing).
-`file` is a `.md` / `.mdx` path relative to the project dir (extension included) — mirrors the on-disk shape, not the extension-less `docName` used by other tools.
+`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.
The resolve operation is best-effort and NOT atomic: `git checkout --ours/--theirs && git add` may succeed but the subsequent `git commit --no-edit` can fail (pre-commit hook rejection, locked index). On commit failure the staged files are re-`git add`-ed back into the unmerged index and the tracked entry remains in `conflicts.json` — re-call `resolve_conflict` after the user clears the blocker.
@@ -151,17 +160,17 @@ OK auto-promotes markdown-native syntax into themed canonical components at pars
| Math | `$x$` inline, `$$…$$` block | KaTeX Math |
| Inline a doc or asset | `![[file]]` | wiki embed |
-`Tabs` is the lone canonical with **no** markdown-native form — write the JSX directly (`<Tabs><Tab label="…">…</Tab></Tabs>`). For any canonical's full JSX prop schema, call `get_components({ ids })`. If no canonical fits, any `<TagName>…</TagName>` falls through as raw MDX — but prefer a canonical when one matches.
+`Tabs` is the lone canonical with **no** markdown-native form — write the JSX directly (`<Tabs><Tab label="…">…</Tab></Tabs>`). For any canonical's full JSX prop schema, call `palette({ components: [ids] })`. If no canonical fits, any `<TagName>…</TagName>` falls through as raw MDX — but prefer a canonical when one matches.
-**Discover the palette in one call.** `get_authoring_palette` returns every markdown-native form (copy-ready `example` + `guidance`), the themed `html preview` embed starters, and the injected theme-token list — the source of truth for component-forward, themed authoring. Canonical names/counts beyond the markdown-native set are project-specific; the inventory in the `write_document` / `edit_document` descriptions and `get_components` are authoritative for those.
+**Discover the palette in one call.** `palette` returns every markdown-native form (copy-ready `example` + `guidance`), the themed `html preview` embed starters, and the injected theme-token list — the source of truth for component-forward, themed authoring. Canonical names/counts beyond the markdown-native set are project-specific; the inventory in the `write` / `edit` descriptions and `palette({ components })` are authoritative for those.
-**Show findings, don't just tell them.** When a point is quantitative or comparative — a trend over time, a breakdown, a before/after, a ranking, a distribution — present it visually: a chart or stat-card `html preview` embed, a ` ```mermaid ` diagram, a table, or a Callout for the headline takeaway. Prose-only buries the insight. This matters most where the document's job is to make findings legible — **`research` reports and `consolidate` articles especially**, and any write-up meant to present results. A research article with three dense paragraphs of numbers should have been a chart. Reach for `get_authoring_palette` as you draft, not after.
+**Show findings, don't just tell them.** When a point is quantitative or comparative — a trend over time, a breakdown, a before/after, a ranking, a distribution — present it visually: a chart or stat-card `html preview` embed, a ` ```mermaid ` diagram, a table, or a Callout for the headline takeaway. Prose-only buries the insight. This matters most where the document's job is to make findings legible — **`research` reports and `consolidate` articles especially**, and any write-up meant to present results. A research article with three dense paragraphs of numbers should have been a chart. Reach for `palette` as you draft, not after.
### `html preview` — themed interactive embeds
A ` ```html preview ` fence (also `htm` / `xml`) renders a standalone HTML/CSS/JS page as a live sandboxed iframe — the extend-to-anything primitive for charts, stat cards, custom SVG, calculators, demos. The iframe auto-sizes to its content; pass `h=` / `w=` (e.g. ` ```html preview h=400px `) only to pin a fixed size.
-**Start from a starter — don't hand-roll.** `get_authoring_palette` returns `embedPatterns` (chart, stat cards, custom SVG, interactive control), each already wired to the theme tokens. Copy one and fill in your data — that is the only path that cannot render unthemed. Hand-author a fence from scratch only when no starter is close.
+**Start from a starter — don't hand-roll.** `palette` returns `embedPatterns` (chart, stat cards, custom SVG, interactive control), each already wired to the theme tokens. Copy one and fill in your data — that is the only path that cannot render unthemed. Hand-author a fence from scratch only when no starter is close.
**MUST — never hardcode colors in an `html preview` embed.** OK injects its theme tokens into every preview iframe; an embed that hardcodes hex / `rgb()` renders unthemed — a white box on a dark page, clashing with every component around it. This is the single most common embed mistake. Wire every color to a token: `var(--chart-1..5)` for chart series, `var(--foreground)` / `var(--muted-foreground)` for text, `var(--card)` / `var(--background)` for surfaces, plus `var(--border)`, `var(--primary)`, `var(--radius)`. Don't set a `body` background at all unless you specifically mean to — the iframe already carries a themed one.
@@ -213,7 +222,7 @@ Knowledge-base docs are factual artifacts — whether the project is a wiki, an
- **Every link must resolve to a doc that exists.** Never link to a doc that isn't written yet. If you want to reference something that should have its own page but doesn't: create that page in the same pass, or record it as a tracked task (`TaskCreate`, or your host's task tool — if the host has none, tell the user) and leave the mention as plain prose. A broken link is debt, not a to-do marker.
- **Never wrap a link in backticks.** `` `[text](./foo.md)` `` is a bug — the backticks make it render as literal code rather than a link.
- **Never use HTML anchors** (`<a href="...">`). Markdown link syntax only.
-- **Verify before walking away.** After writing a doc, call `links({ kind: "dead", sourceDocNames: ["your/doc"] })` to find broken references. Fix or remove every one — a dead link is never acceptable to leave behind. Companion `links` kinds: `backlinks` (incoming), `forward` (outgoing), `orphans` (no incoming), `hubs` (high-incoming), `suggest` (untextualized mentions worth linking).
+- **Verify before walking away.** After writing a doc, call `links({ kind: "dead", sourceDocuments: ["your/doc"] })` to find broken references. Fix or remove every one — a dead link is never acceptable to leave behind. Companion `links` kinds: `backlinks` (incoming), `forward` (outgoing), `orphans` (no incoming), `hubs` (high-incoming), `suggest` (untextualized mentions worth linking).
- **The editor's red-underline visual lies.** Its dead-link detection tolerates slug-fallback (e.g., `foo` may appear resolved because `foo.md` exists at root). `links({ kind: "dead" })` is strict-exact — trust the tool, not the visual.
**Note on wiki-link syntax (`[[Page]]`):** the parser still handles it for legacy content, but it's NO LONGER the recommended default. Write new content with standard markdown links per above. Seed-pack templates (`ok seed --pack <name>`) may still emit `[[Page]]` placeholders inside template body text — those are legacy. When you instantiate a seed-pack template, replace the legacy placeholders with standard markdown links during the `{shape}`-fill pass.
@@ -263,11 +272,11 @@ A doc's frontmatter is exactly its own on-disk YAML — folder frontmatter never
### Read the folder before writing (MUST)
-Before creating or editing docs in a folder, **always** call `exec("ls -A <folder>")` once. The response carries the folder's own `title`/`description`/`tags` + `templates_available` (the template menu for `write_document({ template })`). Skipping this is how agents land docs that violate folder discipline.
+Before creating or editing docs in a folder, **always** call `exec("ls -A <folder>")` once. The response carries the folder's own `title`/`description`/`tags` + `templates_available` (the template menu for `write({ document: { template } })`). Skipping this is how agents land docs that violate folder discipline.
Pre-write checklist:
-0. **First-contact check.** If the folder has no frontmatter of its own AND `templates_available` is empty AND `exec("ls -A")` shows substantial content elsewhere, the project hasn't been onboarded — STOP and invoke `discover` (Workflow tools below). Skip on subsequent writes once confirmed.
+0. **First-contact check.** If the folder has no frontmatter of its own AND `templates_available` is empty AND `exec("ls -A")` shows substantial content elsewhere, the project hasn't been onboarded — STOP and invoke `workflow({ kind: 'discover' })` (Workflow guides below). Skip on subsequent writes once confirmed.
1. **Read the folder's description** — its `title`/`description`/`tags` tell you what the folder is for. (These describe the folder; they are NOT defaults the doc inherits.)
2. **Read `templates_available`** — each entry has `name`, `title`, `description`, `scope` (`local` / `inherited`). If one matches, **prefer it** over free-form markdown (it's the folder's contract — templates carry frontmatter + body structure hand-authored docs routinely miss).
3. **Read recent siblings** — new docs should match the shape of existing ones (filename, frontmatter, body structure).
@@ -277,53 +286,55 @@ Pre-write checklist:
### When to use a template (MUST when one fits)
-Instantiate via `write_document({ template, docName, position: "replace" })`. Inherited templates (`scope: "inherited"`) are equally valid. Skip only when (a) `templates_available` is empty, (b) no entry matches, OR (c) the user asked for free-form. If you skip, briefly note why in chat.
+Instantiate via `write({ document: { path, template } })`. Inherited templates (`scope: "inherited"`) are equally valid. Skip only when (a) `templates_available` is empty, (b) no entry matches, OR (c) the user asked for free-form. If you skip, briefly note why in chat.
### When to create a template
Templates make folder structure durable. Create them proactively:
-- 2+ sibling docs share a skeleton in a folder with no template → extract via `folder_config({ action: "write-template" })`.
+- 2+ sibling docs share a skeleton in a folder with no template → extract via `write({ template })`.
- About to write a doc in a folder where no template fits, AND the shape is reusable → save as template the same turn.
-- Scaffolding a new folder for a doc category → pair the rule (`folder_config({ action: "set-rule" })`) with a template in the same turn.
+- Scaffolding a new folder for a doc category → pair `write({ folder })` (or `edit({ folder })`) with `write({ template })` in the same turn.
- The user describes a recurring doc shape ("we always log meetings with attendees, agenda, action items") → author the template once.
Note new templates in chat ("saved as a template at `meetings/.ok/templates/prep-notes.md` for next time") so the user sees the discipline grew.
+**Keep starter content clean (MUST).** A template body is a reusable skeleton, not a meta-prompt: section headings, real frontmatter, and SHORT `{Stub}` placeholders (e.g. `# {Meeting Title}`). Do NOT bake a workflow's verbose `{...}` prompt-paragraphs (the `research` / `consolidate` shape guidance is for filling ONE doc, not for persisting into every new one), do NOT duplicate sections, and do NOT save a half-filled or in-progress doc as a template. Long "how to fill this" guidance belongs in the folder description, not in the body each new doc inherits. After saving, `exec("cat <folder>/.ok/templates/<name>.md")` and eyeball it — a template propagates to every doc made from it, so a garbled one is a recurring defect, not a one-off.
+
### When recurring per-doc properties emerge (MUST when a pattern emerges)
-If you're writing the same frontmatter (tags, status, a title prefix) on multiple siblings, bake those starting values into a **template** (`folder_config({ action: "write-template" })`) — that's the single mechanism for new-doc starting properties. Folder frontmatter does not cascade values into docs.
+If you're writing the same frontmatter (tags, status, a title prefix) on multiple siblings, bake those starting values into a **template** (`write({ template })`) — that's the single mechanism for new-doc starting properties. Folder frontmatter does not cascade values into docs.
### Editing a folder's own description
```ts
-folder_config({
- action: "set-rule",
- rules: [
- { match: "meetings/**", frontmatter: { title: "Meetings", description: "Meeting notes", tags: ["meeting"] } },
- ],
+edit({
+ folder: {
+ path: "meetings",
+ frontmatter: { title: "Meetings", description: "Meeting notes", tags: ["meeting"] },
+ },
})
```
-`frontmatter` is open-shape — any key about the folder itself, exactly like a doc's frontmatter (`title` / `description` / `tags` are conventional keys the UI surfaces). It's self-only: it describes the folder and does NOT flow into child docs — put per-doc starting values in a template instead. Each `match` resolves to a SINGLE target folder. Multi-folder globs (`specs/*/evidence/**`) are rejected with `MULTI_FOLDER_GLOB` — split per folder. Remove a rule by passing empty `frontmatter: {}` — file deletes and `.ok/` auto-cleans if no other tenant remains.
+`frontmatter` is open-shape — any key about the folder itself, exactly like a doc's frontmatter (`title` / `description` / `tags` are conventional keys the UI surfaces). It's self-only: it describes the folder and does NOT flow into child docs — put per-doc starting values in a template instead. Each call targets a SINGLE folder by its own `path` (no globs). Use `write({ folder })` to create a new folder, `edit({ folder })` to change an existing one (merge-patch). Clear the folder's frontmatter by passing `frontmatter: {}`, or drop one key with `frontmatter: { key: null }` — the file deletes when empty and `.ok/` auto-cleans if no other tenant remains.
### Creating templates
```ts
-folder_config({
- action: "write-template",
- folder: "meetings/",
- name: "prep-notes",
- body: "# {Meeting Title}\n\n**Attendees:** \n**Date:** \n\n## Agenda\n- \n",
- frontmatter: {
- title: "Meeting Prep Notes", // REQUIRED — TEMPLATE_TITLE_REQUIRED if missing
- description: "Use before a meeting.", // recommended — soft warning if absent
- tags: ["meeting", "prep"],
+write({
+ template: {
+ path: "meetings/prep-notes",
+ content: "# {Meeting Title}\n\n**Attendees:** \n**Date:** \n\n## Agenda\n- \n",
+ frontmatter: {
+ title: "Meeting Prep Notes", // REQUIRED — TEMPLATE_TITLE_REQUIRED if missing
+ description: "Use before a meeting.", // recommended — soft warning if absent
+ tags: ["meeting", "prep"],
+ },
},
})
```
-**Substitution allowlist:** template bodies MAY use exactly two server-side substitutions — `{{date}}` (today's ISO-8601 date) and `{{user}}` (calling principal display name). Other `{{...}}` tokens are rejected at write time with `TEMPLATE_UNKNOWN_VARIABLE`. Plain `{shape}` placeholders (e.g., `{Meeting Title}`) are LITERAL — agents fill via subsequent `edit_document` calls. Delete a template via `folder_config({ action: "delete-template", folder, name })` (auto-cleans empty `.ok/templates/` and `.ok/`).
+**Substitution allowlist:** template bodies MAY use exactly two server-side substitutions — `{{date}}` (today's ISO-8601 date) and `{{user}}` (calling principal display name). Other `{{...}}` tokens are rejected at write time with `TEMPLATE_UNKNOWN_VARIABLE`. Plain `{shape}` placeholders (e.g., `{Meeting Title}`) are LITERAL — agents fill via subsequent `edit` calls. Delete a template via `delete({ template: { path } })` (auto-cleans empty `.ok/templates/` and `.ok/`).
### Creating a doc from a template
@@ -332,21 +343,22 @@ folder_config({
exec("ls -A meetings/")
// → templates_available: [{ name: "prep-notes", title: "Meeting Prep Notes", scope: "local" }, ...]
-// Instantiate. `template` and `markdown` are mutually exclusive.
-write_document({
- docName: "meetings/2026-05-02-roadmap-sync",
- template: "prep-notes",
- position: "replace",
+// Instantiate. `template` and `content` are mutually exclusive.
+write({
+ document: {
+ path: "meetings/2026-05-02-roadmap-sync",
+ template: "prep-notes",
+ },
})
-// Fill the `{shape}` placeholders via follow-up edit_document calls.
+// Fill the `{shape}` placeholders via follow-up edit calls.
```
-Templates resolve via leaf → root walk-up at the target's parent folder, closest-wins on filename collision. **`template` and `markdown` are mutually exclusive** — passing both errors with `TEMPLATE_AND_MARKDOWN_BOTH_SET`. Substitution happens at instantiation time only; templates on disk show the raw `{{date}}` token.
+Templates resolve via leaf → root walk-up at the target's parent folder, closest-wins on filename collision. **`template` and `content` are mutually exclusive** — passing both errors with `TEMPLATE_AND_CONTENT_BOTH_SET`. Substitution happens at instantiation time only; templates on disk show the raw `{{date}}` token.
### Editing frontmatter
-`edit_document` does NOT change frontmatter (body-only; frontmatter-intersecting find/replace returns HTTP 400). For single-key edits, prefer `edit_frontmatter({ docName, patch: { key: value } })` — JSON Merge Patch (RFC 7396), `null` deletes, field-level CRDT merge, atomic per-call. For full rewrites (≥3-5 keys, or body + frontmatter together), call `write_document({ position: "replace", markdown })` and include the new YAML block.
+`edit({ document: { path, find, replace } })` does NOT change frontmatter (body-only; frontmatter-intersecting find/replace returns HTTP 400). For metadata, use `edit({ document: { path, frontmatter: { key: value } } })` — JSON Merge Patch (RFC 7396), `null` deletes, field-level CRDT merge, atomic per-call. For a full rewrite (body + frontmatter together), call `write({ document: { path, content, frontmatter, position: "replace" } })`.
### Binary-source wrappers (`ingest`-produced)
@@ -398,7 +410,7 @@ The skill carries the trigger ("KB content changed this turn — go look"). The
| Read an individual doc | `Read: specs/foo/SPEC.md` | `exec("cat specs/foo/SPEC.md")` |
| Explore a markdown-heavy dir | `Agent(Explore): "..."` | Do `exec`-based exploration yourself |
| Wait for the server to tell you to open preview | Skip the session-start preview open and wait for the `attach-preview-once` hint | Open the preview browser at session start; the hint is a fallback when you didn't |
-| Ignore the attach hint | Skip the `warning: { action: "attach-preview-once" }` hint in write-tool responses | Open the preview when the hint fires (`preview_start`, or `get_preview_url`); otherwise do nothing |
+| Ignore the attach hint | Skip the `warning: { action: "attach-preview-once" }` hint in write-tool responses | Open the preview when the hint fires (`preview_start`, or `preview_url`); otherwise do nothing |
| Make the Claude Code Desktop preview work | Read / diagnose / edit `.claude/launch.json` (host-managed config) | Call `preview_start("open-knowledge-ui")` and nothing else; the OK lock-collision proxy bridges any port mismatch transparently |
| Open a doc in the app from the Claude Code CLI | Print the `previewUrl` / `openknowledge://` string for the user to click | Run `ok open <doc>` — it opens the OK Desktop app (folders open in the browser), with browser fallback |
| Reference another doc | `` `[text](./page.md)` `` (backticked) or HTML `<a>` | `[text](./page.md)` (raw markdown) |
@@ -407,31 +419,31 @@ The skill carries the trigger ("KB content changed this turn — go look"). The
| Cite a web source you just fetched | inline `[source](https://...)` because YOU did the fetch (not the user) | `ingest` it — agent-initiated fetches are not exempt from the closed-loop rule |
| Finish a turn that changed KB content | move on without checking for a log | check for a `log.md` and follow its contract per Log discipline |
| Add an image | empty alt `![](./x.png)` or generic alt `![image](./x)` | meaningful alt + source caption below |
-| Catalog folder contents | create `INDEX.md` hub file | `folder_config({ action: "set-rule", rules: [...] })` writes `<folder>/.ok/frontmatter.yml` |
-| Write a doc in an unfamiliar folder | go straight to `write_document` with hand-authored markdown | `exec("ls -A <folder>")` first — read the folder description + `templates_available` before writing |
-| Land in an existing repo without orienting | go straight to `write_document` when no folder frontmatter / templates exist | invoke `discover` once for the project — extracts conventions from siblings, sets folder frontmatter + templates, activates the link graph |
-| Author a doc when a matching template exists | `write_document({ markdown: "..." })` from scratch | `write_document({ template, position: "replace" })` — templates carry the folder's frontmatter + body discipline |
-| Change a doc's title / tags | `edit_document` to swap the YAML (rejected — HTTP 400 frontmatter-intersect) | `edit_frontmatter({ docName, patch })` for 1-2 keys; `write_document({ position: "replace", markdown })` for full rewrites |
-| Repeat the same frontmatter on sibling docs | hand-set identical `tags` / `title` prefix on every new file | `folder_config({ action: "write-template" })` once — new docs start from the template |
-| Re-derive the same body skeleton repeatedly | copy-paste the structure from a sibling each time | `folder_config({ action: "write-template" })` once, then pick from `templates_available` thereafter |
-| Scaffold a new folder for a doc category | set folder rule for frontmatter and stop there | pair `folder_config({ action: "set-rule" })` with `folder_config({ action: "write-template" })` in the same turn |
-| Delete a markdown doc | `Bash: rm` / `unlink` / native deletion on in-scope `.md` | `delete_document` — `version({ action: "save" })` first if rollback may be needed |
+| Catalog folder contents | create `INDEX.md` hub file | `edit({ folder: { path, frontmatter } })` writes `<folder>/.ok/frontmatter.yml` |
+| Write a doc in an unfamiliar folder | go straight to `write` with hand-authored markdown | `exec("ls -A <folder>")` first — read the folder description + `templates_available` before writing |
+| Land in an existing repo without orienting | go straight to `write` when no folder frontmatter / templates exist | invoke `workflow({ kind: 'discover' })` once for the project — extracts conventions from siblings, sets folder frontmatter + templates, activates the link graph |
+| Author a doc when a matching template exists | `write({ document: { path, content: "..." } })` from scratch | `write({ document: { path, template } })` — templates carry the folder's frontmatter + body discipline |
+| Change a doc's title / tags | `edit({ document: { path, find, replace } })` to swap the YAML (rejected — HTTP 400 frontmatter-intersect) | `edit({ document: { path, frontmatter } })` for metadata; `write({ document: { path, content, frontmatter, position: "replace" } })` for full rewrites |
+| Repeat the same frontmatter on sibling docs | hand-set identical `tags` / `title` prefix on every new file | `write({ template })` once — new docs start from the template |
+| Re-derive the same body skeleton repeatedly | copy-paste the structure from a sibling each time | `write({ template })` once, then pick from `templates_available` thereafter |
+| Scaffold a new folder for a doc category | set folder frontmatter and stop there | pair `edit({ folder })` with `write({ template })` in the same turn |
+| Delete a markdown doc | `Bash: rm` / `unlink` / native deletion on in-scope `.md` | `delete({ document })` — `checkpoint()` first if rollback may be needed |
| Fork a skill and expect no stomp | Edit installed SKILL.md | `npx skills remove` before CLI upgrade |
## Workflow tools — when to invoke them
-Four MCP tools build on the primitives above. **They return *procedural guidance* (a multi-step instructional body), not fetched data.** Calling `ingest("https://…")` does not download and write a doc for you — it returns a multi-step plan you then execute. Same for `research` / `consolidate` / `discover`. Plan to follow the numbered steps in order; don't skip the STOP gates.
+One MCP tool — `workflow` — builds on the primitives above, dispatched on `kind`. **It returns *procedural guidance* (a multi-step instructional body), not fetched data.** Calling `workflow({ kind: 'ingest', source: "https://…" })` does not download and write a doc for you — it returns a multi-step plan you then execute. Same for the `research` / `consolidate` / `discover` kinds. Plan to follow the numbered steps in order; don't skip the STOP gates.
-Three correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (`ingest` / `research` / `consolidate`); the fourth (`discover`) operates at the project-metadata layer and is the brownfield counterpart to the greenfield `ok seed` CLI:
+Three kinds correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (`ingest` / `research` / `consolidate`); the fourth (`discover`) operates at the project-metadata layer and is the brownfield counterpart to the greenfield `ok seed` CLI:
-| Tool | Layer | When to invoke |
+| `kind` | Layer | When to invoke (via `workflow({ kind })`) |
| ------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ingest` | Raw sources (immutable) | User shares a URL/PDF/file to preserve verbatim, **OR you fetched a URL** (`WebFetch` / `WebSearch` / equivalent) to ground a claim that's about to land in the knowledge base. The KB is closed-loop — agent-initiated fetches are not exempt. **Binary sources** (PDFs, images, audio, Office docs) are preserved verbatim, not text-scraped — the tool body documents the binary-vs-text classification, write-path STOP gates (executable, size, scheme), re-ingest semantics, and shell-less fallback. No analysis in the file itself — takeaways go back to the user in chat. |
| `research` | KB, provisional | User asks you to investigate, compare alternatives, or synthesize multiple sources. Produces a `status: provisional` article with a `sources:` list. Follows scan-first routing, a STOP scoping gate, 3P-external framing, and a validate checklist — the tool body enforces each step. |
| `consolidate` | KB, canonical | Team has actually decided after research and wants the outcome committed as source-of-truth. Starts with a STOP gate confirming the decision exists; writes a `status: canonical` article with a `supersedes:` chain. |
| `discover` | Project metadata | First arrival at a repo with existing content AND no folder frontmatter / templates set. Extracts conventions from siblings; activates the link graph (orphans, hubs, untextualized mentions); proposes folder frontmatter + templates + `.okignore`; per-phase user confirmation. Phases 1-4 run fs-direct; Phase 5 (link-graph activation) needs `ok start` (Phase 5 step 0 gates). Skip on empty repos (use `ok seed`). One-shot; idempotent on re-run. |
-**These tools are your default move, not `write_document`.** When the work fits one of the three layers — preserving an external source, investigating/synthesizing, committing a decided outcome — invoke the corresponding tool instead of going straight to `write_document` / `edit_document`. The tool bodies enforce framing (sources, status, supersedes chains) that hand-written articles routinely miss. `write_document` is correct for everything that does **not** fit the three layers (specs, runbooks, scratch notes, project pages); for the three that do, lead with the tool. This is doubly true in projects that ran `ok seed` — a doc landing in `external-sources/` / `research/` / `articles/` should have come out of `ingest` / `research` / `consolidate`.
+**These tools are your default move, not `write`.** When the work fits one of the three layers — preserving an external source, investigating/synthesizing, committing a decided outcome — invoke the corresponding tool instead of going straight to `write` / `edit`. The tool bodies enforce framing (sources, status, supersedes chains) that hand-written articles routinely miss. `write` is correct for everything that does **not** fit the three layers (specs, runbooks, scratch notes, project pages); for the three that do, lead with the tool. This is doubly true in projects that ran `ok seed` — a doc landing in `external-sources/` / `research/` / `articles/` should have come out of `ingest` / `research` / `consolidate`.
Typical day-2 flow: user shares a URL → `ingest` (preserve) → user asks "now research this" → `research` (provisional article + `ingest`s more sources as needed) → decision lands → `consolidate` (canonical article, supersedes the research).
@@ -439,18 +451,18 @@ Typical day-2 flow: user shares a URL → `ingest` (preserve) → user asks "now
**Do not chain silently.** After `ingest`, ask the user whether to proceed to `research`. After `research`, let the user decide whether the findings are ready to `consolidate`. Each tool completes on its own terms — the user drives the transitions.
-**Repeat invocations.** Workflow tools return their full instructional body on every call, including 2nd / 3rd / Nth invocation in the same session. If you've already received a tool's body earlier this session, you can skim the repeat for changes (the body can evolve across server versions) but you don't need to re-internalize it — proceed to the next step with the new arguments.
+**Repeat invocations.** The `workflow` tool returns its full instructional body on every call, including 2nd / 3rd / Nth invocation in the same session. If you've already received a tool's body earlier this session, you can skim the repeat for changes (the body can evolve across server versions) but you don't need to re-internalize it — proceed to the next step with the new arguments.
-**Project scaffolding — two paths.** **Empty repo:** run `ok seed` once from a terminal (scaffolds Karpathy three-layer + seeds `log.md` + registers folder defaults). **Existing content:** invoke `discover` (MCP tool, table above — extracts conventions from siblings, sets folder frontmatter + templates, curates `.okignore`, activates link graph; per-phase confirmation gates). Neither is required; the four workflow tools work against any folder structure. Only mention each when explicitly relevant.
+**Project scaffolding — two paths.** **Empty repo:** run `ok seed` once from a terminal (scaffolds Karpathy three-layer + seeds `log.md` + registers folder defaults). **Existing content:** invoke `workflow({ kind: 'discover' })` (table above — extracts conventions from siblings, sets folder frontmatter + templates, curates `.okignore`, activates link graph; per-phase confirmation gates). Neither is required; the four workflow kinds work against any folder structure. Only mention each when explicitly relevant.
## Server lifecycle
-If `write_document` or `edit_document` returns a "Hocuspocus server is not running" error, start it with `ok start` (via Bash) and retry. Never fall back to native `Edit` / `Write` for in-scope markdown — always route through the MCP write tools so edits go through the CRDT with proper attribution.
+If `write` or `edit` returns a "Hocuspocus server is not running" error, start it with `ok start` (via Bash) and retry. Never fall back to native `Edit` / `Write` for in-scope markdown — always route through the MCP write tools so edits go through the CRDT with proper attribution.
## Scope recap
-Open Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: ['content', 'dir'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder's own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.
+Open Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `config({ key: 'content.dir' })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder's own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.
Default mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what's excluded.
-**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn't onboarded — invoke `discover` (Workflow tools table) before writing.
+**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn't onboarded — invoke `workflow({ kind: 'discover' })` before writing.
diff --git a/packages/server/src/api-agent-frontmatter.test.ts b/packages/server/src/api-agent-frontmatter.test.ts
index d24660c04..cc5db54a4 100644
--- a/packages/server/src/api-agent-frontmatter.test.ts
+++ b/packages/server/src/api-agent-frontmatter.test.ts
@@ -380,7 +380,7 @@ describe('POST /api/agent-patch (edit_document) — frontmatter rejection', () =
const parsed = JSON.parse(response.body);
expect(parsed.type).toBe('urn:ok:error:frontmatter-edit-not-supported');
expect(parsed.title).toContain('Frontmatter edits are not supported');
- expect(parsed.title).toContain('write_document');
+ expect(parsed.title).toContain('edit(');
expect(ytextFm(session.dc.document)).toBe(existingFm);
expect(fmMap(session.dc.document)).toEqual({
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index c2e33b145..e9c4363fb 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -199,7 +199,7 @@ import { getLocalDir } from './config/paths.ts';
import { CONFIG_VALIDATION_REVERT_ORIGIN } from './config-edit-origin.ts';
import { DocInConflictError, isDocInConflict, respondDocInConflict } from './conflict-errors.ts';
import { enrichDirectory } from './content/enrichment.ts';
-import { applyNestedFolderRulesUpsert } from './content/folder-rule-write.ts';
+import { applyFolderFrontmatterPatch } from './content/folder-frontmatter-write.ts';
import { applySubstitution, todayIsoUtc } from './content/substitution.ts';
import {
resolveProjectTemplates,
@@ -4357,7 +4357,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:frontmatter-edit-not-supported',
- 'Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.',
+ 'Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.',
{ handler: 'agent-patch' },
);
return;
@@ -4516,7 +4516,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:frontmatter-edit-not-supported',
- 'Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.',
+ 'Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.',
{ handler: 'agent-patch' },
);
return;
@@ -5065,7 +5065,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
const resolvedContentRoot = contentRoot ?? '.';
- const result = await saveVersion(shadow, resolvedContentRoot, writers);
+ const checkpointSummary = normalizeSummary(
+ typeof body.summary === 'string' ? body.summary : undefined,
+ );
+ const result = await saveVersion(
+ shadow,
+ resolvedContentRoot,
+ writers,
+ 'main',
+ checkpointSummary.kind === 'value' ? checkpointSummary.value : undefined,
+ );
getLogger('history').info({ checkpointRef: result.checkpointRef }, 'checkpoint');
@@ -9556,20 +9565,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const validated = validateFolderRel(body.path, res, 'path', 'folder-config-put');
if (!validated) return;
- const match = validated.folderRel === '' ? '**' : `${validated.folderRel}/**`;
-
- const allApplied: Array<{ match: string; path: string; action: 'written' | 'deleted' }> =
- [];
+ const allApplied: Array<{ path: string; action: 'written' | 'deleted' | 'noop' }> = [];
if (body.frontmatter !== undefined) {
- const result = applyNestedFolderRulesUpsert({
- projectDir: validated.resolvedContentDir,
- rules: [{ match, frontmatter: pickFrontmatterFields(body.frontmatter) }],
+ const result = applyFolderFrontmatterPatch({
+ anchorDir: validated.resolvedContentDir,
+ folderRel: validated.folderRel,
+ patch: body.frontmatter,
});
if (!result.ok) {
- const status =
- result.error.code === 'WRITE_ERROR' || result.error.code === 'BAD_PROJECT_DIR'
- ? 500
- : 400;
+ const status = result.error.code === 'WRITE_ERROR' ? 500 : 400;
const urn =
status === 500
? 'urn:ok:error:internal-server-error'
@@ -9582,7 +9586,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
return;
}
- allApplied.push(...result.applied);
+ allApplied.push({ path: result.path, action: result.action });
}
successResponse(
diff --git a/packages/server/src/bash/parse-command.ts b/packages/server/src/bash/parse-command.ts
index 9a16503a8..d29dce73d 100644
--- a/packages/server/src/bash/parse-command.ts
+++ b/packages/server/src/bash/parse-command.ts
@@ -165,13 +165,13 @@ function opTokenError(token: ShellOpToken): ParseCommandError {
if (WRITE_OPS.has(op)) {
return {
category: 'write_blocked',
- message: `Write operation blocked: '${op}'. exec is read-only. For document changes, use write_document or edit_document.`,
+ message: `Write operation blocked: '${op}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`,
};
}
if (SHELL_CONSTRUCT_OPS.has(op)) {
return {
category: 'shell_construct_blocked',
- message: `Shell construct '${op}' is not supported. Only pipes (|) are allowed between allowlisted stages.`,
+ message: `Shell construct '${op}' is not supported — exec runs ONE command or a pipe (|), not a shell. Run separate exec calls, or pass multiple paths to one command (e.g. \`ls -A a b c\`, \`cat a b c\`).`,
};
}
return {
@@ -228,7 +228,7 @@ function checkStage(stage: Stage): ParseCommandError | null {
if (UNIVERSAL_FLAG_DENY.has(arg) || UNIVERSAL_FLAG_PREFIX_DENY.some((p) => arg.startsWith(p))) {
return {
category: 'write_blocked',
- message: `Write operation blocked: '${arg}'. exec is read-only. For document changes, use write_document or edit_document.`,
+ message: `Write operation blocked: '${arg}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`,
};
}
if (stage.command === 'find' && FIND_FLAG_DENY.has(arg)) {
diff --git a/packages/server/src/conflict-errors.test.ts b/packages/server/src/conflict-errors.test.ts
index d79b32173..6cda804e7 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 merge-conflict state. Call get_conflict_content + resolve_conflict before retrying.',
+ 'The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
);
expect(body.file).toBe('docs/notes.md');
diff --git a/packages/server/src/conflict-errors.ts b/packages/server/src/conflict-errors.ts
index b1b9b39e6..cd6497915 100644
--- a/packages/server/src/conflict-errors.ts
+++ b/packages/server/src/conflict-errors.ts
@@ -49,7 +49,7 @@ export function respondDocInConflict(
errorResponse(res, 409, 'urn:ok:error:doc-in-conflict', 'Document is in conflict.', {
handler,
detail:
- 'The document is in a merge-conflict state. Call get_conflict_content + resolve_conflict before retrying.',
+ 'The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.',
extensions: {
file: err.file,
resolutionOptions: RESOLUTION_OPTIONS,
diff --git a/packages/server/src/content/folder-frontmatter-write.ts b/packages/server/src/content/folder-frontmatter-write.ts
new file mode 100644
index 000000000..e1ee162ef
--- /dev/null
+++ b/packages/server/src/content/folder-frontmatter-write.ts
@@ -0,0 +1,124 @@
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmdirSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { isAbsolute, join, resolve, sep } from 'node:path';
+import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
+import { type FrontmatterRecord, mergePatch } from './frontmatter-merge.ts';
+
+export interface FolderFrontmatterPatchInput {
+ anchorDir: string;
+ folderRel: string;
+ patch: FrontmatterRecord;
+}
+
+export type FolderFrontmatterPatchResult =
+ | { ok: true; path: string; action: 'written' | 'deleted' | 'noop' }
+ | {
+ ok: false;
+ error: {
+ code: 'BAD_CONTENT_DIR' | 'PATH_ESCAPE' | 'WRITE_ERROR';
+ message: string;
+ };
+ };
+
+export function applyFolderFrontmatterPatch(
+ input: FolderFrontmatterPatchInput,
+): FolderFrontmatterPatchResult {
+ if (!isAbsolute(input.anchorDir)) {
+ return { ok: false, error: { code: 'BAD_CONTENT_DIR', message: 'anchorDir must be absolute' } };
+ }
+ const contentAbs = resolve(input.anchorDir);
+ const folderRel = input.folderRel.replace(/^\.\//, '').replace(/^\/+/, '').replace(/\/+$/, '');
+ if (folderRel.split('/').some((seg) => seg === '..')) {
+ return {
+ ok: false,
+ error: {
+ code: 'PATH_ESCAPE',
+ message: `Folder path escapes the content directory: ${input.folderRel}`,
+ },
+ };
+ }
+ const targetAbs = folderRel === '' ? contentAbs : resolve(contentAbs, folderRel);
+ if (targetAbs !== contentAbs && !targetAbs.startsWith(contentAbs + sep)) {
+ return {
+ ok: false,
+ error: {
+ code: 'PATH_ESCAPE',
+ message: `Resolved folder escapes the content directory: ${targetAbs}`,
+ },
+ };
+ }
+
+ const okDir = join(targetAbs, '.ok');
+ const fmPath = join(okDir, 'frontmatter.yml');
+
+ try {
+ const existing = readExistingFrontmatter(fmPath);
+ const isEmptyPatch = Object.keys(input.patch).length === 0;
+ const merged = isEmptyPatch ? {} : mergePatch(existing, input.patch);
+
+ if (Object.keys(merged).length === 0) {
+ if (existsSync(fmPath)) {
+ unlinkSync(fmPath);
+ autoCleanOkDir(okDir);
+ return { ok: true, path: relPathOf(contentAbs, fmPath), action: 'deleted' };
+ }
+ return { ok: true, path: relPathOf(contentAbs, fmPath), action: 'noop' };
+ }
+
+ mkdirSync(okDir, { recursive: true });
+ const yaml = stringifyYaml(merged);
+ const tmpPath = `${fmPath}.tmp.${process.pid}.${Date.now()}`;
+ writeFileSync(tmpPath, yaml, 'utf-8');
+ renameSync(tmpPath, fmPath);
+ return { ok: true, path: relPathOf(contentAbs, fmPath), action: 'written' };
+ } catch (err) {
+ return {
+ ok: false,
+ error: {
+ code: 'WRITE_ERROR',
+ message: `Failed to write folder frontmatter for "${folderRel || '.'}": ${(err as Error).message}`,
+ },
+ };
+ }
+}
+
+function readExistingFrontmatter(absPath: string): FrontmatterRecord {
+ if (!existsSync(absPath)) return {};
+ const content = readFileSync(absPath, 'utf-8');
+ const parsed: unknown = parseYaml(content);
+ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
+ return { ...(parsed as FrontmatterRecord) };
+}
+
+function autoCleanOkDir(okAbsDir: string): void {
+ if (!existsSync(okAbsDir)) return;
+ let entries: string[];
+ try {
+ entries = readdirSync(okAbsDir);
+ } catch {
+ return;
+ }
+ if (entries.length === 0) {
+ try {
+ rmdirSync(okAbsDir);
+ } catch {}
+ }
+}
+
+function relPathOf(rootAbs: string, abs: string): string {
+ if (abs.startsWith(rootAbs + sep)) {
+ return abs
+ .slice(rootAbs.length + 1)
+ .split(sep)
+ .join('/');
+ }
+ return abs;
+}
diff --git a/packages/server/src/content/folder-rule-write.test.ts b/packages/server/src/content/folder-rule-write.test.ts
deleted file mode 100644
index d4339a3e8..000000000
--- a/packages/server/src/content/folder-rule-write.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { applyNestedFolderRulesUpsert } from './folder-rule-write.ts';
-
-describe('applyNestedFolderRulesUpsert', () => {
- let projectDir: string;
-
- beforeEach(async () => {
- projectDir = await mkdtemp(join(tmpdir(), 'folder-rule-write-'));
- });
-
- afterEach(async () => {
- await rm(projectDir, { recursive: true, force: true });
- });
-
- test('writes a single-folder rule to <folder>/.ok/frontmatter.yml', () => {
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'meetings/**',
- frontmatter: { title: 'Meetings', tags: ['meeting'] },
- },
- ],
- });
-
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- expect(result.applied).toEqual([
- { match: 'meetings/**', path: 'meetings/.ok/frontmatter.yml', action: 'written' },
- ]);
-
- const abs = join(projectDir, 'meetings', '.ok', 'frontmatter.yml');
- expect(existsSync(abs)).toBe(true);
- const content = readFileSync(abs, 'utf-8');
- expect(content).toContain('title: Meetings');
- expect(content).toContain('- meeting');
- });
-
- test('rejects multi-folder globs with MULTI_FOLDER_GLOB', () => {
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'specs/*/evidence/**',
- frontmatter: { title: 'Evidence' },
- },
- ],
- });
-
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.error.code).toBe('MULTI_FOLDER_GLOB');
- });
-
- test('rejects parent-traversal `match` with PATH_ESCAPE — target folder cannot escape projectDir', () => {
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: '../escape/**',
- frontmatter: { title: 'X' },
- },
- ],
- });
-
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.error.code).toBe('PATH_ESCAPE');
- expect(result.error.rule).toBe('../escape/**');
- expect(existsSync(join(projectDir, '..', 'escape', '.ok', 'frontmatter.yml'))).toBe(false);
- });
-
- test('rejects parent-traversal `new_match` with PATH_ESCAPE — source-folder rename cannot escape projectDir', () => {
- mkdirSync(join(projectDir, 'meetings', '.ok'), { recursive: true });
- writeFileSync(
- join(projectDir, 'meetings', '.ok', 'frontmatter.yml'),
- 'title: Meetings\n',
- 'utf-8',
- );
-
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'meetings/**',
- new_match: '../escape/**',
- frontmatter: { title: 'X' },
- },
- ],
- });
-
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.error.code).toBe('PATH_ESCAPE');
- expect(existsSync(join(projectDir, 'meetings', '.ok', 'frontmatter.yml'))).toBe(true);
- });
-
- test('rejects relative projectDir with BAD_PROJECT_DIR', () => {
- const result = applyNestedFolderRulesUpsert({
- projectDir: 'relative/path',
- rules: [{ match: 'foo/**', frontmatter: { title: 'X' } }],
- });
-
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.error.code).toBe('BAD_PROJECT_DIR');
- });
-
- test('malformed existing YAML surfaces as WRITE_ERROR — does not silently drop existing keys', () => {
- const fmDir = join(projectDir, 'meetings', '.ok');
- mkdirSync(fmDir, { recursive: true });
- writeFileSync(
- join(fmDir, 'frontmatter.yml'),
- 'title: "unterminated\ndescription: also broken: : :',
- 'utf-8',
- );
-
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'meetings/**',
- frontmatter: { tags: ['meeting'] },
- },
- ],
- });
-
- expect(result.ok).toBe(false);
- if (result.ok) return;
- expect(result.error.code).toBe('WRITE_ERROR');
- expect(result.error.rule).toBe('meetings/**');
-
- const content = readFileSync(join(fmDir, 'frontmatter.yml'), 'utf-8');
- expect(content).toContain('unterminated');
- });
-
- test('an empty patch ({}) deletes the file and auto-cleans .ok/', () => {
- const fmDir = join(projectDir, 'meetings', '.ok');
- mkdirSync(fmDir, { recursive: true });
- writeFileSync(join(fmDir, 'frontmatter.yml'), 'title: Meetings\n', 'utf-8');
-
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [{ match: 'meetings/**', frontmatter: {} }],
- });
-
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- expect(result.applied[0]?.action).toBe('deleted');
- expect(existsSync(join(fmDir, 'frontmatter.yml'))).toBe(false);
- expect(existsSync(fmDir)).toBe(false);
- });
-
- test('preserves existing keys when patch only sets one scalar', () => {
- const fmDir = join(projectDir, 'meetings', '.ok');
- mkdirSync(fmDir, { recursive: true });
- writeFileSync(
- join(fmDir, 'frontmatter.yml'),
- 'title: Old Title\ndescription: Old desc\ntags:\n - keep\n',
- 'utf-8',
- );
-
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'meetings/**',
- frontmatter: { title: 'New Title' },
- },
- ],
- });
-
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- const content = readFileSync(join(fmDir, 'frontmatter.yml'), 'utf-8');
- expect(content).toContain('title: New Title');
- expect(content).toContain('Old desc');
- expect(content).toContain('- keep');
- });
-
- test('writes arbitrary keys (open-shape, like a doc)', () => {
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [
- {
- match: 'specs/**',
- frontmatter: { title: 'Specs', status: 'draft', owner: 'tim', priority: 1 },
- },
- ],
- });
-
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- const content = readFileSync(join(projectDir, 'specs', '.ok', 'frontmatter.yml'), 'utf-8');
- expect(content).toContain('title: Specs');
- expect(content).toContain('status: draft');
- expect(content).toContain('owner: tim');
- expect(content).toContain('priority: 1');
- });
-
- test('clearing any key removes it while preserving the rest', () => {
- const fmDir = join(projectDir, 'specs', '.ok');
- mkdirSync(fmDir, { recursive: true });
- writeFileSync(join(fmDir, 'frontmatter.yml'), 'title: Specs\nstatus: draft\n', 'utf-8');
-
- const result = applyNestedFolderRulesUpsert({
- projectDir,
- rules: [{ match: 'specs/**', frontmatter: { status: null } }],
- });
-
- expect(result.ok).toBe(true);
- if (!result.ok) return;
- const content = readFileSync(join(fmDir, 'frontmatter.yml'), 'utf-8');
- expect(content).not.toContain('status');
- expect(content).toContain('title: Specs');
- });
-});
diff --git a/packages/server/src/content/folder-rule-write.ts b/packages/server/src/content/folder-rule-write.ts
deleted file mode 100644
index f4e5d859b..000000000
--- a/packages/server/src/content/folder-rule-write.ts
+++ /dev/null
@@ -1,244 +0,0 @@
-import {
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- renameSync,
- rmdirSync,
- unlinkSync,
- writeFileSync,
-} from 'node:fs';
-import { isAbsolute, join, resolve, sep } from 'node:path';
-import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
-import { type FrontmatterRecord, mergePatch } from './frontmatter-merge.ts';
-
-interface NestedFolderRuleInput {
- match: string;
- frontmatter: Record<string, unknown>;
- new_match?: string;
-}
-
-interface AppliedRule {
- match: string;
- path: string;
- action: 'written' | 'deleted';
-}
-
-type NestedFolderRulesUpsertResult =
- | {
- ok: true;
- applied: AppliedRule[];
- }
- | {
- ok: false;
- error: {
- code: 'MULTI_FOLDER_GLOB' | 'PATH_ESCAPE' | 'BAD_PROJECT_DIR' | 'WRITE_ERROR';
- message: string;
- rule?: string;
- };
- partiallyApplied?: AppliedRule[];
- };
-
-interface NestedFolderRulesUpsertOptions {
- projectDir: string;
- rules: NestedFolderRuleInput[];
-}
-
-export function applyNestedFolderRulesUpsert(
- opts: NestedFolderRulesUpsertOptions,
-): NestedFolderRulesUpsertResult {
- if (!isAbsolute(opts.projectDir)) {
- return {
- ok: false,
- error: { code: 'BAD_PROJECT_DIR', message: 'projectDir must be absolute' },
- };
- }
-
- interface PlannedOp {
- targetFolder: string; // project-root-relative; "" for project root
- targetAbs: string;
- sourceFolder: string | null; // for rename: previous folder (relative)
- sourceAbs: string | null;
- rule: NestedFolderRuleInput;
- }
- const planned: PlannedOp[] = [];
-
- for (const rule of opts.rules) {
- const target = resolveTargetFolderFromMatch(rule.new_match ?? rule.match);
- if (!target.ok) {
- return {
- ok: false,
- error: { code: 'MULTI_FOLDER_GLOB', message: target.message, rule: rule.match },
- };
- }
- const targetAbs = target.folder ? resolve(opts.projectDir, target.folder) : opts.projectDir;
- const projectAbs = resolve(opts.projectDir);
- if (!targetAbs.startsWith(projectAbs + sep) && targetAbs !== projectAbs) {
- return {
- ok: false,
- error: {
- code: 'PATH_ESCAPE',
- message: `Resolved target folder escapes projectDir: ${targetAbs}`,
- rule: rule.match,
- },
- };
- }
-
- let sourceFolder: string | null = null;
- let sourceAbs: string | null = null;
- if (rule.new_match !== undefined && rule.new_match !== rule.match) {
- const source = resolveTargetFolderFromMatch(rule.match);
- if (!source.ok) {
- return {
- ok: false,
- error: { code: 'MULTI_FOLDER_GLOB', message: source.message, rule: rule.match },
- };
- }
- sourceFolder = source.folder;
- sourceAbs = source.folder ? resolve(opts.projectDir, source.folder) : opts.projectDir;
- if (!sourceAbs.startsWith(projectAbs + sep) && sourceAbs !== projectAbs) {
- return {
- ok: false,
- error: {
- code: 'PATH_ESCAPE',
- message: `Resolved source folder escapes projectDir: ${sourceAbs}`,
- rule: rule.match,
- },
- };
- }
- }
-
- planned.push({
- targetFolder: target.folder,
- targetAbs,
- sourceFolder,
- sourceAbs,
- rule,
- });
- }
-
- const applied: AppliedRule[] = [];
-
- for (const op of planned) {
- try {
- if (op.sourceAbs && op.sourceAbs !== op.targetAbs) {
- const sourceFmPath = join(op.sourceAbs, '.ok', 'frontmatter.yml');
- if (existsSync(sourceFmPath)) {
- unlinkSync(sourceFmPath);
- autoCleanOkDir(join(op.sourceAbs, '.ok'));
- applied.push({
- match: op.rule.match,
- path: relPathOf(opts.projectDir, sourceFmPath),
- action: 'deleted',
- });
- }
- }
-
- const okDir = join(op.targetAbs, '.ok');
- const fmPath = join(okDir, 'frontmatter.yml');
- const existing = readExistingFrontmatter(fmPath);
- const isEmptyPatch = Object.keys(op.rule.frontmatter).length === 0;
- const merged = isEmptyPatch ? {} : mergePatch(existing, op.rule.frontmatter);
-
- if (Object.keys(merged).length === 0) {
- if (existsSync(fmPath)) {
- unlinkSync(fmPath);
- autoCleanOkDir(okDir);
- applied.push({
- match: op.rule.new_match ?? op.rule.match,
- path: relPathOf(opts.projectDir, fmPath),
- action: 'deleted',
- });
- }
- continue;
- }
-
- mkdirSync(okDir, { recursive: true });
- const yaml = stringifyYaml(merged);
- const tmpPath = `${fmPath}.tmp.${process.pid}.${Date.now()}`;
- writeFileSync(tmpPath, yaml, 'utf-8');
- renameSync(tmpPath, fmPath);
-
- applied.push({
- match: op.rule.new_match ?? op.rule.match,
- path: relPathOf(opts.projectDir, fmPath),
- action: 'written',
- });
- } catch (err) {
- return {
- ok: false,
- error: {
- code: 'WRITE_ERROR',
- message: `Failed to write nested frontmatter for ${op.rule.match}: ${(err as Error).message}`,
- rule: op.rule.match,
- },
- ...(applied.length > 0 ? { partiallyApplied: applied } : {}),
- };
- }
- }
-
- return { ok: true, applied };
-}
-
-function resolveTargetFolderFromMatch(
- match: string,
-): { ok: true; folder: string } | { ok: false; message: string } {
- const segments = match.split('/').filter((s) => s.length > 0);
- const literalSegments: string[] = [];
- let sawGlob = false;
- for (const seg of segments) {
- const isGlob = /[*?[\]{}]/.test(seg);
- if (sawGlob && !isGlob) {
- return {
- ok: false,
- message: `Glob "${match}" matches multiple folders (literal segment "${seg}" appears after a glob). Split it into one rule per folder, e.g. folder_config({ action: "set-rule", rules: [{ match: "specs/foo/${seg}/**", ... }, ...] }).`,
- };
- }
- if (isGlob) {
- sawGlob = true;
- if (seg !== '**' && seg !== '*') {
- return {
- ok: false,
- message: `Glob "${match}" uses an unsupported pattern segment "${seg}". Only "*" and "**" are supported in nested folder rules.`,
- };
- }
- continue;
- }
- literalSegments.push(seg);
- }
- return { ok: true, folder: literalSegments.join('/') };
-}
-
-function readExistingFrontmatter(absPath: string): FrontmatterRecord {
- if (!existsSync(absPath)) return {};
- const content = readFileSync(absPath, 'utf-8');
- const parsed: unknown = parseYaml(content);
- if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
- return { ...(parsed as FrontmatterRecord) };
-}
-
-function autoCleanOkDir(okAbsDir: string): void {
- if (!existsSync(okAbsDir)) return;
- let entries: string[];
- try {
- entries = readdirSync(okAbsDir);
- } catch {
- return;
- }
- if (entries.length === 0) {
- try {
- rmdirSync(okAbsDir);
- } catch {}
- }
-}
-
-function relPathOf(projectDir: string, abs: string): string {
- const projectAbs = resolve(projectDir);
- if (abs.startsWith(projectAbs + sep)) {
- return abs
- .slice(projectAbs.length + 1)
- .split(sep)
- .join('/');
- }
- return abs;
-}
diff --git a/packages/server/src/mcp-http.test.ts b/packages/server/src/mcp-http.test.ts
index 10c9385d0..2a86ea789 100644
--- a/packages/server/src/mcp-http.test.ts
+++ b/packages/server/src/mcp-http.test.ts
@@ -210,7 +210,7 @@ test('mcp-tool-path-traversal: explicit cwd outside configured project root is r
expect(text).toMatch(/not within the configured project root|escapes the configured root/);
});
-test('PRD-6659: tools/call write_document with an invalid position returns field name + allowed values', async () => {
+test('PRD-6659: tools/call write with an invalid position returns field name + allowed values', async () => {
const config: Config = ConfigSchema.parse({});
const harness = await bootHandler(config);
openHarnesses.push(harness);
@@ -230,8 +230,8 @@ test('PRD-6659: tools/call write_document with an invalid position returns field
id: 42,
method: 'tools/call',
params: {
- name: 'write_document',
- arguments: { docName: 'foo', markdown: 'hello', position: 'middle' },
+ name: 'write',
+ arguments: { document: { path: 'foo', content: 'hello', position: 'middle' } },
},
}),
});
@@ -353,11 +353,13 @@ test('forwarded connectionId header reaches /api/agent-write-md as agentId', asy
id: 2,
method: 'tools/call',
params: {
- name: 'write_document',
+ name: 'write',
arguments: {
- docName: 'forwarded-id-probe',
- markdown: 'hello\n',
- position: 'replace',
+ document: {
+ path: 'forwarded-id-probe',
+ content: 'hello\n',
+ position: 'replace',
+ },
},
},
}),
@@ -476,11 +478,13 @@ test('invalid connectionId header is ignored — session falls back to a fresh U
id: 2,
method: 'tools/call',
params: {
- name: 'write_document',
+ name: 'write',
arguments: {
- docName: 'bad-cid-probe',
- markdown: 'hello\n',
- position: 'replace',
+ document: {
+ path: 'bad-cid-probe',
+ content: 'hello\n',
+ position: 'replace',
+ },
},
},
}),
diff --git a/packages/server/src/mcp/instructions.test.ts b/packages/server/src/mcp/instructions.test.ts
index 80ac892a6..55522566c 100644
--- a/packages/server/src/mcp/instructions.test.ts
+++ b/packages/server/src/mcp/instructions.test.ts
@@ -13,8 +13,8 @@ test('buildInstructions carries the STOP rule on native tools for in-scope markd
const text = buildInstructions(defaultContent());
expect(text).toContain('STOP');
expect(text).toContain('Open Knowledge MCP configured');
- expect(text).toContain('write_document');
- expect(text).toContain('edit_document');
+ expect(text).toContain('write');
+ expect(text).toContain('edit');
});
test('buildInstructions carries the preview-attach rule', () => {
@@ -26,9 +26,7 @@ test('buildInstructions carries the preview-attach rule', () => {
test('buildInstructions carries the autoOpen directional bullet', () => {
const text = buildInstructions(defaultContent());
- expect(text).toContain(
- 'Honor `autoOpen`** (on `get_preview_url`, or on `warning` for write tools)',
- );
+ expect(text).toContain('Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools)');
expect(text).toContain('do not open or refresh any preview UI');
});
diff --git a/packages/server/src/mcp/instructions.ts b/packages/server/src/mcp/instructions.ts
index e74e8dd24..628e2bb61 100644
--- a/packages/server/src/mcp/instructions.ts
+++ b/packages/server/src/mcp/instructions.ts
@@ -13,7 +13,7 @@ When this workspace has Open Knowledge MCP configured, do **not** use your host'
- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native \`Read\` / \`Grep\` / \`Glob\` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via \`exec\` / \`search\`. Subagents remain appropriate for **source-code** exploration.
- **Native \`Read\` / \`Grep\` on any in-scope markdown inside \`.ok/\`** — the \`.ok/\` directory is in-scope; if it carries \`.md\` / \`.mdx\`, treat those the same as any other knowledge-base file.
-Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK's tools return for every matched knowledge-base file. \`exec\` is the primary read surface; it runs read-only bash (\`cat\`, \`ls\`, \`grep\`, \`find\`, \`head\`, \`tail\`, \`wc\`, \`sort\`, \`uniq\`, \`cut\` — pipes OK) and returns raw stdout plus enriched metadata per file.
+Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK's tools return for every matched knowledge-base file. \`exec\` is the primary read surface; it runs read-only bash (\`cat\`, \`ls\`, \`grep\`, \`find\`, \`head\`, \`tail\`, \`wc\`, \`sort\`, \`uniq\`, \`cut\`) and returns raw stdout plus enriched metadata per file. One command or a pipe (\`|\`) per call — it is NOT a shell, so \`&&\` / \`;\` / redirects are rejected; list several dirs with \`ls -A a b c\` or make separate calls.
**MCP tool visibility — not seeing \`exec\` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named \`exec\` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its \`exec\` / \`search\` via your client's documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.
@@ -38,10 +38,10 @@ The user watches your edits land in a live browser preview. Open it once at sess
**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.
-- **You have \`preview_*\` tools** (e.g. \`preview_start\` + \`preview_eval\`) → **First open of the session:** to land directly on a doc, arm it first with \`get_preview_url({ armPaneTarget: true, docName })\` (or \`folder\`), then \`preview_start("open-knowledge-ui")\` — \`ok ui\` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain \`preview_start\` (no arm) opens at root. **Moving between docs once the pane is open: do it in one \`preview_eval\` step — set \`window.location.hash\` to the target's route fragment from the response \`previewUrl\`, the part from \`#\` on (e.g. \`window.location.hash = '#/specs/foo/SPEC'\`).** That drives the SPA router directly. Arm + \`preview_start\` only redirects a *fresh* open; it can't move an already-open pane (\`preview_start\` reuses the live process without reloading), so use \`preview_eval\` there. Don't read or edit \`.claude/launch.json\` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If \`preview_start\` fails, report it; don't "fix" \`launch.json\`.
-- **No \`preview_*\` tool, but you have an in-app / built-in browser tool** — Codex's built-in browser, or any host tool that navigates to a URL (\`browser\`, \`view_url\`, \`open_url\`, \`web.browse\`, etc.) → call \`get_preview_url\` once for the **exact** target (\`docName\` for a doc, \`folder\` for a folder) and navigate your **in-app browser** straight to the returned \`url\`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.
-- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open \`<doc>\`/\`<folder>\`" request, run **\`ok open <doc>\`** (\`--folder\` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No \`ok\` on PATH or no shell → \`get_preview_url\`, then \`open <url>\` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.
-- **Honor \`autoOpen\`** (on \`get_preview_url\`, or on \`warning\` for write tools). If \`false\`, do not open or refresh any preview UI; surface the URL only if asked.
+- **You have \`preview_*\` tools** (e.g. \`preview_start\` + \`preview_eval\`) → **First open of the session:** to land directly on a doc, arm it first with \`preview_url({ armPaneTarget: true, document })\` (or \`folder\`), then \`preview_start("open-knowledge-ui")\` — \`ok ui\` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain \`preview_start\` (no arm) opens at root. **Moving between docs once the pane is open: do it in one \`preview_eval\` step — set \`window.location.hash\` to the target's route fragment from the response \`previewUrl\`, the part from \`#\` on (e.g. \`window.location.hash = '#/specs/foo/SPEC'\`).** That drives the SPA router directly. Arm + \`preview_start\` only redirects a *fresh* open; it can't move an already-open pane (\`preview_start\` reuses the live process without reloading), so use \`preview_eval\` there. Don't read or edit \`.claude/launch.json\` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If \`preview_start\` fails, report it; don't "fix" \`launch.json\`.
+- **No \`preview_*\` tool, but you have an in-app / built-in browser tool** — Codex's built-in browser, or any host tool that navigates to a URL (\`browser\`, \`view_url\`, \`open_url\`, \`web.browse\`, etc.) → call \`preview_url\` once for the **exact** target (\`document\` for a doc, \`folder\` for a folder) and navigate your **in-app browser** straight to the returned \`url\`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.
+- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open \`<doc>\`/\`<folder>\`" request, run **\`ok open <doc>\`** (\`--folder\` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No \`ok\` on PATH or no shell → \`preview_url\`, then \`open <url>\` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.
+- **Honor \`autoOpen\`** (on \`preview_url\`, or on \`warning\` for write tools). If \`false\`, do not open or refresh any preview UI; surface the URL only if asked.
**Opening or reading a file IS a preview navigation.** On any "open \`<file>\`" / "read \`<file>\`" request, navigate the browser to that doc's \`previewUrl\` route from the tool response — not a separate fetch, not a fresh system-browser launch.
@@ -49,12 +49,12 @@ The user watches your edits land in a live browser preview. Open it once at sess
1. You opened/navigated earlier this session → don't reopen.
2. Write response has \`previewUrl\` (non-null route) and NO \`warning\` → a browser is attached somewhere; do nothing.
-3. \`warning: { action: "attach-preview-once", previewUrl, message }\` → UI reachable, no browser attached; navigate one-shot (\`preview_start\`, or \`get_preview_url\` → in-app browser).
+3. \`warning: { action: "attach-preview-once", previewUrl, message }\` → UI reachable, no browser attached; navigate one-shot (\`preview_start\`, or \`preview_url\` → in-app browser).
4. \`warning: { action: "start-ui", previewUrl: null, message }\` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don't loop on retries.
Warnings fire at most once per session in the fresh-start case.
-**\`previewUrl: null\` only means "no UI reachable" on the three attach-warning tools: \`write_document\` / \`edit_document\` / \`edit_frontmatter\`.** Workflow tools return prose and don't carry \`previewUrl\`. \`delete_document\` / \`rename\` emit \`previousPreviewUrl\` (different field, for closing stale tabs) and don't fire attach warnings. \`get_preview_url\` reports \`running: false\` + \`url: null\` when no UI is running.
+**\`previewUrl: null\` only means "no UI reachable" on the two attach-warning tools: \`write\` / \`edit\`.** Workflow tools return prose and don't carry \`previewUrl\`. \`delete\` / \`move\` emit \`previousPreviewUrl\` (different field, for closing stale tabs) and don't fire attach warnings. \`preview_url\` reports \`running: false\` + \`url: null\` when no UI is running.
If you see \`"Hocuspocus server is not running"\`, run \`ok start\` and retry.
@@ -66,11 +66,11 @@ OK Electron and \`ok ui\` share \`ui.lock\`; when a second UI binds a different
## Scope recap
-Open Knowledge looks for documents under the resolved \`content.dir\` (discoverable at runtime via \`get_config({ path: ['content', 'dir'] })\`). \`.gitignore\` and \`.okignore\` (at the project root and at any folder depth) define exclusions. A folder's own metadata + templates live in nested \`<folder>/.ok/frontmatter.yml\` + \`<folder>/.ok/templates/\` — NOT in \`.ok/config.yml\`.
+Open Knowledge looks for documents under the resolved \`content.dir\` (discoverable at runtime via \`config({ key: 'content.dir' })\`). \`.gitignore\` and \`.okignore\` (at the project root and at any folder depth) define exclusions. A folder's own metadata + templates live in nested \`<folder>/.ok/frontmatter.yml\` + \`<folder>/.ok/templates/\` — NOT in \`.ok/config.yml\`.
Default mental model (no jargon): **every \`.md\` and \`.mdx\` under \`content.dir\`** not excluded by \`.gitignore\` or \`.okignore\` is an Open Knowledge document — including under \`specs/\`, \`reports/\`, \`docs/\`, etc. Read \`.okignore\` (and any nested \`.okignore\` files) once per turn to know what's excluded.
-**First session in this project?** If substantial folders have no frontmatter of their own and no \`templates_available\`, the project isn't onboarded — invoke \`discover\` (Workflow tools table) before writing.
+**First session in this project?** If substantial folders have no frontmatter of their own and no \`templates_available\`, the project isn't onboarded — invoke \`workflow({ kind: 'discover' })\` before writing.
Full guidance lives in the bundled \`open-knowledge\` skill at \`~/.ok/skills/open-knowledge/SKILL.md\`.
diff --git a/packages/server/src/mcp/logger.test.ts b/packages/server/src/mcp/logger.test.ts
index 0db250282..ede8d3221 100644
--- a/packages/server/src/mcp/logger.test.ts
+++ b/packages/server/src/mcp/logger.test.ts
@@ -101,7 +101,7 @@ describe('McpLogger', () => {
const logger = new McpLogger('mcp');
logger.info('tool finish', {
- tool: 'get_preview_url',
+ tool: 'preview_url',
requestId: 'req-123',
result: {
previewUrl: 'http://localhost:4242/#/notes/test',
@@ -111,14 +111,14 @@ describe('McpLogger', () => {
const stderrEntry = JSON.parse(stderrLines[0] ?? '');
expect(stderrEntry.msg).toBe('tool finish');
- expect(stderrEntry.tool).toBe('get_preview_url');
+ expect(stderrEntry.tool).toBe('preview_url');
const fileLine = readFileSync(logFile, 'utf-8');
expect(fileLine).toBe(stderrLines[0]);
const fileEntry = JSON.parse(fileLine);
expect(fileEntry.msg).toBe('tool finish');
- expect(fileEntry.tool).toBe('get_preview_url');
+ expect(fileEntry.tool).toBe('preview_url');
expect(fileEntry.requestId).toBe('req-123');
expect(fileEntry.result).toEqual({
previewUrl: 'http://localhost:4242/#/notes/test',
@@ -136,7 +136,7 @@ describe('McpLogger', () => {
logger.info('small context', { backoffMs: 8000, attempt: 3 });
logger.info('large context', {
- tool: 'get_preview_url',
+ tool: 'preview_url',
result: {
previewUrl: 'http://localhost:4242/#/notes/very/long/path/test',
previewUrlSource: 'lock',
@@ -156,7 +156,7 @@ describe('McpLogger', () => {
});
expect(largeEntry).toMatchObject({
msg: 'large context',
- tool: 'get_preview_url',
+ tool: 'preview_url',
requestId: 'req-123',
result: {
previewUrl: 'http://localhost:4242/#/notes/very/long/path/test',
diff --git a/packages/server/src/mcp/tool-logging.test.ts b/packages/server/src/mcp/tool-logging.test.ts
index 5429a1e6a..58e345b22 100644
--- a/packages/server/src/mcp/tool-logging.test.ts
+++ b/packages/server/src/mcp/tool-logging.test.ts
@@ -113,7 +113,7 @@ describe('tool logging wrapper', () => {
expect(
(wrapped as unknown as { tool: (...args: unknown[]) => unknown }).tool(
- 'get_preview_url',
+ 'preview_url',
'desc',
{ docName: 'string' },
originalHandler,
@@ -133,7 +133,7 @@ describe('tool logging wrapper', () => {
);
const finish = JSON.parse(stderrLines[1] ?? '');
- expect(finish.tool).toBe('get_preview_url');
+ expect(finish.tool).toBe('preview_url');
expect(finish.result.previewUrl).toBeNull();
});
diff --git a/packages/server/src/mcp/tools/checkpoint.test.ts b/packages/server/src/mcp/tools/checkpoint.test.ts
new file mode 100644
index 000000000..fcd9ca563
--- /dev/null
+++ b/packages/server/src/mcp/tools/checkpoint.test.ts
@@ -0,0 +1,114 @@
+import {
+ describe as _bunDescribe,
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+} from 'bun:test';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { type CheckpointDeps, DESCRIPTION, register } from './checkpoint.ts';
+import type { ServerInstance } from './shared.ts';
+import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
+
+const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: boolean;
+}
+interface RegisteredTool {
+ name: string;
+ description: string;
+ handler: (args: { summary?: string; cwd?: string }) => Promise<ToolResult>;
+}
+
+function createFakeServer() {
+ let registered: RegisteredTool | undefined;
+ const server = {
+ registerTool(name: string, cfg: { description?: string }, handler: RegisteredTool['handler']) {
+ registered = { name, description: cfg.description ?? '', handler };
+ },
+ } as unknown as ServerInstance;
+ return {
+ server,
+ getTool(): RegisteredTool {
+ if (!registered) throw new Error('Tool was not registered');
+ return registered;
+ },
+ };
+}
+
+function makeDeps(serverUrl: string | undefined, cwdDir: string): CheckpointDeps {
+ return { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwdDir };
+}
+
+let testServer: ReturnType<typeof Bun.serve>;
+let baseUrl: string;
+let tmpDir: string;
+const seenBodies: Array<Record<string, unknown>> = [];
+
+beforeAll(() => {
+ testServer = Bun.serve({
+ port: 0,
+ async fetch(req) {
+ const url = new URL(req.url);
+ const body = req.method === 'POST' ? ((await req.json()) as Record<string, unknown>) : {};
+ if (req.method === 'POST') seenBodies.push(body);
+ if (url.pathname === '/api/save-version' && req.method === 'POST') {
+ return Response.json({
+ ok: true,
+ checkpointRef: 'refs/checkpoints/main/1234567890abcdef1234567890abcdef12345678',
+ });
+ }
+ return new Response('Not found', { status: 404 });
+ },
+ });
+ baseUrl = `http://localhost:${testServer.port}`;
+});
+afterAll(() => testServer.stop());
+beforeEach(async () => {
+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-checkpoint-test-'));
+ seenBodies.length = 0;
+});
+afterEach(async () => {
+ await rm(tmpDir, { recursive: true, force: true });
+});
+
+describe('checkpoint — registration + behavior', () => {
+ test('registers exactly one tool named "checkpoint"', () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ expect(getTool().name).toBe('checkpoint');
+ expect(DESCRIPTION).toContain('project-wide');
+ });
+
+ test('hits POST /api/save-version and returns version + null previewUrl', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const result = await getTool().handler({});
+ expect(result.structuredContent?.version).toBe('1234567890abcdef1234567890abcdef12345678');
+ expect(result.structuredContent?.previewUrl).toBeNull();
+ });
+
+ test('summary is forwarded in the save-version body when present', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ await getTool().handler({ summary: 'Pre-refactor checkpoint' });
+ expect(seenBodies[0]?.summary).toBe('Pre-refactor checkpoint');
+ });
+
+ test('returns Hocuspocus-unavailable error when no serverUrl is configured', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(undefined, tmpDir));
+ const result = await getTool().handler({});
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+});
diff --git a/packages/server/src/mcp/tools/checkpoint.ts b/packages/server/src/mcp/tools/checkpoint.ts
new file mode 100644
index 000000000..a18cd2e35
--- /dev/null
+++ b/packages/server/src/mcp/tools/checkpoint.ts
@@ -0,0 +1,93 @@
+import { z } from 'zod';
+import type { AgentIdentity } from '../agent-identity.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpPost,
+ outputSchemaWithText,
+ previewUrlOutputField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ textPlusStructured,
+ textResult,
+ VERSION_FIELD_DESCRIBE,
+} 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 })`.',
+].join('\n');
+
+export interface CheckpointDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+export function register(server: ServerInstance, deps: CheckpointDeps): void {
+ server.registerTool(
+ 'checkpoint',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ summary: summaryArgSchema.describe(
+ 'Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.',
+ ),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ version: z.string().describe(VERSION_FIELD_DESCRIBE),
+ previewUrl: previewUrlOutputField.describe(
+ 'Always null — a checkpoint is project-wide, not scoped to one doc.',
+ ),
+ }),
+ },
+ async (args: { summary?: 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 identity = deps.identityRef?.current;
+ const result = await httpPost(url, '/api/save-version', {
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...(identity
+ ? {
+ writers: [
+ {
+ id: `agent-${identity.connectionId}`,
+ name: identity.displayName,
+ email: `agent-${identity.connectionId}@openknowledge.local`,
+ },
+ ],
+ }
+ : {}),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+
+ const checkpointRef = typeof result.checkpointRef === 'string' ? result.checkpointRef : '';
+ const version = checkpointRef.split('/').pop() ?? '';
+ if (!/^[0-9a-f]{40}$/i.test(version)) {
+ return textResult(
+ `Error: checkpoint committed but the server returned no usable version ref ("${checkpointRef}"). Find the latest checkpoint via \`history\`.`,
+ true,
+ );
+ }
+ return textPlusStructured(`Checkpoint saved. Version: ${version}`, {
+ version,
+ previewUrl: null,
+ });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/get-config.test.ts b/packages/server/src/mcp/tools/config.test.ts
similarity index 86%
rename from packages/server/src/mcp/tools/get-config.test.ts
rename to packages/server/src/mcp/tools/config.test.ts
index 95510df7e..9f2ce6388 100644
--- a/packages/server/src/mcp/tools/get-config.test.ts
+++ b/packages/server/src/mcp/tools/config.test.ts
@@ -6,7 +6,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './get-config.ts';
+import { register } from './config.ts';
import type { ServerInstance } from './shared.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({
@@ -21,7 +21,7 @@ interface ToolResult {
isError?: boolean;
}
-type ToolHandler = (args: { path?: string[]; cwd?: string }) => Promise<ToolResult>;
+type ToolHandler = (args: { key?: string; cwd?: string }) => Promise<ToolResult>;
function captureRegistration(cwd: string, configOverride?: Partial<Config>): ToolHandler {
let captured: ToolHandler | null = null;
@@ -30,7 +30,7 @@ function captureRegistration(cwd: string, configOverride?: Partial<Config>): Too
captured = handler;
},
tool() {
- throw new Error('legacy tool() should not be called by get_config');
+ throw new Error('legacy tool() should not be called by config');
},
} as unknown as ServerInstance;
register(server, {
@@ -41,7 +41,7 @@ function captureRegistration(cwd: string, configOverride?: Partial<Config>): Too
return captured;
}
-describe('get_config tool', () => {
+describe('config tool', () => {
test('returns the full effective merged config when path is omitted', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
@@ -55,7 +55,7 @@ describe('get_config tool', () => {
test('returns sub-tree when path is provided', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
- const result = await handler({ path: ['appearance'] });
+ const result = await handler({ key: 'appearance' });
const value = result.structuredContent?.value as { theme: string };
expect(value.theme).toBe('dark');
});
@@ -63,14 +63,14 @@ describe('get_config tool', () => {
test('returns scalar leaf when path resolves to a primitive', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
- const result = await handler({ path: ['content', 'dir'] });
+ const result = await handler({ key: 'content.dir' });
expect(result.structuredContent?.value).toBe('.');
});
test('returns null + exists:false for a nonexistent path', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
- const result = await handler({ path: ['nonexistent', 'leaf'] });
+ const result = await handler({ key: 'nonexistent.leaf' });
expect(result.structuredContent?.value).toBeNull();
expect(result.structuredContent?.exists).toBe(false);
expect(result.content[0]?.text).toContain('no value at nonexistent.leaf');
@@ -79,14 +79,14 @@ describe('get_config tool', () => {
test('content[0].text is JSON-serialized for agent consumption', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
- const result = await handler({ path: ['appearance', 'theme'] });
+ const result = await handler({ key: 'appearance.theme' });
expect(result.content[0]?.text).toBe('"dark"');
});
test('reads any field — no allowlist gating on read', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
const handler = captureRegistration(cwd);
- const result = await handler({ path: ['appearance', 'theme'] });
+ const result = await handler({ key: 'appearance.theme' });
expect(result.isError).toBeUndefined();
expect(result.structuredContent?.value).toBe('dark');
});
@@ -114,7 +114,7 @@ describe('get_config tool', () => {
});
if (!captured) throw new Error('tool not registered');
const result = await (captured as ToolHandler)({
- path: ['appearance', 'theme'],
+ key: 'appearance.theme',
});
expect(result.structuredContent?.value).toBe('light');
});
diff --git a/packages/server/src/mcp/tools/get-config.ts b/packages/server/src/mcp/tools/config.ts
similarity index 61%
rename from packages/server/src/mcp/tools/get-config.ts
rename to packages/server/src/mcp/tools/config.ts
index 063ee8dd9..88f9c2ec9 100644
--- a/packages/server/src/mcp/tools/get-config.ts
+++ b/packages/server/src/mcp/tools/config.ts
@@ -12,12 +12,12 @@ export const DESCRIPTION = [
'',
'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 `path` is provided. There is no allowlist on reads — every field is readable.',
+ '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.*`, `github.*`, and `preview.*` config sub-trees were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or hardcoded behavior, in the case of `preview.*`). Reading those paths returns `exists: false`.',
+ 'Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core`. Reading those keys returns `exists: false`. (`preview.scriptSrc` and `appearance.preview.autoOpen` are still live keys.)',
'',
'**Parameters:**',
- '- `path` (optional) — Dotted-segments array. `["content"]` returns the content sub-tree; `["appearance", "theme"]` returns just that leaf. Omit for full config.',
+ '- `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).',
].join('\n');
@@ -27,11 +27,11 @@ interface GetConfigDeps {
}
const InputSchema = {
- path: z
- .array(z.string())
+ key: z
+ .string()
.optional()
.describe(
- 'Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.',
+ 'Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.',
),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
} as const;
@@ -43,12 +43,12 @@ const OutputSchema = outputSchemaWithText({
.optional()
.describe(
'Whether the requested path resolved to a value. `false` distinguishes ' +
- '"path absent" from "path explicitly set to null"; absent on full-config reads.',
+ '"path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.',
),
- path: z
- .array(z.string())
+ key: z
+ .string()
.optional()
- .describe('Echo of the requested dotted path (empty when reading the full config).'),
+ .describe('Echo of the requested dotted key (absent when reading the full config).'),
});
function readConfigPath(value: unknown, path: readonly string[]): unknown {
@@ -63,7 +63,7 @@ function readConfigPath(value: unknown, path: readonly string[]): unknown {
export function register(server: ServerInstance, deps: GetConfigDeps): void {
server.registerTool(
- 'get_config',
+ 'config',
{
description: DESCRIPTION,
inputSchema: InputSchema,
@@ -73,7 +73,7 @@ export function register(server: ServerInstance, deps: GetConfigDeps): void {
idempotentHint: true,
},
},
- async (args: { path?: string[]; cwd?: string }) => {
+ async (args: { key?: string; cwd?: string }) => {
const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
if (!context.ok) {
return {
@@ -81,16 +81,20 @@ export function register(server: ServerInstance, deps: GetConfigDeps): void {
content: [{ type: 'text' as const, text: `Error: ${context.error}` }],
};
}
- const path = args.path ?? [];
- const value = path.length > 0 ? readConfigPath(context.config, path) : context.config;
- if (path.length > 0 && value === undefined) {
- return textPlusStructured(`(no value at ${path.join('.')})`, {
+ const segments = args.key ? args.key.split('.').filter((s) => s.length > 0) : [];
+ const value = segments.length > 0 ? readConfigPath(context.config, segments) : context.config;
+ if (segments.length > 0 && value === undefined) {
+ return textPlusStructured(`(no value at ${args.key})`, {
value: null,
exists: false,
- path,
+ ...(args.key ? { key: args.key } : {}),
});
}
- return textPlusStructured(JSON.stringify(value, null, 2), { value, exists: true, path });
+ return textPlusStructured(JSON.stringify(value, null, 2), {
+ value,
+ exists: true,
+ ...(args.key ? { key: args.key } : {}),
+ });
},
);
}
diff --git a/packages/server/src/mcp/tools/conflicts.test.ts b/packages/server/src/mcp/tools/conflicts.test.ts
new file mode 100644
index 000000000..9582203c8
--- /dev/null
+++ b/packages/server/src/mcp/tools/conflicts.test.ts
@@ -0,0 +1,96 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { register } from './conflicts.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, _c: unknown, h: Handler) {
+ handler = h;
+ },
+ } as unknown as ServerInstance;
+ register(server, { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwd });
+ if (!handler) throw new Error('not registered');
+ return handler;
+}
+
+let testServer: ReturnType<typeof Bun.serve>;
+let baseUrl: string;
+const cwd = mkdtempSync(join(tmpdir(), 'ok-conflicts-test-'));
+
+beforeAll(() => {
+ testServer = Bun.serve({
+ port: 0,
+ 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' }],
+ });
+ }
+ 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',
+ lifecycleStatus: 'conflict',
+ });
+ }
+ return new Response('Not found', { status: 404 });
+ },
+ });
+ baseUrl = `http://localhost:${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(Array.isArray(result.structuredContent?.list)).toBe(true);
+ expect(result.content[0]?.text).toContain('notes/sso.md');
+ });
+
+ 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).not.toHaveProperty('kind');
+ expect(result.content[0]?.text).toContain('shape: both-modified');
+ });
+
+ 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.ts
new file mode 100644
index 000000000..0f99d5523
--- /dev/null
+++ b/packages/server/src/mcp/tools/conflicts.ts
@@ -0,0 +1,133 @@
+import { z } from 'zod';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpGet,
+ looseObjectArray,
+ outputSchemaWithText,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+
+export const DESCRIPTION = [
+ '[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:',
+ '',
+ '- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.',
+ '- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',
+ '',
+ '**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.',
+ '',
+ '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: looseObjectArray
+ .optional()
+ .describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),
+ 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.'),
+ lifecycleStatus: z.string().nullable().describe("The doc's lifecycle status, or null."),
+ })
+ .optional()
+ .describe('`kind: "content"` — the three merge stages + shape + lifecycle.'),
+ }),
+ 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 lifecycleStatus =
+ typeof rec.lifecycleStatus === 'string' ? rec.lifecycleStatus : null;
+ const lifecycleSuffix = lifecycleStatus ? ` (lifecycle: ${lifecycleStatus})` : '';
+ const text = `Conflict stages for ${file} (shape: ${shape})${lifecycleSuffix}:\n--- base ---\n${base}\n--- ours ---\n${ours}\n--- theirs ---\n${theirs}`;
+ return textPlusStructured(text, {
+ content: { file, base, ours, theirs, shape, lifecycleStatus },
+ });
+ }
+
+ 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 file =
+ row && typeof row === 'object' && 'file' in row
+ ? String((row as Record<string, unknown>).file ?? '')
+ : '';
+ return `- ${file}`;
+ })
+ .join('\n')}`;
+ return textPlusStructured(text, { list: conflicts });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/consolidate.ts b/packages/server/src/mcp/tools/consolidate-body.ts
similarity index 87%
rename from packages/server/src/mcp/tools/consolidate.ts
rename to packages/server/src/mcp/tools/consolidate-body.ts
index 4dd235d33..8ecf9d004 100644
--- a/packages/server/src/mcp/tools/consolidate.ts
+++ b/packages/server/src/mcp/tools/consolidate-body.ts
@@ -1,9 +1,6 @@
import { OK_DIR } from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import type { ServerInstance, WorkflowToolDeps } from './shared.ts';
-import { buildWorkflowHandler, ROUTED_CWD_DESCRIPTION } from './shared.ts';
-function buildBody(topic: string, contentDir: string): string {
+export function buildConsolidateBody(topic: string, contentDir: string): string {
return `Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
Topic: ${topic}
@@ -153,23 +150,3 @@ superseded_by: <path-to-new-canonical-article>.md
- **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
`;
}
-
-export const DESCRIPTION = [
- 'Returns a step-by-step plan to promote stabilized research into a canonical article. Does NOT write — you execute the plan after a STOP gate confirms a real decision was made.',
- 'Canonical, not provisional — the output becomes the source of truth, with a `supersedes` trail back to the research.',
- 'Use when a team has decided after research and wants the outcome committed as authoritative knowledge.',
-].join('\n');
-
-export function register(server: ServerInstance, deps: WorkflowToolDeps): void {
- server.registerTool(
- 'consolidate',
- {
- description: DESCRIPTION,
- inputSchema: {
- topic: z.string().describe('The topic to consolidate into a canonical article'),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- buildWorkflowHandler('consolidate', deps, 'topic', buildBody),
- );
-}
diff --git a/packages/server/src/mcp/tools/consolidate.test.ts b/packages/server/src/mcp/tools/consolidate.test.ts
deleted file mode 100644
index f23d3d394..000000000
--- a/packages/server/src/mcp/tools/consolidate.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe as _bunDescribe, expect, test } from 'bun:test';
-
-const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './consolidate.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
-}
-
-function captureTool() {
- let captured: ((args: { topic: string; cwd?: string }) => Promise<ToolResult>) | undefined;
- const server = {
- registerTool(
- _name: string,
- _config: unknown,
- handler: (args: { topic: string; cwd?: string }) => Promise<ToolResult>,
- ) {
- captured = handler;
- },
- } as unknown as ServerInstance;
- return {
- server,
- async call(topic: string) {
- if (!captured) throw new Error('Tool was not registered');
- return await captured({ topic });
- },
- };
-}
-
-describe('consolidate — previewUrl emission', () => {
- test('returns structuredContent with previewUrl: null (workflow primer)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('CRDT architecture');
- expect(result.structuredContent).toMatchObject({ previewUrl: null });
- expect(result.content[0]?.text).toContain('CRDT architecture');
- });
-});
diff --git a/packages/server/src/mcp/tools/content-divergence.ts b/packages/server/src/mcp/tools/content-divergence.ts
new file mode 100644
index 000000000..e483eb44b
--- /dev/null
+++ b/packages/server/src/mcp/tools/content-divergence.ts
@@ -0,0 +1,21 @@
+import { WriteWarningSchema } from '@inkeep/open-knowledge-core';
+import type { z } from 'zod';
+
+export type ContentDivergence = z.infer<typeof WriteWarningSchema>;
+
+export function parseContentDivergence(warning: unknown): ContentDivergence | undefined {
+ const parsed = WriteWarningSchema.safeParse(warning);
+ return parsed.success ? parsed.data : undefined;
+}
+
+export function formatContentDivergenceLine(d: ContentDivergence): string {
+ return d.kind === 'content-divergence'
+ ? `⚠ Content divergence: ${d.actualBytes} actual bytes vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}). ${d.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
+ : `⚠ ${d.hint ?? 'An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.'}`;
+}
+
+export function formatContentDivergenceBrief(d: ContentDivergence): string {
+ return d.kind === 'content-divergence'
+ ? `⚠ Content divergence: ${d.actualBytes} actual vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}).`
+ : '⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.';
+}
diff --git a/packages/server/src/mcp/tools/delete-document.test.ts b/packages/server/src/mcp/tools/delete-document.test.ts
deleted file mode 100644
index 69f72252b..000000000
--- a/packages/server/src/mcp/tools/delete-document.test.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { type DeleteDocumentDeps, register } from './delete-document.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.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;
- description: string;
- handler: (args: Record<string, unknown>) => Promise<ToolResult>;
-}
-
-function createCapturingServer() {
- const registrations: RegisteredTool[] = [];
- const server = {
- registerTool(
- name: string,
- config: { description?: string },
- handler: RegisteredTool['handler'],
- ) {
- registrations.push({ name, description: config.description ?? '', handler });
- },
- } as unknown as ServerInstance;
- return { server, registrations };
-}
-
-function getRegisteredTool(registrations: RegisteredTool[], name: string): RegisteredTool {
- const tool = registrations.find((registration) => registration.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-delete-doc-'));
-});
-
-afterEach(async () => {
- globalThis.fetch = originalFetch;
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-function makeDeps(serverUrl: DeleteDocumentDeps['serverUrl']): DeleteDocumentDeps {
- return {
- serverUrl,
- config: BASE_CONFIG,
- resolveCwd: async () => tmpDir,
- };
-}
-
-describe('delete_document MCP tool', () => {
- test('normalizes trailing markdown extensions before calling the API', 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, deletedDocNames: ['old-page'] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- }) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'old-page.md' });
-
- expect(fetchCalls).toHaveLength(1);
- expect(fetchCalls[0]?.input).toBe('http://localhost:4321/api/delete-path');
- expect(JSON.parse(String(fetchCalls[0]?.init?.body))).toEqual({
- kind: 'file',
- path: 'old-page',
- });
- expect(result.isError).toBeUndefined();
- expect(result.content[0]?.text).toContain('old-page');
- });
-
- test('rejects unsupported markdown extensions before calling the API', async () => {
- const { server, registrations } = createCapturingServer();
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'old-page.markdown' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('.markdown');
- });
-
- test('returns deletedDocNames on success', async () => {
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: true, deletedDocNames: ['notes/draft'] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'notes/draft' });
-
- expect(tool.description).toContain('/api/delete-path');
- expect(result.isError).toBeUndefined();
- expect(result.content[0]?.text).toBe('Deleted notes/draft.');
- expect(result.structuredContent).toMatchObject({
- ok: true,
- deletedDocNames: ['notes/draft'],
- });
- });
-
- test('falls back to the requested docName when server returns no deletedDocNames', async () => {
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: true }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'old-page' });
-
- expect(result.isError).toBeUndefined();
- expect(result.structuredContent).toMatchObject({
- ok: true,
- deletedDocNames: ['old-page'],
- });
- });
-
- test('surfaces 404 when the document does not exist', async () => {
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: false, error: 'file does not exist' }), {
- status: 404,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'missing-page' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('file does not exist');
- expect(result.structuredContent).toMatchObject({
- ok: false,
- error: 'file does not exist',
- });
- });
-
- test('forwards identity fields in the POST body when identityRef is provided', async () => {
- const { server, registrations } = createCapturingServer();
- const fetchCalls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];
-
- globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
- fetchCalls.push({ input, init });
- return new Response(JSON.stringify({ ok: true, deletedDocNames: ['page'] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- }) as typeof fetch;
-
- const deps: DeleteDocumentDeps = {
- ...makeDeps('http://localhost:4321'),
- identityRef: {
- current: {
- connectionId: 'conn-1',
- displayName: 'TestAgent',
- clientInfo: { name: 'claude-code', version: '1.0.0' },
- colorSeed: '42',
- } as AgentIdentity,
- },
- };
-
- register(server, deps);
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- await tool.handler({ docName: 'page' });
-
- const body = JSON.parse(String(fetchCalls[0]?.init?.body));
- expect(body).toMatchObject({
- kind: 'file',
- path: 'page',
- agentId: 'conn-1',
- agentName: 'TestAgent',
- clientName: 'claude-code',
- colorSeed: '42',
- });
- });
-
- test('canonicalizer synthesizes generic HTTP-status `error` when body has neither `error` nor `message`', async () => {
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: false }), {
- status: 500,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'page' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe('Error: Server returned HTTP 500');
- expect(result.structuredContent).toMatchObject({
- ok: false,
- error: 'Server returned HTTP 500',
- });
- });
-
- 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 = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'old-page' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
- });
-
- test('emits route-only previousPreviewUrl for the deleted docName when a preview source resolves', async () => {
- bindTestUiLock(tmpDir);
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: true, deletedDocNames: ['old-page'] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'old-page' });
-
- expect(result.structuredContent).toMatchObject({
- ok: true,
- deletedDocNames: ['old-page'],
- previousPreviewUrl: '/#/old-page',
- });
- });
-});
-
-describe('delete_document — batch (docNames)', () => {
- test('deletes each doc and reports per-doc results', async () => {
- const { server, registrations } = createCapturingServer();
- const deletedPaths: string[] = [];
-
- globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
- const body = JSON.parse(String(init?.body));
- deletedPaths.push(body.path);
- return new Response(JSON.stringify({ ok: true, deletedDocNames: [body.path] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- }) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docNames: ['a', 'notes/b', 'c'] });
-
- expect(result.isError).toBeUndefined();
- expect(deletedPaths.sort()).toEqual(['a', 'c', 'notes/b']);
- const s = result.structuredContent as {
- ok: boolean;
- documents: Array<{ docName: string; ok: boolean }>;
- };
- expect(s.ok).toBe(true);
- expect(s.documents).toHaveLength(3);
- expect(s.documents.every((d) => d.ok)).toBe(true);
- expect(result.content[0]?.text).toContain('3/3 deleted');
- });
-
- test('a per-doc failure surfaces without blocking the rest', async () => {
- const { server, registrations } = createCapturingServer();
-
- globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
- const body = JSON.parse(String(init?.body));
- if (body.path === 'missing') {
- return new Response(JSON.stringify({ ok: false, error: 'file does not exist' }), {
- status: 404,
- headers: { 'Content-Type': 'application/json' },
- });
- }
- return new Response(JSON.stringify({ ok: true, deletedDocNames: [body.path] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- }) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docNames: ['ok-doc', 'missing'] });
-
- expect(result.isError).toBe(true);
- const s = result.structuredContent as {
- ok: boolean;
- documents: Array<{ docName: string; ok: boolean; error?: string }>;
- };
- expect(s.ok).toBe(false);
- expect(s.documents.find((d) => d.docName === 'ok-doc')?.ok).toBe(true);
- expect(s.documents.find((d) => d.docName === 'missing')?.error).toContain(
- 'file does not exist',
- );
- });
-
- test('docName and docNames together is rejected', async () => {
- const { server, registrations } = createCapturingServer();
- register(server, makeDeps('http://localhost:4321'));
- const tool = getRegisteredTool(registrations, 'delete_document');
-
- const result = await tool.handler({ docName: 'a', docNames: ['b'] });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('mutually exclusive');
- });
-});
diff --git a/packages/server/src/mcp/tools/delete-document.ts b/packages/server/src/mcp/tools/delete-document.ts
deleted file mode 100644
index 5dee27abb..000000000
--- a/packages/server/src/mcp/tools/delete-document.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { z } from 'zod';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { resolvePreviewUrlForTool } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpPost,
- normalizeDocName,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-interface DeleteDocumentSuccess {
- ok: true;
- deletedDocNames: string[];
- /** Preview URL that used to resolve to the now-deleted doc. Lets agents
- * close the stale preview tab. Mirrors `rename`'s `previousPreviewUrl`. */
- previousPreviewUrl?: string;
-}
-
-interface DeleteDocumentError {
- ok: false;
- error: string;
-}
-
-export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).',
- 'Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.',
- '',
- '**Parameters:**',
- '- `docName` — A single document to delete, typically extension-less. A trailing `.md` or `.mdx` is stripped automatically.',
- '- `docNames` — Batch form: an array of documents to delete in one call. Mutually exclusive with `docName`. Each is deleted independently; the response reports per-doc status.',
- '',
- '**Notes:**',
- '- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `links({ kind: "backlinks", docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.',
- '- Deletion is irreversible from this tool. Use `version({ action: "save" })` beforehand if you may need to roll back.',
- '- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.',
- '',
- '**Errors:**',
- '- 400 — `docName` is not a valid relative content path.',
- '- 404 — document does not exist.',
-].join('\n');
-
-export interface DeleteDocumentDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- /** Identity passthrough for attribution threading. The server-side handler
- * calls `extractAgentIdentity(body)` even though it does not currently
- * surface the agent in the response — keep the field so future
- * timeline/audit work picks up MCP-driven deletes correctly. */
- identityRef?: { current: AgentIdentity };
-}
-
-interface DeleteOneResult {
- docName: string;
- ok: boolean;
- deletedDocNames?: string[];
- previousPreviewUrl?: string;
- error?: string;
-}
-
-function parseDeletedDocNames(value: unknown): string[] {
- if (!Array.isArray(value)) return [];
- return value.filter((entry): entry is string => typeof entry === 'string');
-}
-
-async function deleteOne(
- rawDocName: string,
- url: string,
- cwd: string,
- deps: DeleteDocumentDeps,
-): Promise<DeleteOneResult> {
- const normalized = normalizeDocName(rawDocName);
- if (!normalized.ok) return { docName: rawDocName, ok: false, error: normalized.error };
-
- const identity = deps.identityRef?.current;
- const result = await httpPost(url, '/api/delete-path', {
- kind: 'file',
- path: normalized.docName,
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
-
- if (!result.ok) {
- return { docName: normalized.docName, ok: false, error: result.error as string };
- }
-
- const deletedDocNames = parseDeletedDocNames(result.deletedDocNames);
- const previousPreview = await resolvePreviewUrlForTool(
- normalized.docName,
- { config: deps.config, resolveCwd: deps.resolveCwd },
- cwd,
- );
- return {
- docName: normalized.docName,
- ok: true,
- deletedDocNames: deletedDocNames.length > 0 ? deletedDocNames : [normalized.docName],
- ...(previousPreview ? { previousPreviewUrl: previousPreview.url } : {}),
- };
-}
-
-export function register(server: ServerInstance, deps: DeleteDocumentDeps): void {
- server.registerTool(
- 'delete_document',
- {
- description: DESCRIPTION,
- inputSchema: {
- docName: z.string().optional().describe('A single document to delete.'),
- docNames: z
- .array(z.string())
- .min(1)
- .optional()
- .describe('Batch: documents to delete in one call. Mutually exclusive with `docName`.'),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: { docName?: string; docNames?: 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 { cwd, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
-
- if (args.docName === undefined && args.docNames === undefined) {
- return textResult('Error: provide `docName` (single) or `docNames` (batch).', true);
- }
- if (args.docName !== undefined && args.docNames !== undefined) {
- return textResult('Error: `docName` and `docNames` are mutually exclusive.', true);
- }
-
- if (args.docNames !== undefined) {
- const results = await Promise.all(args.docNames.map((d) => deleteOne(d, url, cwd, deps)));
- const okCount = results.filter((r) => r.ok).length;
- const allOk = okCount === results.length;
- const lines = results.map((r) =>
- r.ok ? `Deleted ${r.docName}.` : `Failed ${r.docName}: ${r.error}`,
- );
- const text = `${okCount}/${results.length} deleted.\n${lines.join('\n')}`;
- return textPlusStructured(text, { ok: allOk, documents: results }, !allOk);
- }
-
- const r = await deleteOne(args.docName as string, url, cwd, deps);
- if (!r.ok) {
- const structured: DeleteDocumentError = { ok: false, error: r.error ?? 'unknown error' };
- return textPlusStructured(`Error: ${structured.error}`, structured, true);
- }
- const deletedDocNames = r.deletedDocNames ?? [r.docName];
- const structured: DeleteDocumentSuccess = {
- ok: true,
- deletedDocNames,
- ...(r.previousPreviewUrl ? { previousPreviewUrl: r.previousPreviewUrl } : {}),
- };
- const text =
- deletedDocNames.length === 1
- ? `Deleted ${deletedDocNames[0]}.`
- : `Deleted ${deletedDocNames.length} documents: ${deletedDocNames.join(', ')}.`;
- return textPlusStructured(text, structured);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.ts
new file mode 100644
index 000000000..ad35a09d0
--- /dev/null
+++ b/packages/server/src/mcp/tools/delete.ts
@@ -0,0 +1,256 @@
+import { z } from 'zod';
+import { applyTemplateDelete } from '../../content/templates-write.ts';
+import type { AgentIdentity } from '../agent-identity.ts';
+import { resolvePreviewUrlForTool } from './preview-url.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpPost,
+ looseObjectArray,
+ normalizeDocName,
+ outputSchemaWithText,
+ previousPreviewUrlField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import { exactlyOneTargetError, resolveTemplatePath } from './verb-schemas.ts';
+
+const BASE_DESCRIPTION = [
+ 'Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, 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 (fs-direct; auto-cleans empty `.ok/`).',
+ '- `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.',
+].join('\n');
+
+export const DESCRIPTION = BASE_DESCRIPTION;
+
+interface DeleteDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+interface DeleteOneResult {
+ docName: string;
+ ok: boolean;
+ deletedDocNames?: string[];
+ previousPreviewUrl?: string;
+ error?: string;
+}
+
+function parseDeletedDocNames(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return value.filter((entry): entry is string => typeof entry === 'string');
+}
+
+async function deleteOneDoc(
+ rawDocName: string,
+ url: string,
+ cwd: string,
+ deps: DeleteDeps,
+): Promise<DeleteOneResult> {
+ const normalized = normalizeDocName(rawDocName);
+ if (!normalized.ok)
+ return { docName: rawDocName, ok: false, error: normalized.error.replace(/^Error:\s*/, '') };
+ const result = await httpPost(url, '/api/delete-path', {
+ kind: 'file',
+ path: normalized.docName,
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) return { docName: normalized.docName, ok: false, error: result.error as string };
+ const deletedDocNames = parseDeletedDocNames(result.deletedDocNames);
+ const previousPreview = await resolvePreviewUrlForTool(
+ normalized.docName,
+ { config: deps.config, resolveCwd: deps.resolveCwd },
+ cwd,
+ );
+ return {
+ docName: normalized.docName,
+ ok: true,
+ deletedDocNames: deletedDocNames.length > 0 ? deletedDocNames : [normalized.docName],
+ ...(previousPreview ? { previousPreviewUrl: previousPreview.url } : {}),
+ };
+}
+
+export function register(server: ServerInstance, deps: DeleteDeps): void {
+ server.registerTool(
+ 'delete',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ document: z
+ .union([
+ z.string(),
+ z.array(z.string()).min(1),
+ z.object({ path: z.union([z.string(), z.array(z.string()).min(1)]) }),
+ ])
+ .optional()
+ .describe(
+ 'Doc path(s) to delete — a string, an array, or `{ path }`. Inbound links become redlinks. Irreversible.',
+ ),
+ folder: z
+ .union([z.string(), z.object({ path: z.string() })])
+ .optional()
+ .describe('Folder path to delete (recursive) — a string or `{ path }`.'),
+ template: z
+ .object({ path: z.string().describe('Template path = `<folder>/<name>`.') })
+ .optional()
+ .describe('A template to delete.'),
+ asset: z
+ .object({
+ path: z
+ .string()
+ .describe(
+ 'Asset path incl. extension — the slashes are its folder. Example: "images/diagram.png".',
+ ),
+ })
+ .optional()
+ .describe('A binary asset to delete.'),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ document: z
+ .object({
+ ok: z.boolean(),
+ deletedDocNames: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'The single docName removed (a document delete never cascades to descendants).',
+ ),
+ error: z.string().optional().describe('Present when `ok` is false.'),
+ })
+ .optional()
+ .describe('Single-document delete result.'),
+ folder: z
+ .object({ ok: z.boolean(), deletedDocNames: z.array(z.string()) })
+ .optional()
+ .describe('Folder delete result (docNames removed).'),
+ template: z
+ .object({ ok: z.boolean(), existed: z.boolean() })
+ .optional()
+ .describe('Template delete result.'),
+ asset: z
+ .object({ ok: z.boolean(), path: z.string() })
+ .optional()
+ .describe('Asset delete result.'),
+ documents: looseObjectArray
+ .optional()
+ .describe('Batch doc delete: per-doc result records.'),
+ previousPreviewUrl: previousPreviewUrlField,
+ }),
+ },
+ async (args: {
+ document?: string | string[] | { path: string | string[] };
+ folder?: string | { path: string };
+ template?: { path: string };
+ asset?: { path: 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 { cwd, url } = context;
+
+ const folderPath = typeof args.folder === 'object' ? args.folder.path : args.folder;
+ const documentArg =
+ args.document && typeof args.document === 'object' && !Array.isArray(args.document)
+ ? args.document.path
+ : args.document;
+
+ const teaching = exactlyOneTargetError(args as Record<string, unknown>, [
+ 'document',
+ 'folder',
+ 'template',
+ 'asset',
+ ]);
+ if (teaching) return textResult(`Error: ${teaching}`, true);
+
+ if (args.template !== undefined) {
+ const resolved = resolveTemplatePath(args.template.path);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ const { folder, name } = resolved;
+ const result = applyTemplateDelete({ projectDir: cwd, folder, name });
+ if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
+ return textPlusStructured(
+ result.existed
+ ? `Deleted template "${name}" from ${folder || '(root)'}.`
+ : `Template "${name}" did not exist in ${folder || '(root)'} — nothing to delete.`,
+ { template: { ok: true, existed: result.existed } },
+ );
+ }
+
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ if (args.folder !== undefined) {
+ const result = await httpPost(url, '/api/delete-path', {
+ kind: 'folder',
+ path: folderPath,
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ const deleted = parseDeletedDocNames(result.deletedDocNames);
+ return textPlusStructured(
+ `Deleted folder ${folderPath}${deleted.length ? ` (${deleted.length} doc(s))` : ''}.`,
+ { folder: { ok: true, deletedDocNames: deleted } },
+ );
+ }
+
+ if (args.asset !== undefined) {
+ const path = args.asset.path.replace(/^\/+/, '').replace(/\/+$/, '');
+ const result = await httpPost(url, '/api/delete-path', {
+ kind: 'asset',
+ path,
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ return textPlusStructured(`Deleted asset ${path}.`, { asset: { ok: true, path } });
+ }
+
+ const doc = documentArg as string | string[];
+ if (Array.isArray(doc)) {
+ const results = await Promise.all(doc.map((d) => deleteOneDoc(d, url, cwd, deps)));
+ const okCount = results.filter((r) => r.ok).length;
+ const allOk = okCount === results.length;
+ const lines = results.map((r) =>
+ r.ok ? `Deleted ${r.docName}.` : `Failed ${r.docName}: ${r.error}`,
+ );
+ return textPlusStructured(
+ `${okCount}/${results.length} deleted.\n${lines.join('\n')}`,
+ { documents: results },
+ !allOk,
+ );
+ }
+ const r = await deleteOneDoc(doc, url, cwd, deps);
+ if (!r.ok) {
+ return textPlusStructured(
+ `Error: ${r.error ?? 'unknown error'}`,
+ { document: { ok: false, error: r.error } },
+ true,
+ );
+ }
+ const deletedDocNames = r.deletedDocNames ?? [r.docName];
+ return textPlusStructured(
+ deletedDocNames.length === 1
+ ? `Deleted ${deletedDocNames[0]}.`
+ : `Deleted ${deletedDocNames.length} documents: ${deletedDocNames.join(', ')}.`,
+ {
+ document: { ok: true, deletedDocNames },
+ ...(r.previousPreviewUrl ? { previousPreviewUrl: r.previousPreviewUrl } : {}),
+ },
+ );
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/discover-body.ts b/packages/server/src/mcp/tools/discover-body.ts
index 75bfd52cb..f6afb4195 100644
--- a/packages/server/src/mcp/tools/discover-body.ts
+++ b/packages/server/src/mcp/tools/discover-body.ts
@@ -9,7 +9,7 @@ Use OK primitives only — no new files outside \`<folder>/.ok/\`, no body rewri
**You will work through 7 phases in order. STOP gates (⛔) require user confirmation before proceeding. Do not skip or batch ahead.**
-**Server requirement.** Phases 1-4 run fs-direct — \`exec\` (scan + read) and \`folder_config\` (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes \`links\` and \`search\`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a \`run ok start\` instruction if it is down.
+**Server requirement.** Phases 1-4 run fs-direct — \`exec\` (scan + read) and the \`write\`/\`edit\` verbs (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes \`links\` and \`search\`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a \`run ok start\` instruction if it is down.
---
@@ -110,43 +110,42 @@ For **each** folder the user marked \`[KB]\`:
- If this folder already has its own frontmatter → switch to "extend mode." Show existing keys to user; propose ADDITIONS only.
- If \`templates_available\` includes a template → skip template extraction. Tell user: "existing template \`<name>\` found; preserving."
-5. **Propose folder frontmatter + template.** Both are \`folder_config\` writes — one call per action:
+5. **Propose folder frontmatter + template.** One \`write\`/\`edit\` call per target:
\`\`\`ts
- folder_config({
- action: 'set-rule',
- rules: [{
- match: '<folder>/**',
+ edit({
+ folder: {
+ path: '<folder>',
frontmatter: {
title: '<inferred>', // e.g., "Specifications"
description: '<inferred>', // 1-2 sentences describing the folder's purpose
tags: ['<inferred>'], // e.g., ['spec']
},
- }],
+ },
})
- folder_config({
- action: 'write-template',
- folder: '<folder>',
- name: '<inferred-name>', // e.g., 'SPEC' for specs/, 'REPORT' for reports/
- frontmatter: { title: '<placeholder>', description: '<placeholder>' },
- body: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, …) as starting values>',
+ write({
+ template: {
+ path: '<folder>/<inferred-name>', // e.g., 'specs/SPEC', 'reports/REPORT'
+ frontmatter: { title: '<placeholder>', description: '<placeholder>' },
+ content: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, …) as starting values>',
+ },
})
\`\`\`
6. **⛔ STOP gate 4 — Surface proposal to user.** Show: heading set + frontmatter shape + filename pattern + link patterns. Ask: "Apply this proposal? (yes / edit / skip this folder)"
-7. **Apply confirmed proposals** via the two \`folder_config\` calls above. Re-run \`exec("ls <folder>")\` to confirm \`templates_available\` + the folder's descriptive \`title\`/\`description\`/\`tags\` are populated.
+7. **Apply confirmed proposals** via the \`edit({ folder })\` + \`write({ template })\` calls above. Re-run \`exec("ls <folder>")\` to confirm \`templates_available\` + the folder's descriptive \`title\`/\`description\`/\`tags\` are populated.
Repeat for every \`[KB]\` folder.
-**v1 scope note:** \`discover\` does NOT attempt nested-pattern detection (e.g., applying the same rule across \`specs/*/evidence/\` for every spec's evidence/ subfolder). \`folder_config\` rejects multi-folder globs with \`MULTI_FOLDER_GLOB\`. Users who want nested folder frontmatter set it up manually after \`discover\` finishes the top-level work.
+**v1 scope note:** \`discover\` does NOT attempt nested-pattern detection (e.g., applying the same folder frontmatter across \`specs/*/evidence/\` for every spec's evidence/ subfolder). Each folder is addressed by its own path — one \`edit({ folder })\` call per folder. Users who want nested folder frontmatter set it up manually after \`discover\` finishes the top-level work.
---
## Phase 5 — Link-graph activation
-The largest phase. Uses the \`links\` tool (every link-graph view) plus \`search\` and \`edit_document\` to apply confirmed link insertions.
+The largest phase. Uses the \`links\` tool (every link-graph view) plus \`search\` and \`edit\` to apply confirmed link insertions.
0. **Server check (required for this phase).** \`links\` and \`search\` need the OK Hocuspocus server. Probe via \`links({ kind: "hubs" })\`. If the response starts with \`"Error: Hocuspocus server is not running"\`, STOP — tell the user "the link-graph phase of discover needs the OK server. Start it with \`ok start\` from a terminal, then re-invoke \`discover\` (Phases 1-4 are already applied; it resumes here)." Exit cleanly.
@@ -158,7 +157,7 @@ Six sub-passes, each with its own STOP gate.
2. For each orphan, run \`links({ kind: "suggest", docName: <orphan> })\`:
- If \`mentions[]\` is non-empty → there are docs that mention this orphan without linking. Adoption candidates.
- If \`mentions[]\` is empty → the orphan is **genuinely standalone** (no other doc references it at all). Surface as: "this looks intentionally standalone (e.g., a README). Skip / adopt anyway by linking from a hub / add to \`.okignore\`?"
-3. Confirm per orphan. For each "link" choice, \`edit_document\` on the source doc at the offset \`links({ kind: "suggest" })\` returned to wrap the existing mention in link syntax.
+3. Confirm per orphan. For each "link" choice, \`edit({ document: { path, find, replace } })\` on the source doc — find the existing mention text \`links({ kind: "suggest" })\` surfaced and replace it wrapped in link syntax.
**Note on re-surfacing:** v1 does NOT persist "intentional standalone" markers. Each \`discover\` re-run surfaces the same intentional orphans (root \`README.md\`, \`CONTRIBUTING.md\`, etc.) and the user re-dismisses them. Acceptable minor friction.
@@ -175,7 +174,7 @@ Six sub-passes, each with its own STOP gate.
1. Run \`links({ kind: "dead" })\` (no \`sourceDocNames\` → audits the whole corpus).
2. For each dead link, propose: fix candidate (via \`search\` for the correct target), or delete (remove the link, or the prose around it). Leaving it as an "intentional redlink" is not an option — every dead link is fixed or removed.
-3. Confirm per dead-link. Apply confirmed fixes via \`edit_document\`.
+3. Confirm per dead-link. Apply confirmed fixes via \`edit\`.
### 5d. Untextualized-reference detection (⛔ STOP gate 5d)
@@ -192,7 +191,7 @@ Six sub-passes, each with its own STOP gate.
line 203: "...per AGENTS.md ecosystem convention" → matches root AGENTS.md — accept as link
\`\`\`
-4. Confirm per source doc (batched). Apply confirmed link insertions via \`edit_document\` using the offsets the \`suggest\` view returned.
+4. Confirm per source doc (batched). Apply confirmed link insertions via \`edit({ document: { path, find, replace } })\` — find the mention text the \`suggest\` view surfaced and replace it wrapped in link syntax.
**Truncation handling:** if the \`suggest\` view returns \`truncated: true\`, the scan hit its time budget. Iterate with smaller scope or accept partial coverage and tell the user.
@@ -205,7 +204,7 @@ Harder case: prose discusses a concept covered by another doc without naming it.
3. For each candidate sibling:
- Verify it is NOT already linked from this doc (\`links({ kind: "forward", docName: <doc> })\`).
- Verify content is actually relevant (re-read summary; LLM judgment).
-4. Surface to user with brief justification per pair. Confirm. Apply via \`edit_document\` (insert link in a "Related" or "References" section).
+4. Surface to user with brief justification per pair. Confirm. Apply via \`edit\` (insert link in a "Related" or "References" section).
**Caveat:** vague-referential is LLM-judgment-heavy. False positives are expected; the user is the final arbiter. If the user rejects > 50% of proposals in a batch, recalibrate (tighten concept-extraction, raise relevance bar).
@@ -215,7 +214,7 @@ Harder case: prose discusses a concept covered by another doc without naming it.
- Wiki-link syntax: \`[[Page Title]]\` (legacy)
- Relative-markdown: \`[text](./path.md)\` or \`[text](path.md)\` (current OK recommended)
2. Report ratio to user. If mixed, propose a one-time standardization: convert all \`[[Page]]\` to \`[Page](./path.md)\`. Ambiguous \`[[Page]]\` (multiple matching files) → surface for confirmation.
-3. Apply via \`edit_document\` on each affected doc, resolving page titles to file paths via \`exec("ls")\` / \`search\`.
+3. Apply via \`edit\` on each affected doc, resolving page titles to file paths via \`exec("ls")\` / \`search\`.
---
diff --git a/packages/server/src/mcp/tools/discover.test.ts b/packages/server/src/mcp/tools/discover.test.ts
deleted file mode 100644
index a0d37b7cf..000000000
--- a/packages/server/src/mcp/tools/discover.test.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { DESCRIPTION, register } from './discover.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: boolean;
-}
-
-interface DiscoverArgs {
- cwd?: string;
-}
-
-type ToolHandler = (args: DiscoverArgs) => Promise<ToolResult>;
-
-interface RegisterToolCapture {
- name: string;
- cfg: {
- description: string;
- inputSchema: Record<string, unknown>;
- outputSchema?: Record<string, unknown>;
- annotations?: {
- readOnlyHint?: boolean;
- idempotentHint?: boolean;
- destructiveHint?: boolean;
- };
- };
- handler: ToolHandler;
-}
-
-function newProject(): string {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-discover-'));
- mkdirSync(join(cwd, '.ok'), { recursive: true });
- return cwd;
-}
-
-function captureRegistration(cwd: string): RegisterToolCapture {
- let captured: RegisterToolCapture | null = null;
- const server = {
- registerTool(name: string, cfg: RegisterToolCapture['cfg'], handler: ToolHandler) {
- captured = { name, cfg, handler };
- },
- tool() {
- throw new Error('discover should use registerTool, not tool');
- },
- } as unknown as ServerInstance;
- register(server, {
- config: BASE_CONFIG,
- resolveCwd: async () => cwd,
- });
- if (!captured) throw new Error('discover tool was not registered');
- return captured;
-}
-
-describe('discover — tool registration', () => {
- test('T-U1: registers under the name `discover`', () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- expect(captured.name).toBe('discover');
- });
-
- test('T-U2: annotations match set_folder_rule + write_template (readOnly:false, idempotent:true, destructive:false)', () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- expect(captured.cfg.annotations).toEqual({
- readOnlyHint: false,
- idempotentHint: true,
- destructiveHint: false,
- });
- });
-
- test('T-U6: input schema declares optional `cwd` and nothing else', () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const schemaKeys = Object.keys(captured.cfg.inputSchema);
- expect(schemaKeys).toEqual(['cwd']);
- });
-});
-
-describe('discover — DESCRIPTION (tools/list blurb)', () => {
- test('T-U3a: mentions "existing" repo context', () => {
- expect(DESCRIPTION.toLowerCase()).toContain('existing');
- });
-
- test('T-U3b: names `ok seed` as the empty-repo alternative', () => {
- expect(DESCRIPTION).toContain('ok seed');
- });
-
- test('T-U3c: signals idempotency / one-shot semantics', () => {
- expect(DESCRIPTION.toLowerCase()).toMatch(/one-shot|idempotent/);
- });
-});
-
-describe('discover — instructional body structural markers', () => {
- test('T-U4: body contains all seven phase markers (Phase 1 … Phase 7)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- for (const n of [1, 2, 3, 4, 5, 6, 7]) {
- expect(body).toContain(`Phase ${n}`);
- }
- });
-
- test('T-U5a: body contains the four primary STOP gate markers (gates 1, 2, 3, 4)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- for (const n of [1, 2, 3, 4]) {
- expect(body).toContain(`STOP gate ${n}`);
- }
- });
-
- test('T-U5b: body contains the six Phase 5 link-graph sub-pass STOP gates (5a-5f)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- for (const letter of ['a', 'b', 'c', 'd', 'e', 'f']) {
- expect(body).toContain(`STOP gate 5${letter}`);
- }
- });
-
- test('T-U5c: body contains ⛔ marker (visual STOP indicator)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('⛔');
- });
-
- test("body contains anti-patterns section (don't restructure / don't auto-apply / etc.)", async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- expect(body).toContain("Don't restructure");
- expect(body).toContain("Don't auto-apply");
- expect(body).toContain("Don't bulk-rewrite");
- });
-
- test('body contains exit conditions section (empty project, server down, validation failure)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('Exit conditions');
- expect(body).toContain('Empty project');
- expect(body).toContain('ok seed');
- });
-
- test('body references the existing primitives discover composes', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('folder_config');
- expect(body).toContain('links');
- expect(body).toContain('search');
- expect(body).toContain('exec');
- expect(body).toContain('edit_document');
- });
-});
-
-describe('discover — handler behavior', () => {
- test('returns structuredContent with previewUrl: null (matches workflow-tool pattern)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- expect(result.structuredContent).toMatchObject({ previewUrl: null });
- });
-
- test('returns dual-channel result (text content + structuredContent)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(cwd);
- const result = await captured.handler({});
- expect(result.content[0]?.type).toBe('text');
- expect(result.content[0]?.text.length).toBeGreaterThan(1000);
- expect(result.structuredContent).toBeDefined();
- });
-
- test('T-U7: handler returns error when cwd resolution fails', async () => {
- const capture: { handler: ToolHandler | null } = { handler: null };
- const server = {
- registerTool(_name: string, _cfg: unknown, h: ToolHandler) {
- capture.handler = h;
- },
- tool() {
- throw new Error('not used');
- },
- } as unknown as ServerInstance;
- register(server, {
- config: BASE_CONFIG,
- resolveCwd: async () => {
- throw new Error('synthetic: no cwd available');
- },
- });
- if (!capture.handler) throw new Error('tool not registered');
- const handler = capture.handler;
- const result = await handler({});
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('Error');
- });
-
- test('body includes the resolved content directory (interpolation distinguishable from hardcoded default)', async () => {
- const cwd = newProject();
- const customConfig: Config = ConfigSchema.parse({ content: { dir: 'knowledge' } });
- let captured: ToolHandler | null = null;
- const server = {
- registerTool(_name: string, _cfg: unknown, h: ToolHandler) {
- captured = h;
- },
- tool() {
- throw new Error('not used');
- },
- } as unknown as ServerInstance;
- register(server, { config: customConfig, resolveCwd: async () => cwd });
- if (!captured) throw new Error('tool not registered');
- const handler = captured as ToolHandler;
- const result = await handler({});
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('Content directory: `knowledge`');
- expect(body).toContain('exec("ls knowledge")');
- expect(body).not.toContain('Content directory: `.`');
- });
-
- test('args.cwd is plumbed through to resolveCwd', async () => {
- const projectCwd = newProject();
- const received: { explicit: string | undefined } = { explicit: undefined };
- const capture: { handler: ToolHandler | null } = { handler: null };
- const server = {
- registerTool(_name: string, _cfg: unknown, h: ToolHandler) {
- capture.handler = h;
- },
- tool() {
- throw new Error('not used');
- },
- } as unknown as ServerInstance;
- register(server, {
- config: BASE_CONFIG,
- resolveCwd: async (explicit?: string) => {
- received.explicit = explicit;
- return projectCwd;
- },
- });
- if (!capture.handler) throw new Error('tool not registered');
- const handler = capture.handler;
- await handler({ cwd: '/explicit/path/from/caller' });
- expect(received.explicit).toBe('/explicit/path/from/caller');
- });
-});
diff --git a/packages/server/src/mcp/tools/discover.ts b/packages/server/src/mcp/tools/discover.ts
deleted file mode 100644
index 36cc60946..000000000
--- a/packages/server/src/mcp/tools/discover.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { z } from 'zod';
-import { buildDiscoverBody } from './discover-body.ts';
-import type { ConfigOrResolver, ServerInstance } from './shared.ts';
-import {
- outputSchemaWithText,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectConfigContext,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-export const DESCRIPTION = [
- 'Returns a step-by-step plan for setting up an existing repo: extract folder conventions, write folder frontmatter + templates, activate the link graph. Does NOT execute the plan — you run it, with per-phase user confirmation.',
- '',
- 'Invoke on first arrival at a repo that has markdown content but no folder frontmatter / templates (an `exec` listing shows no folder `title`/`description`/`tags` and empty `templates_available`). Skip empty repos (use `ok seed`) and already-configured ones. One-shot per project; idempotent on re-run (extends, never re-proposes).',
- '',
- 'Phases 1-4 run fs-direct; Phase 5 (link-graph activation) needs `ok start`. Composes existing tools only — `exec`, `links`, `search`, `folder_config`, `edit_document`.',
-].join('\n');
-
-interface DiscoverDeps {
- resolveCwd: (explicit?: string) => Promise<string>;
- config: ConfigOrResolver;
-}
-
-const InputSchema = {
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
-} as const;
-
-const OutputSchema = outputSchemaWithText({
- previewUrl: z.null(),
-});
-
-export function register(server: ServerInstance, deps: DiscoverDeps): void {
- server.registerTool(
- 'discover',
- {
- description: DESCRIPTION,
- inputSchema: InputSchema,
- outputSchema: OutputSchema,
- annotations: {
- readOnlyHint: false,
- idempotentHint: true,
- destructiveHint: false,
- },
- },
- async (args: { cwd?: string }) => {
- const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- const body = buildDiscoverBody(context.config.content.dir);
- return textPlusStructured(body, { previewUrl: null });
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/edit-document.test.ts b/packages/server/src/mcp/tools/edit-document.test.ts
deleted file mode 100644
index e6928d7ae..000000000
--- a/packages/server/src/mcp/tools/edit-document.test.ts
+++ /dev/null
@@ -1,458 +0,0 @@
-import {
- describe as _bunDescribe,
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- expect,
- test,
-} from 'bun:test';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
-
-const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { DESCRIPTION, register } from './edit-document.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: true;
-}
-
-interface RegisteredTool {
- name: string;
- description: string;
- schema: Record<string, unknown>;
- handler: (args: {
- docName: string;
- find: string;
- replace: string;
- offset?: number;
- }) => Promise<ToolResult>;
-}
-
-function createFakeServer() {
- let registeredTool: RegisteredTool | undefined;
-
- const server = {
- registerTool(
- name: string,
- config: { description?: string; inputSchema?: Record<string, unknown> },
- handler: RegisteredTool['handler'],
- ) {
- registeredTool = {
- name,
- description: config.description ?? '',
- schema: config.inputSchema ?? {},
- handler,
- };
- },
- } as unknown as ServerInstance;
-
- return {
- server,
- getTool(): RegisteredTool {
- if (!registeredTool) throw new Error('Tool was not registered');
- return registeredTool;
- },
- };
-}
-
-let testServer: ReturnType<typeof Bun.serve>;
-let baseUrl: string;
-const requestBodies: unknown[] = [];
-let mockSubscriberCount: number | undefined = 1;
-let mockSystemSubscriberCount: number | undefined = 1;
-let mockErrorEnvelope: { status: number; body: Record<string, unknown> } | undefined;
-let mockWarning: Record<string, unknown> | undefined;
-
-beforeAll(() => {
- testServer = Bun.serve({
- port: 0,
- async fetch(req) {
- const url = new URL(req.url);
-
- if (url.pathname === '/api/agent-patch') {
- const body = await req.json();
- requestBodies.push(body);
-
- if (mockErrorEnvelope) {
- return Response.json(mockErrorEnvelope.body, { status: mockErrorEnvelope.status });
- }
-
- if ((body as { offset?: number }).offset === 13) {
- return Response.json(
- { ok: false, error: 'Target text no longer matches at the requested offset' },
- { status: 409 },
- );
- }
-
- return Response.json({
- ok: true,
- timestamp: '2026-04-14T22:00:00.000Z',
- ...(mockSubscriberCount !== undefined ? { subscriberCount: mockSubscriberCount } : {}),
- ...(mockSystemSubscriberCount !== undefined
- ? { systemSubscriberCount: mockSystemSubscriberCount }
- : {}),
- ...(mockWarning !== undefined ? { warning: mockWarning } : {}),
- });
- }
-
- return new Response('Not found', { status: 404 });
- },
- });
- baseUrl = `http://localhost:${testServer.port}`;
-});
-
-afterAll(() => {
- testServer.stop();
-});
-
-let tmpDir: string;
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-edit-doc-'));
- mockSubscriberCount = 1;
- mockSystemSubscriberCount = 1;
- mockErrorEnvelope = undefined;
- mockWarning = undefined;
-});
-
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-function makeDeps(overrides: Partial<Config> = {}) {
- const config: Config = { ...BASE_CONFIG, ...overrides };
- return {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- };
-}
-
-describe('edit_document MCP tool', () => {
- test('describes the optional offset precision contract', () => {
- expect(DESCRIPTION).toContain('offset');
- expect(DESCRIPTION).toContain('exact occurrence');
- expect(DESCRIPTION).toContain('links({ kind: "suggest"');
- });
-
- test('sends offset to the agent-patch endpoint when provided', async () => {
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- offset: 42,
- });
-
- expect(requestBodies.at(-1)).toEqual({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- offset: 42,
- });
- expect(result.content[0]?.text).toBe('Edit applied successfully.');
- });
-
- test('relays a content-divergence warning as structuredContent.contentDivergence + a text line', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = {
- kind: 'content-divergence',
- intendedBytes: 20,
- actualBytes: 27,
- byteDelta: 7,
- divergenceType: 'patch-content-mismatch',
- currentState: { kind: 'inline', content: 'what actually landed\nextra\n' },
- hint: 'currentState carries the converged content.',
- };
-
- const result = await getTool().handler({ docName: 'notes', find: 'a', replace: 'b' });
-
- expect(result.structuredContent?.contentDivergence).toMatchObject({
- kind: 'content-divergence',
- byteDelta: 7,
- divergenceType: 'patch-content-mismatch',
- currentState: { kind: 'inline', content: 'what actually landed\nextra\n' },
- });
- expect(result.content[0]?.text).toContain('⚠ Content divergence');
- });
-
- test('drops a malformed server warning at the safeParse boundary', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = {
- kind: 'content-divergence',
- intendedBytes: 20,
- actualBytes: 27,
- byteDelta: 'seven',
- };
-
- const result = await getTool().handler({ docName: 'notes', find: 'a', replace: 'b' });
-
- expect(result.structuredContent?.contentDivergence).toBeUndefined();
- expect(result.content[0]?.text).not.toContain('⚠ Content divergence');
- });
-
- test('ignores a non-divergence server warning (preview-attach lives on its own key)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = { action: 'attach-preview-once', previewUrl: '/#/notes' };
-
- const result = await getTool().handler({ docName: 'notes', find: 'a', replace: 'b' });
-
- expect(result.structuredContent?.contentDivergence).toBeUndefined();
- });
-
- test('omits offset when the caller uses first-match mode', async () => {
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(requestBodies.at(-1)).toEqual({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
- });
-
- test('propagates stale-target errors from the server', async () => {
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- offset: 13,
- });
-
- expect(result).toEqual({
- content: [
- { type: 'text', text: 'Error: Target text no longer matches at the requested offset' },
- ],
- isError: true,
- });
- });
-
- test('surfaces the server field-level detail alongside the title (parity with write_document)', async () => {
- mockErrorEnvelope = {
- status: 400,
- body: {
- type: 'urn:ok:error:invalid-request',
- title: 'Request body is invalid.',
- status: 400,
- detail: 'find: String must contain at least 1 character(s)',
- },
- };
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'x',
- replace: 'y',
- });
-
- expect(result.isError).toBe(true);
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('Request body is invalid.');
- expect(text).toContain('find: String must contain at least 1 character(s)');
- });
-
- test('includes route-only previewUrl + source in structuredContent when resolver resolves', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/notes',
- previewUrlSource: 'lock',
- });
- });
-
- test('omits structuredContent when resolver returns null AND subscribers>0', async () => {
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toBeUndefined();
- expect(result.content[0]?.text).toBe('Edit applied successfully.');
- });
-
- test('emits attach-preview-once hint with previewUrl when systemSubscriberCount=0', async () => {
- bindTestUiLock(tmpDir);
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/notes',
- previewUrlSource: 'lock',
- warning: {
- action: 'attach-preview-once',
- message:
- 'No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.',
- previewUrl: '/#/notes',
- autoOpen: true,
- },
- });
- });
-
- test('emits start-ui hint with null previewUrl when systemSubscriberCount=0 and no resolver source', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'start-ui',
- previewUrl: null,
- autoOpen: true,
- },
- });
- const warning = (result.structuredContent as { warning: { message: string } }).warning;
- expect(warning.message).toContain('ok ui');
- expect(warning.message).toContain('preview_start');
- expect(warning.message).toContain('OK Electron');
- expect(result.structuredContent?.previewUrl).toBeUndefined();
- });
-
- test('no hint when systemSubscriberCount>0 even if per-doc subscriberCount=0 (second doc, server-push follows)', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 1;
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent?.warning).toBeUndefined();
- expect(result.content[0]?.text).not.toContain('No preview attached');
- });
-
- test('no warning emitted when server omits systemSubscriberCount field (legacy server)', async () => {
- mockSubscriberCount = undefined;
- mockSystemSubscriberCount = undefined;
- const { server, getTool } = createFakeServer();
-
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toBeUndefined();
- expect(result.content[0]?.text).toBe('Edit applied successfully.');
- });
-});
-
-describe('edit_document — autoOpen field on PreviewAttachWarning', () => {
- test('attach-preview-once warning carries autoOpen=false when user disabled it', async () => {
- bindTestUiLock(tmpDir);
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- const config = ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } });
- register(server, {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- });
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'attach-preview-once',
- previewUrl: '/#/notes',
- autoOpen: false,
- },
- });
- });
-
- test('start-ui warning carries autoOpen=false when user disabled it', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- const config = ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } });
- register(server, {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- });
-
- const result = await getTool().handler({
- docName: 'notes',
- find: 'Project Alpha',
- replace: '[[Project Alpha]]',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'start-ui',
- previewUrl: null,
- autoOpen: false,
- },
- });
- });
-});
diff --git a/packages/server/src/mcp/tools/edit-document.ts b/packages/server/src/mcp/tools/edit-document.ts
deleted file mode 100644
index 4c199dc40..000000000
--- a/packages/server/src/mcp/tools/edit-document.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { renderInventoryFooter, WriteWarningSchema } from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import { resolveLockDir } from '../../config/paths.ts';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpPost,
- normalizeDocName,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- summaryArgSchema,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-const BASE_DESCRIPTION = [
- '[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer. The patch propagates to all connected editors in real-time. Use `offset` to target an exact occurrence; omit for first-match.',
- '',
- '**Body-only.** Frontmatter-intersecting find/replace is rejected with HTTP 400. For frontmatter: 1-2 keys → `edit_frontmatter`; full rewrite → `write_document({ position: "replace" })`.',
- '',
- '**Parameters:**',
- '- `docName` — Document name, extension-less. Trailing `.md`/`.mdx` stripped.',
- '- `find` — Text to find (exact match).',
- '- `replace` — Replacement text.',
- '- `offset` — Optional JavaScript string offset of the exact occurrence to patch. Stale offsets return an error; re-fetch via `links({ kind: "suggest", docName })`.',
- '- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history.',
- '',
- 'Responses may include `structuredContent.contentDivergence` (`{kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint}`) when the converged Y.Text doesn\'t match the bytes your splice composed to. The patch still landed; you do NOT need to re-read — `currentState` carries the converged document inline (or a truncation marker over the soft cap).',
-].join('\n');
-
-export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
-
-interface EditDocumentDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- identityRef?: { current: AgentIdentity };
-}
-
-export function register(server: ServerInstance, deps: EditDocumentDeps): void {
- server.registerTool(
- 'edit_document',
- {
- description: DESCRIPTION,
- inputSchema: {
- docName: z.string().describe('Document name to edit'),
- find: z.string().describe('Text to find (exact match)'),
- replace: z.string().describe('Replacement text'),
- offset: z
- .number()
- .int()
- .min(0)
- .optional()
- .describe(
- 'Exact occurrence to patch, as a JavaScript string offset in the current markdown',
- ),
- summary: summaryArgSchema,
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: {
- docName: string;
- find: string;
- replace: string;
- offset?: number;
- summary?: 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 { cwd, config, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const autoOpen = config.appearance.preview.autoOpen;
- const normalized = normalizeDocName(args.docName);
- if (!normalized.ok) return textResult(normalized.error, true);
- const identity = deps.identityRef?.current;
- const result = await httpPost(url, '/api/agent-patch', {
- docName: normalized.docName,
- find: args.find,
- replace: args.replace,
- offset: args.offset,
- ...(args.summary !== undefined ? { summary: args.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
- if (!result.ok) {
- const detail =
- typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
- return textResult(
- detail ? `Error: ${result.error} (${detail})` : `Error: ${result.error}`,
- true,
- );
- }
-
- const lockDir = resolveLockDir(cwd);
- const preview = resolvePreviewUrl(normalized.docName, { lockDir });
- const subscriberCount =
- typeof result.subscriberCount === 'number' ? result.subscriberCount : undefined;
- const systemSubscriberCount =
- typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;
- const noPreviewAnywhere = systemSubscriberCount === 0;
- const noPreviewOnThisDoc = subscriberCount === 0;
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const writeWarningParse = WriteWarningSchema.safeParse(result.warning);
- const writeWarning = writeWarningParse.success ? writeWarningParse.data : undefined;
-
- const lines: string[] = ['Edit applied successfully.'];
- if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
- if (summaryHint) lines.push(summaryHint);
- if (writeWarning) {
- lines.push(
- writeWarning.kind === 'content-divergence'
- ? `⚠ Content divergence: ${writeWarning.actualBytes} actual bytes vs ${writeWarning.intendedBytes} intended (byteDelta=${writeWarning.byteDelta}). ${writeWarning.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
- : `⚠ ${writeWarning.hint ?? 'An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.'}`,
- );
- }
- const text = lines.join('\n');
-
- if (
- !preview &&
- !noPreviewAnywhere &&
- !noPreviewOnThisDoc &&
- !summaryResult &&
- !writeWarning
- ) {
- return textResult(text);
- }
-
- const structured: Record<string, unknown> = {};
- if (writeWarning) {
- structured.contentDivergence = writeWarning;
- }
- if (preview) {
- structured.previewUrl = preview.url;
- structured.previewUrlSource = preview.source;
- }
- if (noPreviewAnywhere) {
- structured.warning = buildPreviewAttachWarning(preview, autoOpen);
- }
- if (summaryResult) {
- structured.summary = summaryResult;
- }
- return textPlusStructured(text, structured);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/edit-frontmatter.test.ts b/packages/server/src/mcp/tools/edit-frontmatter.test.ts
deleted file mode 100644
index 14c7895e8..000000000
--- a/packages/server/src/mcp/tools/edit-frontmatter.test.ts
+++ /dev/null
@@ -1,388 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
-import type { IncomingMessage, ServerResponse } from 'node:http';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { Readable } from 'node:stream';
-import { Hocuspocus } from '@hocuspocus/server';
-import {
- AGENT_WRITE_ORIGIN,
- AgentSessionManager,
- applyAgentMarkdownWrite,
-} from '../../agent-sessions.ts';
-import { createApiExtension } from '../../api-extension.ts';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './edit-frontmatter.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: true;
-}
-
-interface RegisteredTool {
- name: string;
- handler: (args: {
- docName: string;
- patch: Record<string, string | number | boolean | string[] | null>;
- summary?: string;
- types?: Record<string, 'text' | 'number' | 'boolean' | 'date' | 'list'>;
- }) => Promise<ToolResult>;
-}
-
-function createFakeServer() {
- let registeredTool: RegisteredTool | undefined;
- const server = {
- tool(
- name: string,
- _description: string,
- _schema: Record<string, unknown>,
- handler: RegisteredTool['handler'],
- ) {
- registeredTool = { name, handler };
- },
- registerTool(name: string, _config: unknown, handler: RegisteredTool['handler']) {
- registeredTool = { name, handler };
- },
- } as unknown as ServerInstance;
- return {
- server,
- getTool(): RegisteredTool {
- if (!registeredTool) throw new Error('Tool was not registered');
- return registeredTool;
- },
- };
-}
-
-interface Harness {
- projectDir: string;
- contentDir: string;
- hocuspocus: Hocuspocus;
- sessionManager: AgentSessionManager;
- baseUrl: string;
- testServer: ReturnType<typeof Bun.serve>;
- cleanup: () => Promise<void>;
-}
-
-async function setupHarness(): Promise<Harness> {
- const projectDir = mkdtempSync(join(tmpdir(), 'ok-frontmatter-patch-'));
- const contentDir = join(projectDir, 'content');
- mkdirSync(contentDir, { recursive: true });
- const hocuspocus = new Hocuspocus({ quiet: true });
- const sessionManager = new AgentSessionManager(hocuspocus);
- const ext = createApiExtension({
- hocuspocus,
- sessionManager,
- contentDir,
- getFileIndex: () => new Map(),
- });
-
- const testServer = Bun.serve({
- port: 0,
- async fetch(req) {
- const url = new URL(req.url);
- const bodyText = req.method === 'POST' ? await req.text() : '';
- const readable = Readable.from(Buffer.from(bodyText)) as unknown as IncomingMessage;
- readable.method = req.method;
- readable.url = `${url.pathname}${url.search}`;
- readable.headers = {
- host: url.host,
- 'content-type': req.headers.get('content-type') ?? 'application/json',
- };
- const captured = { status: 200, body: '', contentType: 'application/json' };
- const res = {
- writeHead(status: number, headers?: Record<string, string>) {
- captured.status = status;
- if (headers?.['Content-Type']) captured.contentType = headers['Content-Type'];
- },
- setHeader(name: string, value: string) {
- if (name.toLowerCase() === 'content-type') captured.contentType = value;
- },
- end(body?: string) {
- captured.body = body ?? '';
- },
- headersSent: false,
- writableEnded: false,
- destroyed: false,
- } as unknown as ServerResponse;
- await (
- ext as {
- onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
- }
- ).onRequest({ request: readable, response: res });
- return new Response(captured.body || null, {
- status: captured.status,
- headers: { 'Content-Type': captured.contentType },
- });
- },
- });
- const baseUrl = `http://localhost:${testServer.port}`;
-
- const cleanup = async () => {
- testServer.stop();
- await sessionManager.closeAll();
- rmSync(projectDir, { recursive: true, force: true });
- };
-
- return { projectDir, contentDir, hocuspocus, sessionManager, baseUrl, testServer, cleanup };
-}
-
-function readFmRegion(doc: import('yjs').Doc): string {
- const ytext = doc.getText('source').toString();
- const m = ytext.match(/^---\n([\s\S]*?)\n---\n/);
- return m ? m[1] : '';
-}
-
-describe('edit_frontmatter — MCP tool over real CRDT path', () => {
- let harness: Harness;
-
- beforeEach(async () => {
- harness = await setupHarness();
- });
-
- afterEach(async () => {
- await harness.cleanup();
- });
-
- function makeDeps() {
- return {
- serverUrl: harness.baseUrl,
- config: BASE_CONFIG,
- resolveCwd: async () => harness.projectDir,
- };
- }
-
- async function seedDoc(docName: string, fullMarkdown: string): Promise<void> {
- const session = await harness.sessionManager.getSession(docName);
- session.dc.document.transact(() => {
- applyAgentMarkdownWrite(session.dc.document, fullMarkdown, 'replace');
- }, AGENT_WRITE_ORIGIN);
- }
-
- test('per-key SET adds the new key (RFC 7396)', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n\nOriginal body.\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'published' },
- });
-
- expect(result.isError).toBeUndefined();
- expect(result.content[0]?.text).toContain('Frontmatter patched');
-
- const session = await harness.sessionManager.getSession('test-doc');
- const fm = readFmRegion(session.dc.document);
- expect(fm).toContain('title: My Doc');
- expect(fm).toContain('status: published');
- expect(session.dc.document.getText('source').toString()).toContain('Original body.');
- });
-
- test('per-key DELETE removes the key (RFC 7396 null sentinel)', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\ntags: [a, b]\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { tags: null },
- });
-
- expect(result.isError).toBeUndefined();
- const session = await harness.sessionManager.getSession('test-doc');
- const fm = readFmRegion(session.dc.document);
- expect(fm).toContain('title: My Doc');
- expect(fm).not.toContain('tags:');
- });
-
- test('atomic rejection: invalid value rejects whole patch + emits fieldErrors', async () => {
- await seedDoc('test-doc', '---\ntitle: Original\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: {
- title: { nested: 'object' } as unknown as string,
- note: 'should-not-land',
- },
- });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('Error:');
-
- const session = await harness.sessionManager.getSession('test-doc');
- const fm = readFmRegion(session.dc.document);
- expect(fm).toContain('title: Original');
- expect(fm).not.toContain('note:');
- });
-
- test('CRDT field-level merge: two patches to different keys both land', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const r1 = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'draft' },
- });
- const r2 = await getTool().handler({
- docName: 'test-doc',
- patch: { author: 'Alice' },
- });
-
- expect(r1.isError).toBeUndefined();
- expect(r2.isError).toBeUndefined();
-
- const session = await harness.sessionManager.getSession('test-doc');
- const fm = readFmRegion(session.dc.document);
- expect(fm).toContain('title: My Doc');
- expect(fm).toContain('status: draft');
- expect(fm).toContain('author: Alice');
- });
-
- test('writer attribution: write fires under session.origin (paired) — undo tracks it', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const session = await harness.sessionManager.getSession('test-doc', 'claude-1');
- session.um.clear();
- expect(session.um.undoStack.length).toBe(0);
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBeUndefined();
- expect(session.um.undoStack.length).toBeGreaterThan(0);
- });
-
- test('reserved doc name (__system__) rejected with HTTP 400', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: '__system__',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBe(true);
- const text = (result.content?.[0] as { text?: string } | undefined)?.text ?? '';
- expect(text).toContain('reserved');
- });
-
- test('reserved doc name (__config__/project) rejected with HTTP 400', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: '__config__/project',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBe(true);
- const text = (result.content?.[0] as { text?: string } | undefined)?.text ?? '';
- expect(text).toContain('reserved');
- });
-
- test('empty patch {} is a clean no-op (success, no contributor, no git flush)', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: {},
- });
-
- expect(result.isError).toBeUndefined();
- const session = await harness.sessionManager.getSession('test-doc');
- expect(readFmRegion(session.dc.document)).toBe('title: My Doc');
- });
-
- test('emits start-ui warning when no UI is attached + no preview URL resolves', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBeUndefined();
- const structured = result.structuredContent as {
- warning?: { action: string; previewUrl: unknown; message: string; autoOpen: boolean };
- };
- expect(structured.warning).toBeDefined();
- expect(structured.warning?.action).toBe('start-ui');
- expect(structured.warning?.previewUrl).toBeNull();
- expect(structured.warning?.message).toContain('ok ui');
- expect(structured.warning?.message).toContain('preview_start');
- expect(structured.warning?.message).toContain('OK Electron');
- expect(structured.warning?.autoOpen).toBe(true);
- });
-
- test('start-ui warning carries autoOpen=false when user disabled it', async () => {
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, {
- serverUrl: harness.baseUrl,
- config: ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } }),
- resolveCwd: async () => harness.projectDir,
- });
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBeUndefined();
- const structured = result.structuredContent as {
- warning?: { action: string; previewUrl: unknown; autoOpen: boolean };
- };
- expect(structured.warning?.action).toBe('start-ui');
- expect(structured.warning?.previewUrl).toBeNull();
- expect(structured.warning?.autoOpen).toBe(false);
- });
-
- test('attach-preview-once warning carries autoOpen=false when user disabled it', async () => {
- bindTestUiLock(harness.projectDir);
- await seedDoc('test-doc', '---\ntitle: My Doc\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, {
- serverUrl: harness.baseUrl,
- config: ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } }),
- resolveCwd: async () => harness.projectDir,
- });
-
- const result = await getTool().handler({
- docName: 'test-doc',
- patch: { status: 'reviewed' },
- });
-
- expect(result.isError).toBeUndefined();
- const structured = result.structuredContent as {
- warning?: { action: string; previewUrl: unknown; autoOpen: boolean };
- };
- expect(structured.warning?.action).toBe('attach-preview-once');
- expect(structured.warning?.previewUrl).toBe('/#/test-doc');
- expect(structured.warning?.autoOpen).toBe(false);
- });
-});
diff --git a/packages/server/src/mcp/tools/edit-frontmatter.ts b/packages/server/src/mcp/tools/edit-frontmatter.ts
deleted file mode 100644
index b3918ec08..000000000
--- a/packages/server/src/mcp/tools/edit-frontmatter.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import {
- FRONTMATTER_TYPES,
- FrontmatterValueSchema,
- WriteWarningSchema,
-} from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import { resolveLockDir } from '../../config/paths.ts';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpPost,
- normalizeDocName,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- summaryArgSchema,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Set, create, or delete frontmatter properties via JSON Merge Patch (RFC 7396).',
- '',
- 'Field-level CRDT merge: concurrent patches to different keys (human form + this tool, or two agents) merge cleanly. Same-key concurrent writes resolve last-writer-wins per key.',
- '',
- '**Use this tool — not `edit_document` — for any frontmatter change.** `edit_document` (agent-patch) targets body content; FM-intersecting `edit_document` calls return HTTP 400. For full-document rewrites (≥3-5 frontmatter keys changing), `write_document({ position: "replace" })` remains the canonical pathway.',
- '',
- '**Parameters:**',
- '- `docName` — Document name. A trailing `.md` or `.mdx` is stripped automatically.',
- '- `patch` — Object whose keys are property names. Each value is the new value (string, number, boolean, or array of strings) to **set or create** the key, or `null` to **delete** the key. Keys not present in `patch` are unchanged.',
- '- `types` (optional) — **Currently ignored.** Shape-validated for forward-compat but not persisted server-side; type is inferred from value shape on read. Reserved for a future per-key widget-type override (`text | number | boolean | date | list`) once persistence ships.',
- '- `summary` — Optional one-line user-outcome description (≤80 chars). Prefer outcome phrasing ("Marked spec as approved") over structural ("Set status field"). Avoid secrets / PII — summaries persist to git history.',
- '',
- '**Atomicity:** any value failing schema validation rejects the WHOLE patch (HTTP 400 with per-key error report). Either every change commits or none do.',
-].join('\n');
-
-interface EditFrontmatterDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- identityRef?: { current: AgentIdentity };
-}
-
-const PatchValueSchema = z
- .union([FrontmatterValueSchema, z.null()])
- .describe('Property value (string|number|boolean|string[]) — `null` deletes the key');
-
-export function register(server: ServerInstance, deps: EditFrontmatterDeps): void {
- server.registerTool(
- 'edit_frontmatter',
- {
- description: DESCRIPTION,
- inputSchema: {
- docName: z.string().describe('Document name'),
- patch: z
- .record(z.string(), PatchValueSchema)
- .describe('JSON Merge Patch — `{key: value}` sets, `{key: null}` deletes'),
- types: z
- .record(z.string(), z.enum(FRONTMATTER_TYPES))
- .optional()
- .describe(
- 'Currently ignored (shape-validated for forward-compat but not persisted). Type is inferred from value shape on read. Will become a real per-key widget-type override (text|number|boolean|date|list) once persistence lands.',
- ),
- summary: summaryArgSchema,
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: {
- docName: string;
- patch: Record<string, string | number | boolean | string[] | null>;
- types?: Record<string, 'text' | 'number' | 'boolean' | 'date' | 'list'>;
- summary?: 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 { cwd, config, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const autoOpen = config.appearance.preview.autoOpen;
- const normalized = normalizeDocName(args.docName);
- if (!normalized.ok) return textResult(normalized.error, true);
- const identity = deps.identityRef?.current;
-
- const result = await httpPost(url, '/api/frontmatter-patch', {
- docName: normalized.docName,
- patch: args.patch,
- ...(args.types ? { types: args.types } : {}),
- ...(args.summary !== undefined ? { summary: args.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
- if (!result.ok) {
- const errorText = result.error as string;
- const fieldErrors =
- result.fieldErrors && typeof result.fieldErrors === 'object'
- ? (result.fieldErrors as Record<string, string>)
- : undefined;
- if (fieldErrors) {
- const lines = Object.entries(fieldErrors).map(([key, msg]) => ` ${key}: ${msg}`);
- return textResult(`Error: ${errorText}\n${lines.join('\n')}`, true);
- }
- return textResult(`Error: ${errorText}`, true);
- }
-
- const lockDir = resolveLockDir(cwd);
- const preview = resolvePreviewUrl(normalized.docName, { lockDir });
- const subscriberCount =
- typeof result.subscriberCount === 'number' ? result.subscriberCount : undefined;
- const systemSubscriberCount =
- typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;
- const noPreviewAnywhere = systemSubscriberCount === 0;
- const noPreviewOnThisDoc = subscriberCount === 0;
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const setKeys: string[] = [];
- const deleteKeys: string[] = [];
- for (const [key, value] of Object.entries(args.patch)) {
- if (value === null) deleteKeys.push(key);
- else setKeys.push(key);
- }
- const opSummary = [
- setKeys.length ? `${setKeys.length} set` : '',
- deleteKeys.length ? `${deleteKeys.length} deleted` : '',
- ]
- .filter(Boolean)
- .join(', ');
-
- const lines: string[] = [
- `Frontmatter patched (${opSummary || `${Object.keys(args.patch).length} key(s)`}).`,
- ];
- if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
- if (summaryHint) lines.push(summaryHint);
- const writeWarningParse = WriteWarningSchema.safeParse(result.warning);
- const writeWarning = writeWarningParse.success ? writeWarningParse.data : undefined;
- if (writeWarning?.hint) lines.push(`⚠ ${writeWarning.hint}`);
- const text = lines.join('\n');
-
- if (
- !preview &&
- !noPreviewAnywhere &&
- !noPreviewOnThisDoc &&
- !summaryResult &&
- !writeWarning
- ) {
- return textResult(text);
- }
-
- const structured: Record<string, unknown> = {};
- if (writeWarning) {
- structured.contentDivergence = writeWarning;
- }
- if (preview) {
- structured.previewUrl = preview.url;
- structured.previewUrlSource = preview.source;
- }
- if (noPreviewAnywhere) {
- structured.warning = buildPreviewAttachWarning(preview, autoOpen);
- }
- if (summaryResult) {
- structured.summary = summaryResult;
- }
- return textPlusStructured(text, structured);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
new file mode 100644
index 000000000..92cb4042b
--- /dev/null
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -0,0 +1,516 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { renderInventoryFooter, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { parse as parseYaml } from 'yaml';
+import { z } from 'zod';
+import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
+import { applyFolderFrontmatterPatch } from '../../content/folder-frontmatter-write.ts';
+import { mergePatch } from '../../content/frontmatter-merge.ts';
+import { applyTemplateWrite, type TemplateFrontmatter } from '../../content/templates-write.ts';
+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
+import type { AgentIdentity } from '../agent-identity.ts';
+import { formatContentDivergenceLine, parseContentDivergence } from './content-divergence.ts';
+import { resolveWithinRoot } from './path-safety.ts';
+import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ documentResultBaseShape,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpPost,
+ nestDocResult,
+ normalizeDocName,
+ outputSchemaWithText,
+ previewAttachWarningField,
+ previewUrlOutputField,
+ previewUrlSourceField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import {
+ exactlyOneTargetError,
+ FrontmatterArg,
+ resolveTemplatePath,
+ TEMPLATE_PATH_DESCRIBE,
+} from './verb-schemas.ts';
+
+type FrontmatterPatch = Record<string, string | number | boolean | string[] | null>;
+
+const BASE_DESCRIPTION = [
+ 'Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, or `template`. Within each: a body edit (`find` + `replace`) OR a `frontmatter` merge-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 (fs-direct): `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',
+ '- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, recorded for DOCUMENT edits only (folder and template edits are fs-direct git rewrites and do not record a timeline summary). Avoid secrets or PII — persisted to git history.',
+ '',
+ 'Responses may include `structuredContent.document.contentDivergence` when the converged Y.Text doesn\'t match the bytes your edit composed to. The edit still landed; re-read the doc with `exec("cat <path>")` to see what converged.',
+].join('\n');
+
+export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
+
+interface EditDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+interface BodyEdit {
+ find?: string;
+ replace?: string;
+ occurrence?: number;
+}
+
+function bodyOrFrontmatterError(
+ t: BodyEdit & { frontmatter?: FrontmatterPatch },
+ label: string,
+): string | null {
+ const hasBody = t.find !== undefined || t.replace !== undefined;
+ const hasFm = t.frontmatter !== undefined;
+ if (t.find !== undefined && t.replace === undefined) {
+ return `\`find\` needs a \`replace\`. Body edit: { ${label}: { …, find, replace } }.`;
+ }
+ if (t.replace !== undefined && t.find === undefined) {
+ return `\`replace\` needs a \`find\`. Body edit: { ${label}: { …, find, replace } }.`;
+ }
+ if (hasBody && hasFm) {
+ return `Pick ONE: edit body text (find+replace) OR metadata (frontmatter), not both in one call.`;
+ }
+ if (!hasBody && !hasFm) {
+ return `Provide either a body edit (find+replace) or a frontmatter patch for { ${label} }.`;
+ }
+ return null;
+}
+
+function readDocFullText(contentDir: string, docName: string): string | null {
+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {
+ const contained = resolveWithinRoot(contentDir, `${docName}${ext}`);
+ if (contained.ok && existsSync(contained.abs)) {
+ try {
+ return readFileSync(contained.abs, 'utf-8');
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null;
+ throw err;
+ }
+ }
+ }
+ return null;
+}
+
+function nthOccurrenceOffset(text: string, find: string, occurrence: number): number {
+ let from = 0;
+ for (let i = 0; i < occurrence; i++) {
+ const idx = text.indexOf(find, from);
+ if (idx === -1) return -1;
+ if (i === occurrence - 1) return idx;
+ from = idx + Math.max(1, find.length);
+ }
+ return -1;
+}
+
+async function handleDocBody(
+ doc: { path: string; find?: string; replace?: string; occurrence?: number },
+ args: { summary?: string },
+ cwd: string,
+ contentDir: string,
+ url: string,
+ deps: EditDeps,
+ autoOpen: boolean,
+) {
+ const normalized = normalizeDocName(doc.path);
+ if (!normalized.ok) return textResult(normalized.error, true);
+ const identity = deps.identityRef?.current;
+
+ let offset: number | undefined;
+ const occurrence = doc.occurrence ?? 1;
+ if (occurrence > 1) {
+ let full: string | null;
+ try {
+ full = readDocFullText(contentDir, normalized.docName);
+ } catch (err) {
+ return textResult(
+ `Error: cannot read "${normalized.docName}" to resolve occurrence ${occurrence}: ${err instanceof Error ? err.message : String(err)}.`,
+ true,
+ );
+ }
+ if (full === null) {
+ return textResult(
+ `Error: cannot resolve occurrence ${occurrence} — "${normalized.docName}" is not on disk yet. Retry with the first match (omit \`occurrence\`).`,
+ true,
+ );
+ }
+ const idx = nthOccurrenceOffset(full, doc.find as string, occurrence);
+ if (idx === -1) {
+ return textResult(
+ `Error: \`find\` occurs fewer than ${occurrence} times in "${normalized.docName}".`,
+ true,
+ );
+ }
+ offset = idx;
+ }
+
+ const result = await httpPost(url, '/api/agent-patch', {
+ docName: normalized.docName,
+ find: doc.find,
+ replace: doc.replace,
+ ...(offset !== undefined ? { offset } : {}),
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(identity),
+ });
+ if (!result.ok) {
+ const detail =
+ typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
+ return textResult(
+ detail ? `Error: ${result.error} (${detail})` : `Error: ${result.error}`,
+ true,
+ );
+ }
+ return composeWritePreviewResult(
+ result,
+ normalized.docName,
+ cwd,
+ autoOpen,
+ 'Edit applied successfully.',
+ );
+}
+
+async function handleDocFrontmatter(
+ doc: { path: string; frontmatter: FrontmatterPatch },
+ args: { summary?: string },
+ cwd: string,
+ url: string,
+ deps: EditDeps,
+ autoOpen: boolean,
+) {
+ const normalized = normalizeDocName(doc.path);
+ if (!normalized.ok) return textResult(normalized.error, true);
+ const identity = deps.identityRef?.current;
+ const result = await httpPost(url, '/api/frontmatter-patch', {
+ docName: normalized.docName,
+ patch: doc.frontmatter,
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(identity),
+ });
+ if (!result.ok) {
+ const errorText = result.error as string;
+ const fieldErrors =
+ result.fieldErrors && typeof result.fieldErrors === 'object'
+ ? (result.fieldErrors as Record<string, string>)
+ : undefined;
+ if (fieldErrors) {
+ const lines = Object.entries(fieldErrors).map(([k, m]) => ` ${k}: ${m}`);
+ return textResult(`Error: ${errorText}\n${lines.join('\n')}`, true);
+ }
+ return textResult(`Error: ${errorText}`, true);
+ }
+ const setKeys: string[] = [];
+ const deleteKeys: string[] = [];
+ for (const [key, value] of Object.entries(doc.frontmatter)) {
+ if (value === null) deleteKeys.push(key);
+ else setKeys.push(key);
+ }
+ const opSummary = [
+ setKeys.length ? `${setKeys.length} set` : '',
+ deleteKeys.length ? `${deleteKeys.length} deleted` : '',
+ ]
+ .filter(Boolean)
+ .join(', ');
+ return composeWritePreviewResult(
+ result,
+ normalized.docName,
+ cwd,
+ autoOpen,
+ `Frontmatter patched (${opSummary || `${Object.keys(doc.frontmatter).length} key(s)`}).`,
+ );
+}
+
+function composeWritePreviewResult(
+ result: Awaited<ReturnType<typeof httpPost>>,
+ docName: string,
+ cwd: string,
+ autoOpen: boolean,
+ leadLine: string,
+) {
+ const lockDir = resolveLockDir(cwd);
+ const preview = resolvePreviewUrl(docName, { lockDir });
+ const subscriberCount =
+ typeof result.subscriberCount === 'number' ? result.subscriberCount : undefined;
+ const systemSubscriberCount =
+ typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;
+ const noPreviewAnywhere = systemSubscriberCount === 0;
+ const noPreviewOnThisDoc = subscriberCount === 0;
+ const summaryResult =
+ result.summary && typeof result.summary === 'object'
+ ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
+ : undefined;
+ const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
+ const contentDivergence = parseContentDivergence(result.warning);
+
+ const lines: string[] = [leadLine];
+ if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
+ if (summaryHint) lines.push(summaryHint);
+ if (contentDivergence) {
+ lines.push(formatContentDivergenceLine(contentDivergence));
+ }
+ const text = lines.join('\n');
+ if (
+ !preview &&
+ !noPreviewAnywhere &&
+ !noPreviewOnThisDoc &&
+ !summaryResult &&
+ !contentDivergence
+ ) {
+ return textResult(text);
+ }
+ const document: Record<string, unknown> = {};
+ if (summaryResult) document.summary = summaryResult;
+ if (contentDivergence) document.contentDivergence = contentDivergence;
+ const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;
+ return textPlusStructured(text, nestDocResult(preview, warning, document));
+}
+
+function templateFilePath(
+ cwd: string,
+ folder: string,
+ name: string,
+): { ok: true; abs: string } | { ok: false } {
+ const contained = resolveWithinRoot(
+ cwd,
+ `${folder.replace(/\/+$/, '')}/.ok/templates/${name}.md`,
+ );
+ return contained.ok ? { ok: true, abs: contained.abs } : { ok: false };
+}
+
+function parseTemplateFrontmatter(raw: string): TemplateFrontmatter {
+ const inner = raw
+ .replace(/^---\r?\n/, '')
+ .replace(/\r?\n?---\r?\n?$/, '')
+ .trim();
+ if (inner === '') return { title: '' };
+ const parsed: unknown = parseYaml(inner);
+ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) return { title: '' };
+ const obj = parsed as Record<string, unknown>;
+ return {
+ title: typeof obj.title === 'string' ? obj.title : '',
+ ...(typeof obj.description === 'string' ? { description: obj.description } : {}),
+ ...(Array.isArray(obj.tags) ? { tags: obj.tags.map((t) => String(t)) } : {}),
+ };
+}
+
+function handleTemplate(
+ template: {
+ path: string;
+ find?: string;
+ replace?: string;
+ occurrence?: number;
+ frontmatter?: FrontmatterPatch;
+ },
+ cwd: string,
+) {
+ const teaching = bodyOrFrontmatterError(template, 'template');
+ if (teaching) return textResult(`Error: ${teaching}`, true);
+
+ const resolved = resolveTemplatePath(template.path);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ const { folder, name } = resolved;
+
+ const filePath = templateFilePath(cwd, folder, name);
+ if (!filePath.ok || !existsSync(filePath.abs)) {
+ return textResult(
+ `Error: template "${name}" not found in ${folder || '(root)'}. Create it with \`write({ template })\` first.`,
+ true,
+ );
+ }
+ let raw: string;
+ try {
+ raw = readFileSync(filePath.abs, 'utf-8');
+ } catch (err) {
+ return textResult(`Error: could not read template: ${(err as Error).message}`, true);
+ }
+ const { frontmatter: fmRaw, body } = stripFrontmatter(raw);
+ const existingFm = parseTemplateFrontmatter(fmRaw);
+
+ if (template.frontmatter !== undefined) {
+ const merged = mergePatch(
+ existingFm as Record<string, unknown>,
+ template.frontmatter as Record<string, unknown>,
+ ) as TemplateFrontmatter;
+ const result = applyTemplateWrite({ projectDir: cwd, folder, name, body, frontmatter: merged });
+ if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
+ return textPlusStructured(`Patched template "${name}" frontmatter (${result.path}).`, {
+ template: { ok: true, path: result.path },
+ });
+ }
+
+ const occurrence = template.occurrence ?? 1;
+ const idx = nthOccurrenceOffset(body, template.find as string, occurrence);
+ if (idx === -1) {
+ return textResult(
+ `Error: \`find\` occurs fewer than ${occurrence} time(s) in template "${name}".`,
+ true,
+ );
+ }
+ const newBody =
+ body.slice(0, idx) +
+ (template.replace as string) +
+ body.slice(idx + (template.find as string).length);
+ const result = applyTemplateWrite({
+ projectDir: cwd,
+ folder,
+ name,
+ body: newBody,
+ frontmatter: existingFm,
+ });
+ if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
+ return textPlusStructured(`Edited template "${name}" (${result.path}).`, {
+ template: { ok: true, path: result.path },
+ });
+}
+
+function handleFolder(folder: { path: string; frontmatter: FrontmatterPatch }, contentDir: string) {
+ const result = applyFolderFrontmatterPatch({
+ anchorDir: contentDir,
+ folderRel: folder.path,
+ patch: folder.frontmatter as Record<string, unknown>,
+ });
+ if (!result.ok) return textResult(`Error: ${result.error.message}`, true);
+ const verb =
+ result.action === 'deleted' ? 'Cleared' : result.action === 'noop' ? 'No change to' : 'Updated';
+ return textPlusStructured(`${verb} folder properties for ${folder.path} (${result.path}).`, {
+ folder: { ok: true, path: result.path, action: result.action },
+ });
+}
+
+export function register(server: ServerInstance, deps: EditDeps): void {
+ const bodyFields = {
+ find: z
+ .string()
+ .optional()
+ .describe(
+ 'Exact BODY text to find. Use WITH `replace`. For metadata, use `frontmatter` instead — not this.',
+ ),
+ replace: z.string().optional().describe('Replacement for the `find` match.'),
+ occurrence: z
+ .number()
+ .int()
+ .positive()
+ .optional()
+ .describe('Which match to edit (1 = first). Default: first.'),
+ };
+
+ server.registerTool(
+ 'edit',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ document: z
+ .object({
+ path: z
+ .string()
+ .describe(
+ 'Document path, no extension — the slashes are its folder. Example: "meetings/standup".',
+ ),
+ ...bodyFields,
+ frontmatter: FrontmatterArg.optional().describe(
+ 'Metadata merge-patch (set keys; `null` deletes a key). Use INSTEAD of find/replace.',
+ ),
+ })
+ .optional()
+ .describe(
+ 'Edit a DOCUMENT: its body (find+replace) OR its frontmatter (patch). Body: { document: { path, find, replace } }. Metadata: { document: { path, frontmatter } }.',
+ ),
+ folder: z
+ .object({
+ path: z.string().describe('Folder path.'),
+ frontmatter: FrontmatterArg.describe(
+ "Update the folder's own title/description/tags (merge-patch; `null` deletes).",
+ ),
+ })
+ .optional()
+ .describe(
+ 'Edit a FOLDER: only its frontmatter (folders have no body). Example: { folder: { path: "meetings", frontmatter: { description: "All-hands" } } }',
+ ),
+ template: z
+ .object({
+ path: z.string().describe(TEMPLATE_PATH_DESCRIBE),
+ ...bodyFields,
+ frontmatter: FrontmatterArg.optional().describe('Template metadata merge-patch.'),
+ })
+ .optional()
+ .describe('Edit a TEMPLATE: body (find+replace) or frontmatter (patch).'),
+ summary: summaryArgSchema,
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ document: z
+ .object(documentResultBaseShape)
+ .optional()
+ .describe('Document edit result (present when there is a doc-specific signal).'),
+ folder: z
+ .object({
+ ok: z.boolean(),
+ path: z.string(),
+ action: z
+ .string()
+ .describe('`written` (created/updated) | `deleted` (cleared) | `noop`.'),
+ })
+ .optional()
+ .describe('Folder frontmatter edit result.'),
+ template: z
+ .object({ ok: z.boolean(), path: z.string() })
+ .optional()
+ .describe('Template edit result.'),
+ previewUrl: previewUrlOutputField.optional(),
+ previewUrlSource: previewUrlSourceField,
+ warning: previewAttachWarningField,
+ }),
+ },
+ async (args: {
+ document?: { path: string } & BodyEdit & { frontmatter?: FrontmatterPatch };
+ folder?: { path: string; frontmatter: FrontmatterPatch };
+ template?: { path: string } & BodyEdit & { frontmatter?: FrontmatterPatch };
+ summary?: 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 { cwd, config, url } = context;
+ const contentDir = resolveContentDir(config, cwd);
+ const autoOpen = config.appearance.preview.autoOpen;
+
+ const teaching = exactlyOneTargetError(args as Record<string, unknown>, [
+ 'document',
+ 'folder',
+ 'template',
+ ]);
+ if (teaching) return textResult(`Error: ${teaching}`, true);
+
+ if (args.document !== undefined) {
+ const docTeaching = bodyOrFrontmatterError(args.document, 'document');
+ if (docTeaching) return textResult(`Error: ${docTeaching}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ if (args.document.frontmatter !== undefined) {
+ return handleDocFrontmatter(
+ { path: args.document.path, frontmatter: args.document.frontmatter },
+ args,
+ cwd,
+ url,
+ deps,
+ autoOpen,
+ );
+ }
+ return handleDocBody(args.document, args, cwd, contentDir, url, deps, autoOpen);
+ }
+ if (args.folder !== undefined) return handleFolder(args.folder, contentDir);
+ return handleTemplate(args.template as NonNullable<typeof args.template>, cwd);
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.ts
index 84df0b073..c908d7428 100644
--- a/packages/server/src/mcp/tools/exec.ts
+++ b/packages/server/src/mcp/tools/exec.ts
@@ -23,7 +23,12 @@ import {
import { resolveWithinRoot } from './path-safety.ts';
import { buildListResolver, docNameFromPath, type PreviewUrlSource } from './preview-url.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import { resolveProjectServerContext, textPlusStructured } from './shared.ts';
+import {
+ looseObjectArray,
+ outputSchemaWithText,
+ resolveProjectServerContext,
+ textPlusStructured,
+} from './shared.ts';
const SOFT_CAP_LINES = 500;
const SOFT_CAP_BYTES = 50 * 1024;
@@ -35,7 +40,7 @@ export const DESCRIPTION = [
'',
'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).',
'',
- 'Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.',
+ 'Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, redirections, subshells, and writes are rejected. To do several things, make separate exec calls or pass multiple paths to one command (e.g. `ls -A a b c`, `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.",
'',
@@ -481,6 +486,28 @@ export function register(server: ServerInstance, deps: ExecDeps): void {
'Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.',
),
},
+ outputSchema: outputSchemaWithText({
+ enrichedPaths: looseObjectArray.describe(
+ 'Per-referenced-file metadata: frontmatter, backlink/forward-link counts, recent shadow-repo activity, and a route-only previewUrl.',
+ ),
+ stdout: z
+ .string()
+ .optional()
+ .describe('Raw command stdout (soft-cap truncated), without banners or enrichment.'),
+ stdoutTruncated: z
+ .boolean()
+ .optional()
+ .describe('True when stdout was truncated by the soft cap.'),
+ warnings: z
+ .array(z.string())
+ .optional()
+ .describe('Tool-level warnings — head/tail truncation, binary detection, stderr.'),
+ cwd: z.string().optional().describe('Absolute directory the command ran in.'),
+ error: z
+ .object({ category: z.string(), message: z.string() })
+ .optional()
+ .describe('Present on failure — the error category + message.'),
+ }),
},
async (args: { command: string; cwd?: string }) => {
try {
diff --git a/packages/server/src/mcp/tools/folder-config.test.ts b/packages/server/src/mcp/tools/folder-config.test.ts
deleted file mode 100644
index 00b6e90da..000000000
--- a/packages/server/src/mcp/tools/folder-config.test.ts
+++ /dev/null
@@ -1,407 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import {
- normalizeObjectSchema,
- safeParseAsync,
-} from '@modelcontextprotocol/sdk/server/zod-compat.js';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { DESCRIPTION, register } from './folder-config.ts';
-import type { ServerInstance } 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: Record<string, unknown>) => Promise<ToolResult>;
-
-interface CapturedTool {
- name: string;
- description: string;
- inputSchema: unknown;
- outputSchema: unknown;
- annotations: { readOnlyHint: boolean; idempotentHint: boolean; destructiveHint: boolean };
- handler: Handler;
-}
-
-function newProject(): string {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-folder-config-'));
- mkdirSync(join(cwd, '.ok'), { recursive: true });
- return cwd;
-}
-
-function captureRegistration(cwd: string): CapturedTool {
- let captured: CapturedTool | null = null;
- const server = {
- registerTool(
- name: string,
- cfg: {
- description?: string;
- inputSchema?: unknown;
- outputSchema?: unknown;
- annotations?: {
- readOnlyHint: boolean;
- idempotentHint: boolean;
- destructiveHint: boolean;
- };
- },
- handler: Handler,
- ) {
- captured = {
- name,
- description: cfg.description ?? '',
- inputSchema: cfg.inputSchema,
- outputSchema: cfg.outputSchema,
- annotations: cfg.annotations ?? {
- readOnlyHint: false,
- idempotentHint: false,
- destructiveHint: false,
- },
- handler,
- };
- },
- tool() {
- throw new Error('legacy tool() API not expected');
- },
- } as unknown as ServerInstance;
- register(server, { config: BASE_CONFIG, resolveCwd: async () => cwd });
- if (!captured) throw new Error('tool did not register');
- return captured;
-}
-
-async function parseArgs(
- inputSchema: unknown,
- args: Record<string, unknown>,
-): Promise<{ success: boolean; errorText: string }> {
- const normalized = normalizeObjectSchema(
- inputSchema as Parameters<typeof normalizeObjectSchema>[0],
- );
- if (!normalized) throw new Error('inputSchema did not normalize');
- const result = await safeParseAsync(normalized, args);
- if (result.success) return { success: true, errorText: '' };
- const errAny = (result as { error?: unknown }).error;
- const errorText =
- errAny && typeof errAny === 'object' && 'message' in errAny
- ? String((errAny as { message: unknown }).message)
- : JSON.stringify(errAny);
- return { success: false, errorText };
-}
-
-function readNestedFm(cwd: string, folder: string): string | null {
- const p = folder
- ? join(cwd, folder, '.ok', 'frontmatter.yml')
- : join(cwd, '.ok', 'frontmatter.yml');
- return existsSync(p) ? readFileSync(p, 'utf-8') : null;
-}
-
-describe('folder_config — registration + DESCRIPTION', () => {
- test('registers exactly one tool named "folder_config" with the three-action surface', () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- expect(tool.name).toBe('folder_config');
- });
-
- test('DESCRIPTION enumerates the three actions and their parameter contracts', () => {
- expect(DESCRIPTION).toContain('action: "set-rule"');
- expect(DESCRIPTION).toContain('action: "write-template"');
- expect(DESCRIPTION).toContain('action: "delete-template"');
- expect(DESCRIPTION).not.toContain('declare-field');
- expect(DESCRIPTION).not.toContain('remove-field');
- expect(DESCRIPTION).toContain('rules');
- expect(DESCRIPTION).toContain('folder');
- expect(DESCRIPTION).toContain('name');
- expect(DESCRIPTION).toContain('body');
- expect(DESCRIPTION).toContain('frontmatter');
- expect(DESCRIPTION).toContain('open-shape');
- });
-
- test('annotations: readOnlyHint=false, idempotentHint=true, destructiveHint=true', () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- expect(tool.annotations.readOnlyHint).toBe(false);
- expect(tool.annotations.idempotentHint).toBe(true);
- expect(tool.annotations.destructiveHint).toBe(true);
- });
-
- test('outputSchema admits the auto-injected `text` mirror field', () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- expect(tool.outputSchema).toBeDefined();
- });
-});
-
-describe('folder_config — input-schema strictness per action', () => {
- test('action=set-rule: accepts a well-formed rules payload', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'set-rule',
- rules: [{ match: 'specs/**', frontmatter: { description: 'Specs' } }],
- });
- expect(r.errorText).toBe('');
- expect(r.success).toBe(true);
- });
-
- test('action=set-rule: extra keys are rejected by the strict outer schema (tightens vs retired set_folder_rule)', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'set-rule',
- rules: [{ match: 'specs/**', frontmatter: {} }],
- legacyExtra: 'ignored',
- });
- expect(r.success).toBe(false);
- expect(r.errorText).toMatch(/legacyExtra/);
- });
-
- test('action=write-template: accepts a well-formed payload', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'write-template',
- folder: '',
- name: 'foo',
- body: '# hi',
- frontmatter: { title: 'Hello' },
- });
- expect(r.errorText).toBe('');
- expect(r.success).toBe(true);
- });
-
- test('action=write-template: rejects stale `target` key (preserves write_template strictness)', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'write-template',
- folder: '',
- name: 'foo',
- body: '# hi',
- frontmatter: { title: 'Hello' },
- target: 'user',
- });
- expect(r.success).toBe(false);
- expect(r.errorText).toMatch(/target/i);
- });
-
- test('action=delete-template: accepts a well-formed payload', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'delete-template',
- folder: '',
- name: 'foo',
- });
- expect(r.errorText).toBe('');
- expect(r.success).toBe(true);
- });
-
- test('action=delete-template: rejects stale `target` key (preserves delete_template strictness)', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'delete-template',
- folder: '',
- name: 'foo',
- target: 'project',
- });
- expect(r.success).toBe(false);
- expect(r.errorText).toMatch(/target/i);
- });
-
- test('rejects unknown action values', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'bogus',
- rules: [],
- });
- expect(r.success).toBe(false);
- });
-});
-
-describe('folder_config — action=set-rule re-routes to applyNestedFolderRulesUpsert', () => {
- test('writes nested <folder>/.ok/frontmatter.yml for `specs/**`', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- action: 'set-rule',
- rules: [{ match: 'specs/**', frontmatter: { description: 'Specs', tags: ['spec'] } }],
- });
- expect(result.isError).toBeUndefined();
- const yaml = readNestedFm(cwd, 'specs');
- expect(yaml).not.toBeNull();
- expect(yaml).toContain('description: Specs');
- expect(yaml).toContain('- spec');
- });
-
- test('supports new_match rule-move semantics', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- await tool.handler({
- action: 'set-rule',
- rules: [{ match: 'oldspecs/**', frontmatter: { description: 'Old' } }],
- });
- await tool.handler({
- action: 'set-rule',
- rules: [
- {
- match: 'oldspecs/**',
- new_match: 'newspecs/**',
- frontmatter: { description: 'Old' },
- },
- ],
- });
- expect(readNestedFm(cwd, 'oldspecs')).toBeNull();
- expect(readNestedFm(cwd, 'newspecs')).toContain('description: Old');
- });
-
- test('multi-folder glob is rejected with MULTI_FOLDER_GLOB', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- action: 'set-rule',
- rules: [{ match: 'specs/*/evidence/**', frontmatter: {} }],
- });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('MULTI_FOLDER_GLOB');
- });
-});
-
-describe('folder_config — action=write-template re-routes to applyTemplateWrite', () => {
- test('creates a template at <folder>/.ok/templates/<name>.md', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- action: 'write-template',
- folder: 'meetings',
- name: 'standup',
- body: '# Standup {{date}}',
- frontmatter: { title: 'Standup notes' },
- });
- expect(result.isError).toBeUndefined();
- const path = join(cwd, 'meetings', '.ok', 'templates', 'standup.md');
- expect(existsSync(path)).toBe(true);
- const body = readFileSync(path, 'utf-8');
- expect(body).toContain('Standup notes');
- expect(body).toContain('{{date}}');
- });
-
- test('rejects body with unknown substitution token', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- action: 'write-template',
- folder: '',
- name: 'bad',
- body: '# {{secret}}',
- frontmatter: { title: 'Bad' },
- });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('TEMPLATE_UNKNOWN_VARIABLE');
- });
-});
-
-describe('folder_config — action=delete-template re-routes to applyTemplateDelete', () => {
- test('removes <folder>/.ok/templates/<name>.md', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- await tool.handler({
- action: 'write-template',
- folder: 'meetings',
- name: 'standup',
- body: '# Standup',
- frontmatter: { title: 'Standup notes' },
- });
- const path = join(cwd, 'meetings', '.ok', 'templates', 'standup.md');
- expect(existsSync(path)).toBe(true);
-
- const result = await tool.handler({
- action: 'delete-template',
- folder: 'meetings',
- name: 'standup',
- });
- expect(result.isError).toBeUndefined();
- expect(existsSync(path)).toBe(false);
- });
-
- test('idempotent: deleting a non-existent template returns success with existed:false', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- action: 'delete-template',
- folder: 'meetings',
- name: 'ghost',
- });
- expect(result.isError).toBeUndefined();
- const payload = result.structuredContent as { result: { ok: boolean; existed: boolean } };
- expect(payload.result.ok).toBe(true);
- expect(payload.result.existed).toBe(false);
- });
-});
-
-describe('folder_config — batch (operations)', () => {
- test('applies a set-rule + write-template in one call', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- operations: [
- {
- action: 'set-rule',
- rules: [{ match: 'specs/**', frontmatter: { description: 'Specs', tags: ['spec'] } }],
- },
- {
- action: 'write-template',
- folder: 'specs',
- name: 'SPEC',
- body: '# {{date}}',
- frontmatter: { title: 'Spec' },
- },
- ],
- });
- expect(result.isError).toBeUndefined();
- expect(readNestedFm(cwd, 'specs')).toContain('description: Specs');
- expect(existsSync(join(cwd, 'specs', '.ok', 'templates', 'SPEC.md'))).toBe(true);
- const payload = result.structuredContent as {
- result: { ok: boolean; operations: Array<{ action: string; result: { ok: boolean } }> };
- };
- expect(payload.result.ok).toBe(true);
- expect(payload.result.operations).toHaveLength(2);
- expect(payload.result.operations.every((o) => o.result.ok)).toBe(true);
- });
-
- test('a failing operation surfaces in the batch result without blocking the rest', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const result = await tool.handler({
- operations: [
- { action: 'set-rule', rules: [{ match: 'docs/**', frontmatter: { description: 'Docs' } }] },
- { action: 'set-rule', rules: [{ match: 'a/*/b/**', frontmatter: {} }] },
- ],
- });
- expect(result.isError).toBe(true);
- expect(readNestedFm(cwd, 'docs')).toContain('description: Docs');
- const payload = result.structuredContent as {
- result: { ok: boolean; operations: Array<{ result: { ok: boolean } }> };
- };
- expect(payload.result.ok).toBe(false);
- expect(payload.result.operations[0]?.result.ok).toBe(true);
- expect(payload.result.operations[1]?.result.ok).toBe(false);
- });
-
- test('rejects `action` and `operations` together', async () => {
- const cwd = newProject();
- const tool = captureRegistration(cwd);
- const r = await parseArgs(tool.inputSchema, {
- action: 'set-rule',
- rules: [{ match: 'x/**', frontmatter: {} }],
- operations: [{ action: 'delete-template', folder: '', name: 'foo' }],
- });
- expect(r.success).toBe(false);
- expect(r.errorText).toMatch(/mutually exclusive/i);
- });
-});
diff --git a/packages/server/src/mcp/tools/folder-config.ts b/packages/server/src/mcp/tools/folder-config.ts
deleted file mode 100644
index f26fa8526..000000000
--- a/packages/server/src/mcp/tools/folder-config.ts
+++ /dev/null
@@ -1,488 +0,0 @@
-import { z } from 'zod';
-import { applyNestedFolderRulesUpsert } from '../../content/folder-rule-write.ts';
-import {
- applyTemplateDelete,
- applyTemplateWrite,
- type TemplateFrontmatter,
-} from '../../content/templates-write.ts';
-import type { ConfigOrResolver, ServerInstance } from './shared.ts';
-import {
- outputSchemaWithText,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectConfigContext,
- textPlusStructured,
-} from './shared.ts';
-
-export const DESCRIPTION = [
- '[Operates on disk; no running OK server required] Folder-level configuration writes. Dispatches on `action`:',
- '',
- "- `action: \"set-rule\"` — Upsert a folder's own frontmatter (open-shape, exactly like a doc's frontmatter — any key). Writes nested `<folder>/.ok/frontmatter.yml`. SELF-ONLY: this metadata describes the folder and does NOT cascade values into child docs — for per-doc starting values, write a template instead. Always batch-shape: pass `rules: [{...}]` even for one. Empty `frontmatter: {}` removes the rule and auto-cleans `<folder>/.ok/` if empty. Use `new_match` to rename the rule's match glob. Multi-folder globs are rejected (split per folder).",
- '- `action: "write-template"` — Create or update `<folder>/.ok/templates/<name>.md`. Templates are markdown starter shapes (the single mechanism for "what new docs start with"); agents instantiate via `write_document({ template })`. `title` in frontmatter is REQUIRED (menu surface). Body MAY use `{{date}}` / `{{user}}` substitution tokens; any other `{{...}}` is rejected. Unknown keys are rejected.',
- '- `action: "delete-template"` — Remove `<folder>/.ok/templates/<name>.md`. Idempotent (`existed: false` if missing). Auto-cleans empty `templates/` and `.ok/` dirs. Unknown keys are rejected.',
- '',
- 'To apply several writes in one call (e.g. set a folder rule and write its template together), pass `operations: [{action, ...}, ...]` instead of a top-level `action`. Operations run in order; the response reports each.',
- '',
- '**Parameters:**',
- '- `action` — `set-rule` | `write-template` | `delete-template`. Omit when using `operations`.',
- '- `operations` — Array of `{action, ...}` objects. Mutually exclusive with a top-level `action`.',
- "- `rules` — Required for `set-rule`. Array of `{match, frontmatter, new_match?}`. `match` is a folder glob (`specs/**`). `frontmatter` is the folder's own open-shape metadata (any key, like a doc); `null` / `''` / `[]` clears a key.",
- '- `folder` — Required for `write-template`/`delete-template`. Project-root-relative folder. Empty / `.` means project root.',
- '- `name` — Required for `write-template`/`delete-template`. Filename without `.md` (letters/digits/`_`/`-` only).',
- '- `body` — Required for `write-template`. Markdown body. May use `{{date}}` / `{{user}}`.',
- '- `frontmatter` — Required for `write-template`. `{title (required), description?, tags?: string[]}`.',
- '- `cwd` (optional) — Project root.',
-].join('\n');
-
-interface FolderConfigDeps {
- resolveCwd: (explicit?: string) => Promise<string>;
- config: ConfigOrResolver;
-}
-
-const ACTIONS = ['set-rule', 'write-template', 'delete-template'] as const;
-
-const FolderRuleUpsertInputSchema = z.object({
- match: z
- .string()
- .min(1)
- .describe(
- 'Glob pattern (e.g. "specs/**", "meetings/prep-notes/**") that identifies the target folder.',
- ),
- frontmatter: z
- .record(z.string(), z.unknown())
- .refine(
- (obj) => {
- if ('title' in obj && obj.title !== null && typeof obj.title !== 'string') return false;
- if ('description' in obj && obj.description !== null && typeof obj.description !== 'string')
- return false;
- if ('tags' in obj && obj.tags !== null && !Array.isArray(obj.tags)) return false;
- return true;
- },
- {
- message:
- 'Well-known keys must match expected types when present: `title` (string|null), `description` (string|null), `tags` (string[]|null).',
- },
- )
- .describe(
- "The folder's own open-shape frontmatter (any key, like a doc's). `title` / `description` / `tags` are conventional well-known keys the UI surfaces; other keys are allowed. Note one folder/doc asymmetry: only `title` / `description` / `tags` appear in `exec ls` output — other keys are stored and returned by `GET /api/folder-config` (and the folder-properties UI), but not surfaced on the directory listing. Self-only — does NOT cascade into child docs (use a template for per-doc starting values). `null` / `''` / `[]` clears a key; `{}` removes the rule.",
- ),
- new_match: z
- .string()
- .min(1)
- .optional()
- .describe('If set, move the rule from `match` to this new folder.'),
-});
-
-const TEMPLATE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
-
-const TemplateFrontmatterSchema = z.object({
- title: z
- .string()
- .min(1, 'Template `title` is required — it is the menu surface agents pick from.')
- .describe('Required. The menu surface agents pick from.'),
- description: z
- .string()
- .optional()
- .describe('Recommended. Disambiguates similarly-named templates.'),
- tags: z
- .array(z.string())
- .optional()
- .describe('Optional. Applied to docs created from this template.'),
-});
-
-const ACTION_FIELDS = {
- rules: z
- .array(FolderRuleUpsertInputSchema)
- .min(1)
- .optional()
- .describe('Required for `set-rule`. Array of folder rules to upsert.'),
- folder: z
- .string()
- .optional()
- .describe(
- 'Required for `write-template`/`delete-template`. Project-root-relative folder. Empty / `.` means project root.',
- ),
- name: z
- .string()
- .min(1)
- .max(128)
- .optional()
- .describe(
- 'Required for `write-template`/`delete-template`. Template filename without `.md` extension (letters/digits/`_`/`-` only — enforced per-action).',
- ),
- body: z.string().optional().describe('Required for `write-template`. Markdown body.'),
- frontmatter: TemplateFrontmatterSchema.optional().describe(
- 'Required for `write-template`. Template menu metadata.',
- ),
-} as const;
-
-const OperationSchema = z
- .object({
- action: z.enum(ACTIONS).describe('Which folder-config write to perform.'),
- ...ACTION_FIELDS,
- })
- .strict();
-
-type Operation = z.infer<typeof OperationSchema>;
-
-function checkActionFields(
- op: {
- action?: string;
- rules?: unknown;
- folder?: unknown;
- name?: unknown;
- body?: unknown;
- frontmatter?: unknown;
- },
- ctx: z.RefinementCtx,
- path: (string | number)[],
-): void {
- if (op.action === 'set-rule') {
- if (!op.rules) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=set-rule requires `rules`.',
- path: [...path, 'rules'],
- });
- }
- } else if (op.action === 'write-template') {
- if (op.folder === undefined) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=write-template requires `folder`.',
- path: [...path, 'folder'],
- });
- }
- if (!op.name) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=write-template requires `name`.',
- path: [...path, 'name'],
- });
- } else if (typeof op.name === 'string' && !TEMPLATE_NAME_REGEX.test(op.name)) {
- ctx.addIssue({
- code: 'custom',
- message:
- 'Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).',
- path: [...path, 'name'],
- });
- }
- if (op.body === undefined) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=write-template requires `body`.',
- path: [...path, 'body'],
- });
- }
- if (!op.frontmatter) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=write-template requires `frontmatter`.',
- path: [...path, 'frontmatter'],
- });
- }
- } else if (op.action === 'delete-template') {
- if (op.folder === undefined) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=delete-template requires `folder`.',
- path: [...path, 'folder'],
- });
- }
- if (!op.name) {
- ctx.addIssue({
- code: 'custom',
- message: 'action=delete-template requires `name`.',
- path: [...path, 'name'],
- });
- } else if (typeof op.name === 'string' && !TEMPLATE_NAME_REGEX.test(op.name)) {
- ctx.addIssue({
- code: 'custom',
- message:
- 'Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).',
- path: [...path, 'name'],
- });
- }
- }
-}
-
-const FolderConfigInputSchema = z
- .object({
- action: z
- .enum(ACTIONS)
- .optional()
- .describe('Which folder-config write to perform. Omit when `operations` is set.'),
- ...ACTION_FIELDS,
- operations: z
- .array(OperationSchema)
- .min(1)
- .optional()
- .describe(
- 'Batch form: apply several folder-config writes in one call. Mutually exclusive with `action`.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- })
- .strict()
- .superRefine((args, ctx) => {
- if (args.operations !== undefined) {
- if (args.action !== undefined) {
- ctx.addIssue({
- code: 'custom',
- message: '`action` and `operations` are mutually exclusive.',
- path: ['action'],
- });
- }
- for (const field of ['rules', 'folder', 'name', 'body', 'frontmatter'] as const) {
- if (args[field] !== undefined) {
- ctx.addIssue({
- code: 'custom',
- message: `\`${field}\` belongs inside an \`operations\` entry, not at the top level.`,
- path: [field],
- });
- }
- }
- args.operations.forEach((op, i) => {
- checkActionFields(op, ctx, ['operations', i]);
- });
- return;
- }
- if (args.action === undefined) {
- ctx.addIssue({
- code: 'custom',
- message: 'Provide either `action` or `operations`.',
- path: ['action'],
- });
- return;
- }
- checkActionFields(args, ctx, []);
- });
-
-type FolderConfigArgs = z.infer<typeof FolderConfigInputSchema>;
-
-const AppliedEntrySchema = z.object({
- match: z.string(),
- path: z.string(),
- action: z.enum(['written', 'deleted']),
-});
-
-const SingleResultSchema = z.union([
- z.object({ ok: z.literal(true), applied: z.array(AppliedEntrySchema) }),
- z.object({
- ok: z.literal(false),
- error: z.object({
- code: z.enum(['MULTI_FOLDER_GLOB', 'PATH_ESCAPE', 'BAD_PROJECT_DIR', 'WRITE_ERROR']),
- message: z.string(),
- rule: z.string().optional(),
- }),
- partiallyApplied: z.array(AppliedEntrySchema).optional(),
- }),
- z.object({
- ok: z.literal(true),
- path: z.string(),
- created: z.boolean(),
- warnings: z.array(z.string()),
- }),
- z.object({
- ok: z.literal(true),
- path: z.string(),
- existed: z.boolean(),
- cleanedEmpty: z.object({
- templatesDir: z.boolean(),
- okDir: z.boolean(),
- }),
- }),
- z.object({
- ok: z.literal(false),
- error: z.object({ code: z.string(), message: z.string() }),
- }),
-]);
-
-const FolderConfigOutputSchema = outputSchemaWithText({
- result: z.union([
- SingleResultSchema,
- z.object({
- ok: z.boolean(),
- operations: z.array(z.object({ action: z.enum(ACTIONS), result: SingleResultSchema })),
- }),
- ]),
-});
-
-export function register(server: ServerInstance, deps: FolderConfigDeps): void {
- server.registerTool(
- 'folder_config',
- {
- description: DESCRIPTION,
- inputSchema: FolderConfigInputSchema,
- outputSchema: FolderConfigOutputSchema,
- annotations: {
- readOnlyHint: false,
- idempotentHint: true,
- destructiveHint: true,
- },
- },
- async (args: FolderConfigArgs) => {
- const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
- if (!context.ok) {
- return {
- isError: true,
- content: [{ type: 'text' as const, text: `Error: ${context.error}` }],
- };
- }
- const { cwd } = context;
-
- if (args.operations !== undefined) {
- return handleBatch(args.operations, cwd);
- }
-
- switch (args.action) {
- case 'set-rule':
- return handleSetRule(args, cwd);
- case 'write-template':
- return handleWriteTemplate(args, cwd);
- case 'delete-template':
- return handleDeleteTemplate(args, cwd);
- }
- return {
- isError: true as const,
- content: [{ type: 'text' as const, text: 'Error: no action.' }],
- };
- },
- );
-}
-
-function applyOperation(op: Operation, cwd: string) {
- switch (op.action) {
- case 'set-rule': {
- if (!op.rules) {
- return {
- ok: false as const,
- error: { code: 'MISSING_FIELD', message: 'set-rule requires `rules`.' },
- };
- }
- return applyNestedFolderRulesUpsert({
- projectDir: cwd,
- rules: op.rules.map((r) => ({
- match: r.match,
- frontmatter: r.frontmatter ?? {},
- ...(r.new_match !== undefined ? { new_match: r.new_match } : {}),
- })),
- });
- }
- case 'write-template': {
- if (op.folder === undefined || !op.name || op.body === undefined || !op.frontmatter) {
- return {
- ok: false as const,
- error: {
- code: 'MISSING_FIELD',
- message: 'write-template requires `folder`, `name`, `body`, and `frontmatter`.',
- },
- };
- }
- return applyTemplateWrite({
- projectDir: cwd,
- folder: op.folder,
- name: op.name,
- body: op.body,
- frontmatter: op.frontmatter as TemplateFrontmatter,
- });
- }
- case 'delete-template': {
- if (op.folder === undefined || !op.name) {
- return {
- ok: false as const,
- error: {
- code: 'MISSING_FIELD',
- message: 'delete-template requires `folder` and `name`.',
- },
- };
- }
- return applyTemplateDelete({
- projectDir: cwd,
- folder: op.folder,
- name: op.name,
- });
- }
- }
-}
-
-function describeResult(action: string, result: ReturnType<typeof applyOperation>): string {
- if (!result.ok) return `${action}: ${result.error.code}: ${result.error.message}`;
- if ('applied' in result) return `${action}: ${result.applied.length} rule(s) applied`;
- if ('created' in result) {
- return `${action}: ${result.created ? 'created' : 'updated'} ${result.path}`;
- }
- if ('existed' in result) {
- return `${action}: ${result.existed ? 'deleted' : 'no-op (missing)'} ${result.path}`;
- }
- return action;
-}
-
-function handleBatch(operations: Operation[], cwd: string) {
- const results = operations.map((op) => ({ action: op.action, result: applyOperation(op, cwd) }));
- const allOk = results.every((r) => r.result.ok);
- const batchResult = { ok: allOk, operations: results };
- const text = results.map((r) => describeResult(r.action, r.result)).join('\n');
- if (!allOk) {
- return textPlusStructured(text, { result: batchResult }, true);
- }
- return textPlusStructured(text, { result: batchResult });
-}
-
-function handleSetRule(args: FolderConfigArgs, cwd: string) {
- const rules = args.rules ?? [];
- const result = applyNestedFolderRulesUpsert({
- projectDir: cwd,
- rules: rules.map((r) => ({
- match: r.match,
- frontmatter: r.frontmatter ?? {},
- ...(r.new_match !== undefined ? { new_match: r.new_match } : {}),
- })),
- });
-
- if (!result.ok) {
- return textPlusStructured(`${result.error.code}: ${result.error.message}`, { result }, true);
- }
-
- return textPlusStructured(JSON.stringify(result, null, 2), { result });
-}
-
-function handleWriteTemplate(args: FolderConfigArgs, cwd: string) {
- const result = applyTemplateWrite({
- projectDir: cwd,
- folder: args.folder ?? '',
- name: args.name ?? '',
- body: args.body ?? '',
- frontmatter: (args.frontmatter ?? { title: '' }) as TemplateFrontmatter,
- });
-
- if (!result.ok) {
- return textPlusStructured(`${result.error.code}: ${result.error.message}`, { result }, true);
- }
-
- const lines = [`${result.created ? 'Created' : 'Updated'} template at ${result.path}`];
- if (result.warnings.length > 0) {
- lines.push('', 'Warnings:');
- for (const w of result.warnings) lines.push(` - ${w}`);
- }
- return textPlusStructured(lines.join('\n'), { result });
-}
-
-function handleDeleteTemplate(args: FolderConfigArgs, cwd: string) {
- const result = applyTemplateDelete({
- projectDir: cwd,
- folder: args.folder ?? '',
- name: args.name ?? '',
- });
-
- if (!result.ok) {
- return textPlusStructured(`${result.error.code}: ${result.error.message}`, { result }, true);
- }
-
- const lines = [
- result.existed
- ? `Deleted template at ${result.path}`
- : `Template at ${result.path} did not exist (no-op)`,
- ];
- if (result.cleanedEmpty.templatesDir) lines.push('Removed empty .ok/templates/ directory');
- if (result.cleanedEmpty.okDir) lines.push('Removed empty .ok/ directory');
- return textPlusStructured(lines.join('\n'), { result });
-}
diff --git a/packages/server/src/mcp/tools/get-components.test.ts b/packages/server/src/mcp/tools/get-components.test.ts
deleted file mode 100644
index 66f55765a..000000000
--- a/packages/server/src/mcp/tools/get-components.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './get-components.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({ content: { dir: '.' } });
-
-interface ComponentEntry {
- id: string;
- displayName: string;
- description: string;
- kind: 'jsx-block' | 'jsx-void';
- example: string;
- params: Array<Record<string, unknown>>;
-}
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: {
- version: number;
- components: ComponentEntry[];
- notFound: string[];
- text?: string;
- };
- isError?: boolean;
-}
-
-type ToolHandler = (args: { ids: string[]; cwd?: string }) => Promise<ToolResult>;
-
-function captureRegistration(): ToolHandler {
- let captured: ToolHandler | null = null;
- const server = {
- registerTool(_name: string, _config: unknown, handler: ToolHandler) {
- captured = handler;
- },
- tool() {
- throw new Error('legacy tool() should not be called by get_components');
- },
- } as unknown as ServerInstance;
- register(server, {
- config: BASE_CONFIG,
- resolveCwd: async () => '/tmp/ok-get-components-test',
- });
- if (!captured) throw new Error('tool not registered');
- return captured;
-}
-
-describe('get_components tool', () => {
- test('empty ids → empty components, empty notFound, version stamp', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: [] });
- expect(result.isError).toBeUndefined();
- expect(result.structuredContent?.version).toBe(1);
- expect(result.structuredContent?.components).toEqual([]);
- expect(result.structuredContent?.notFound).toEqual([]);
- });
-
- test('unknown id surfaces in notFound; does not error', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['NotARealComponent'] });
- expect(result.structuredContent?.components).toEqual([]);
- expect(result.structuredContent?.notFound).toEqual(['NotARealComponent']);
- });
-
- test('known id returns a full entry with example + params', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['Callout'] });
- const components = result.structuredContent?.components ?? [];
- expect(components.length).toBe(1);
- const entry = components[0];
- expect(entry?.id).toBe('Callout');
- expect(entry?.kind).toBe('jsx-block');
- expect(entry?.example.length).toBeGreaterThan(0);
- expect(entry?.example).toContain('<Callout');
- expect(Array.isArray(entry?.params)).toBe(true);
- expect((entry?.params.length ?? 0) > 0).toBe(true);
- expect(result.structuredContent?.notFound).toEqual([]);
- });
-
- test('duplicate ids are deduplicated — each canonical appears once', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['Callout', 'Callout', 'Callout'] });
- expect(result.structuredContent?.components.length).toBe(1);
- expect(result.structuredContent?.components[0]?.id).toBe('Callout');
- });
-
- test('fence-kind id MermaidFence is excluded from the agent surface (D20)', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['MermaidFence'] });
- expect(result.structuredContent?.components).toEqual([]);
- expect(result.structuredContent?.notFound).toEqual(['MermaidFence']);
- });
-
- test('mixed batch — partial match: matched ids return entries, unmatched land in notFound', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['Callout', 'NopeNope', 'Tabs', 'MermaidFence'] });
- const components = result.structuredContent?.components ?? [];
- const componentIds = components.map((c) => c.id).sort();
- expect(componentIds).toEqual(['Callout', 'Tabs']);
- expect((result.structuredContent?.notFound ?? []).sort()).toEqual(['MermaidFence', 'NopeNope']);
- });
-
- test('content[0].text mirrors structuredContent body as JSON (dual-channel envelope)', async () => {
- const handler = captureRegistration();
- const result = await handler({ ids: ['Callout'] });
- const text = result.content[0]?.text;
- expect(text).toBeDefined();
- const parsed = JSON.parse(text ?? '{}');
- expect(parsed.version).toBe(1);
- expect(parsed.components.length).toBe(1);
- expect(parsed.notFound).toEqual([]);
- });
-});
diff --git a/packages/server/src/mcp/tools/get-components.ts b/packages/server/src/mcp/tools/get-components.ts
deleted file mode 100644
index ae77bb486..000000000
--- a/packages/server/src/mcp/tools/get-components.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import {
- type ComponentEntryFull,
- getAgentCanonicalDescriptors,
- projectFull,
-} from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import type { ConfigOrResolver, ServerInstance } from './shared.ts';
-import { outputSchemaWithText, ROUTED_CWD_DESCRIPTION, textPlusStructured } from './shared.ts';
-
-const ID_CARDINALITY_CAP = 32;
-
-export const DESCRIPTION = [
- '[Operates on registry data; no running OK server required] Return full per-entry details for the canonical components an agent picked from the inventory rendered in the `write_document` / `edit_document` tool descriptions.',
- '',
- 'Each entry carries: literal source-form `example` (copy-pasteable) + form-aware `params` (every prop, with `type` / `values?` / `required` / `defaultValue?` / `description`). Unmatched ids surface in `notFound` rather than failing the call.',
- '',
- '**Parameters:**',
- `- \`ids\` — Array of canonical ids picked from the write-tool inventory (e.g. \`["Callout", "Tabs"]\`). Max ${ID_CARDINALITY_CAP} ids per call. Case-sensitive — must match the inventory exactly (\`Callout\` not \`callout\`; \`img\` not \`Image\`).`,
- '- `cwd` (optional) — Project root (see `cwd` description below).',
-].join('\n');
-
-interface GetComponentsDeps {
- resolveCwd: (explicit?: string) => Promise<string>;
- config: ConfigOrResolver;
-}
-
-const InputSchema = {
- ids: z
- .array(z.string().min(1))
- .max(ID_CARDINALITY_CAP)
- .describe(
- `Array of canonical ids to fetch. Max ${ID_CARDINALITY_CAP} ids per call. Empty array returns an empty components list.`,
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
-} as const;
-
-const ParamSchema = z.object({
- name: z.string(),
- type: z.enum(['string', 'boolean', 'number', 'enum', 'reactnode']),
- values: z.array(z.string()).optional(),
- required: z.boolean(),
- defaultValue: z.union([z.string(), z.boolean(), z.number()]).optional(),
- description: z.string().optional(),
- omitOnDefault: z.literal(true).optional(),
- advanced: z.literal(true).optional(),
- language: z
- .enum(['mermaid', 'latex', 'html', 'json', 'yaml', 'javascript', 'markdown'])
- .optional(),
- accept: z.array(z.string()).optional(),
-});
-
-const ComponentEntrySchema = z.object({
- id: z.string(),
- displayName: z.string(),
- description: z.string(),
- kind: z.enum(['jsx-block', 'jsx-void']),
- example: z.string(),
- params: z.array(ParamSchema),
-});
-
-const OutputSchema = outputSchemaWithText({
- version: z.literal(1).describe('Schema version stamp — bump for breaking shape changes.'),
- components: z
- .array(ComponentEntrySchema)
- .describe('Full per-entry details for ids that matched.'),
- notFound: z.array(z.string()).describe('Ids that did not match any canonical descriptor.'),
-});
-
-export function register(server: ServerInstance, _deps: GetComponentsDeps): void {
- server.registerTool(
- 'get_components',
- {
- description: DESCRIPTION,
- inputSchema: InputSchema,
- outputSchema: OutputSchema,
- annotations: {
- readOnlyHint: true,
- idempotentHint: true,
- },
- },
- async (args: { ids: string[]; cwd?: string }) => {
- void args.cwd;
- const canonicals = getAgentCanonicalDescriptors();
- const byId = new Map(canonicals.map((d) => [d.name, d]));
- const components: ComponentEntryFull[] = [];
- const notFound: string[] = [];
- const seen = new Set<string>();
- for (const id of args.ids) {
- if (seen.has(id)) continue;
- seen.add(id);
- const descriptor = byId.get(id);
- if (descriptor === undefined) {
- notFound.push(id);
- continue;
- }
- components.push(projectFull(descriptor));
- }
- const payload = { version: 1 as const, components, notFound };
- return textPlusStructured(JSON.stringify(payload, null, 2), payload);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/get-conflict-content.test.ts b/packages/server/src/mcp/tools/get-conflict-content.test.ts
deleted file mode 100644
index 4c18cbda0..000000000
--- a/packages/server/src/mcp/tools/get-conflict-content.test.ts
+++ /dev/null
@@ -1,268 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './get-conflict-content.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;
- handler: (args: Record<string, unknown>) => Promise<ToolResult>;
-}
-
-function createCapturingServer() {
- const registrations: RegisteredTool[] = [];
- const server = {
- registerTool(name: string, _cfg: unknown, handler: RegisteredTool['handler']) {
- registrations.push({ name, 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-get-conflict-content-'));
-});
-
-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('get_conflict_content MCP tool', () => {
- test('always passes ?source=ytext and forwards `file` verbatim (with .md)', async () => {
- const { server, registrations } = createCapturingServer();
- const fetchCalls: Array<{ input: RequestInfo | URL }> = [];
-
- globalThis.fetch = (async (input) => {
- fetchCalls.push({ input });
- return new Response(
- JSON.stringify({
- ok: true,
- file: 'notes/sso.md',
- base: 'baseBytes',
- ours: 'oursBytes',
- theirs: 'theirsBytes',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- );
- }) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'notes/sso.md' });
-
- expect(fetchCalls).toHaveLength(1);
- const url = String(fetchCalls[0]?.input ?? '');
- expect(url).toBe(
- 'http://localhost:4321/api/sync/conflict-content?file=notes%2Fsso.md&source=ytext',
- );
- expect(result.isError).toBeUndefined();
- expect(result.structuredContent).toMatchObject({
- file: 'notes/sso.md',
- base: 'baseBytes',
- ours: 'oursBytes',
- theirs: 'theirsBytes',
- lifecycleStatus: 'conflict',
- });
- });
-
- test('propagates the kind discriminator into structured + text output (both-modified)', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- ok: true,
- file: 'a.md',
- base: 'b',
- ours: 'o',
- theirs: 't',
- kind: 'both-modified',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.structuredContent).toMatchObject({ kind: 'both-modified' });
- expect(result.content[0]?.text).toContain('kind: both-modified');
- });
-
- test('propagates kind: delete-modify (DU) so agents know to dispatch strategy: delete', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- ok: true,
- file: 'a.md',
- base: 'b',
- ours: '',
- theirs: 't',
- kind: 'delete-modify',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.structuredContent).toMatchObject({ kind: 'delete-modify' });
- expect(result.content[0]?.text).toContain('kind: delete-modify');
- });
-
- test('propagates kind: modify-delete (UD) so agents know to dispatch strategy: delete', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- ok: true,
- file: 'a.md',
- base: 'b',
- ours: 'o',
- theirs: '',
- kind: 'modify-delete',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.structuredContent).toMatchObject({ kind: 'modify-delete' });
- expect(result.content[0]?.text).toContain('kind: modify-delete');
- });
-
- test('falls back to kind: both-modified when server omits the field (stale-server safety)', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- ok: true,
- file: 'a.md',
- base: 'b',
- ours: 'o',
- theirs: 't',
- lifecycleStatus: 'conflict',
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.structuredContent).toMatchObject({ kind: 'both-modified' });
- });
-
- test('returns lifecycleStatus: null when the server omits it (e.g. doc unloaded)', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- ok: true,
- file: 'a.md',
- base: '',
- ours: 'fromGitIndex',
- theirs: '',
- lifecycleStatus: null,
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.isError).toBeUndefined();
- expect(result.structuredContent).toMatchObject({
- file: 'a.md',
- ours: 'fromGitIndex',
- lifecycleStatus: null,
- });
- });
-
- test('surfaces 404 (or other HTTP error) to the agent', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- type: 'urn:ok:error:no-conflict-tracked',
- title: 'No conflict is tracked for this path.',
- status: 404,
- }),
- { status: 404, headers: { 'Content-Type': 'application/problem+json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'missing.md' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('No conflict is tracked');
- });
-
- test('concatenates RFC 9457 detail into the agent error when the server provides one', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- type: 'urn:ok:error:internal-server-error',
- title: 'Failed to read conflict content.',
- status: 500,
- detail: 'simple-git: fatal: ambiguous argument',
- }),
- { status: 500, headers: { 'Content-Type': 'application/problem+json' } },
- )) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('Failed to read conflict content.');
- expect(result.content[0]?.text).toContain('simple-git: fatal: ambiguous argument');
- });
-
- 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, 'get_conflict_content');
- const result = await tool.handler({ file: 'a.md' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
- });
-});
diff --git a/packages/server/src/mcp/tools/get-conflict-content.ts b/packages/server/src/mcp/tools/get-conflict-content.ts
deleted file mode 100644
index 81545e83d..000000000
--- a/packages/server/src/mcp/tools/get-conflict-content.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-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';
-
-export const DESCRIPTION = [
- "[Requires: Hocuspocus server] Fetch the three merge stages (base / ours / theirs) for a doc currently in a merge-conflict state, plus the doc's lifecycle status and the conflict shape discriminator.",
- 'Returns 404 if no conflict is tracked for the path.',
- 'The `ours` field is sourced from the live Y.Text (showing any pre-conflict unflushed user edits) when the doc is loaded server-side; falls back to `git show :2:<file>` otherwise.',
- 'The `kind` field discriminates conflict shape: `both-modified` (both sides edited the file), `delete-modify` (DU — you deleted, they edited; stage 2 absent, `ours` empty), or `modify-delete` (UD — you edited, they deleted; stage 3 absent, `theirs` empty). Use it to pick the right `resolve_conflict` strategy: both-modified accepts `mine`/`theirs`/`content`; delete-modify accepts `delete` (keep deletion) or `theirs` (restore); modify-delete accepts `mine` (keep your version) or `delete` (accept their deletion).',
- '',
- '**Parameters:**',
- '- `file` — Relative-to-projectDir path WITH the `.md` extension (e.g. `notes/sso.md`). Mirrors the server-side wire contract.',
-].join('\n');
-
-interface GetConflictContentDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
-}
-
-const OutputSchema = outputSchemaWithText({
- file: z.string(),
- base: z.string(),
- ours: z.string(),
- theirs: z.string(),
- kind: z.enum(['both-modified', 'delete-modify', 'modify-delete']),
- lifecycleStatus: z.string().nullable(),
-});
-
-export function register(server: ServerInstance, deps: GetConflictContentDeps): void {
- server.registerTool(
- 'get_conflict_content',
- {
- description: DESCRIPTION,
- inputSchema: {
- file: z
- .string()
- .min(1)
- .describe(
- 'Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`). Server-side contract — do NOT strip the extension.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- outputSchema: OutputSchema,
- annotations: {
- readOnlyHint: true,
- idempotentHint: true,
- },
- },
- async (args: { 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);
-
- 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;
- const message = detail ? `${error} — ${detail}` : error;
- return textResult(`Error: ${message}`, 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 kind: 'both-modified' | 'delete-modify' | 'modify-delete' =
- rec.kind === 'delete-modify' || rec.kind === 'modify-delete' ? rec.kind : 'both-modified';
- const lifecycleStatus = typeof rec.lifecycleStatus === 'string' ? rec.lifecycleStatus : null;
- const structured = { file, base, ours, theirs, kind, lifecycleStatus };
- const lifecycleSuffix = lifecycleStatus ? ` (lifecycle: ${lifecycleStatus})` : '';
- const text = `Conflict stages for ${file} (kind: ${kind})${lifecycleSuffix}:\n--- base ---\n${base}\n--- ours ---\n${ours}\n--- theirs ---\n${theirs}`;
- return textPlusStructured(text, structured);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index ca7e328d2..e93e4e43a 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -34,7 +34,7 @@ function captureRegistration(cwd: string, config: Config = BASE_CONFIG): ToolHan
captured = handler;
},
tool() {
- throw new Error('legacy tool() should not be called by get_preview_url');
+ throw new Error('legacy tool() should not be called by preview_url');
},
} as unknown as ServerInstance;
register(server, {
@@ -45,12 +45,12 @@ function captureRegistration(cwd: string, config: Config = BASE_CONFIG): ToolHan
return captured;
}
-describe('get_preview_url tool — UI running', () => {
+describe('preview_url tool — UI running', () => {
test('with docName: composes baseUrl + the doc route', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const uiBase = bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
- const result = await handler({ docName: 'specs/foo/SPEC' });
+ const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBeUndefined();
expect(result.structuredContent?.running).toBe(true);
expect(result.structuredContent?.baseUrl).toBe(uiBase);
@@ -79,7 +79,7 @@ describe('get_preview_url tool — UI running', () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
- await handler({ docName: 'specs/foo/SPEC', armPaneTarget: true });
+ await handler({ document: 'specs/foo/SPEC', armPaneTarget: true });
expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/specs/foo/SPEC');
});
@@ -87,7 +87,7 @@ describe('get_preview_url tool — UI running', () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
- await handler({ docName: 'specs/foo/SPEC' });
+ await handler({ document: 'specs/foo/SPEC' });
expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
});
@@ -112,7 +112,7 @@ describe('get_preview_url tool — UI running', () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
- const result = await handler({ docName: 'specs/foo/SPEC', folder: 'specs/foo' });
+ const result = await handler({ document: 'specs/foo/SPEC', folder: 'specs/foo' });
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toContain('mutually exclusive');
expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
@@ -134,16 +134,16 @@ describe('get_preview_url tool — UI running', () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const uiBase = bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
- const result = await handler({ docName: 'notes/My Doc' });
+ const result = await handler({ document: 'notes/My Doc' });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/notes/My%20Doc`);
});
});
-describe('get_preview_url tool — no UI running', () => {
+describe('preview_url tool — no UI running', () => {
test('returns running:false + null url when no ui.lock is present', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const handler = captureRegistration(cwd);
- const result = await handler({ docName: 'specs/foo/SPEC' });
+ const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBeUndefined();
expect(result.structuredContent?.running).toBe(false);
expect(result.structuredContent?.url).toBeNull();
@@ -162,12 +162,12 @@ describe('get_preview_url tool — no UI running', () => {
});
});
-describe('get_preview_url tool — autoOpen field', () => {
+describe('preview_url tool — autoOpen field', () => {
test('echoes resolved autoOpen=false when the user has disabled it', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
bindTestUiLock(cwd);
const handler = captureRegistration(cwd, CONFIG_AUTOOPEN_OFF);
- const result = await handler({ docName: 'specs/foo/SPEC' });
+ const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBeUndefined();
expect(result.structuredContent?.running).toBe(true);
expect(result.structuredContent?.autoOpen).toBe(false);
@@ -193,7 +193,7 @@ describe('get_preview_url tool — autoOpen field', () => {
captured = handler;
},
tool() {
- throw new Error('legacy tool() should not be called by get_preview_url');
+ throw new Error('legacy tool() should not be called by preview_url');
},
} as unknown as ServerInstance;
register(server, {
@@ -203,16 +203,16 @@ describe('get_preview_url tool — autoOpen field', () => {
if (!captured) throw new Error('tool not registered');
const handler = captured as ToolHandler;
- const first = await handler({ docName: 'foo' });
+ const first = await handler({ document: 'foo' });
expect(first.structuredContent?.autoOpen).toBe(true);
currentAutoOpen = false;
- const second = await handler({ docName: 'foo' });
+ const second = await handler({ document: 'foo' });
expect(second.structuredContent?.autoOpen).toBe(false);
});
});
-describe('get_preview_url tool — error path', () => {
+describe('preview_url tool — error path', () => {
test('returns isError when resolveCwd rejects', async () => {
let captured: ToolHandler | undefined;
const server = {
@@ -220,7 +220,7 @@ describe('get_preview_url tool — error path', () => {
captured = handler;
},
tool() {
- throw new Error('legacy tool() should not be called by get_preview_url');
+ throw new Error('legacy tool() should not be called by preview_url');
},
} as unknown as ServerInstance;
register(server, {
@@ -230,7 +230,7 @@ describe('get_preview_url tool — error path', () => {
},
});
if (!captured) throw new Error('tool not registered');
- const result = await captured({ docName: 'specs/foo/SPEC' });
+ const result = await captured({ document: 'specs/foo/SPEC' });
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toContain('no roots configured');
});
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index a71594a47..159b66b03 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -22,12 +22,12 @@ export const DESCRIPTION = [
'',
'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.',
'',
- 'Returns `{ url, baseUrl, running: false }` and a recovery hint when no UI is running for the project (start one with `ok ui`).',
+ 'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` and a recovery hint when no UI is running for the project (start one with `ok ui`).',
'',
'**Parameters:**',
- '- `docName` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
- '- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `docName`.',
- '- `armPaneTarget` (optional) — When true with a `docName`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. This is the tool’s ONLY side effect; omit it and the call is read-only.',
+ '- `document` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
+ '- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
+ '- `armPaneTarget` (optional) — When true with a `document`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. This is the tool’s ONLY side effect; omit it and the call is read-only.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
].join('\n');
@@ -37,7 +37,7 @@ interface GetPreviewUrlDeps {
}
const InputSchema = {
- docName: z
+ document: z
.string()
.optional()
.describe(
@@ -48,13 +48,13 @@ const InputSchema = {
.min(1)
.optional()
.describe(
- 'Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `docName`.',
+ 'Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
),
armPaneTarget: z
.boolean()
.optional()
.describe(
- 'When true with a `docName` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open.',
+ 'When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open.',
),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
} as const;
@@ -64,7 +64,7 @@ const OutputSchema = outputSchemaWithText({
.string()
.nullable()
.describe(
- 'Browser-reachable URL — the UI base joined with the doc route when `docName` is given, else the UI root. `null` when no UI is running.',
+ 'Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running.',
),
baseUrl: z
.string()
@@ -85,7 +85,7 @@ const NO_UI_MESSAGE =
export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void {
server.registerTool(
- 'get_preview_url',
+ 'preview_url',
{
description: DESCRIPTION,
inputSchema: InputSchema,
@@ -95,14 +95,14 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
idempotentHint: true,
},
},
- async (args: { docName?: string; folder?: string; armPaneTarget?: boolean; cwd?: string }) => {
- if (args.docName && args.folder) {
+ async (args: { document?: string; folder?: string; armPaneTarget?: boolean; cwd?: string }) => {
+ if (args.document && args.folder) {
return {
isError: true,
content: [
{
type: 'text' as const,
- text: 'Error: docName and folder are mutually exclusive — pass exactly one.',
+ text: 'Error: document and folder are mutually exclusive — pass exactly one.',
},
],
};
@@ -119,8 +119,8 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
const { baseUrl } = resolveUiInfo(ctx);
const autoOpen = context.config.appearance.preview.autoOpen;
- const routeFragment = args.docName
- ? `#/${encodeDocName(args.docName)}`
+ const routeFragment = args.document
+ ? `#/${encodeDocName(args.document)}`
: args.folder
? `#/${encodeFolderRoute(args.folder)}`
: null;
@@ -133,7 +133,7 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
const armNote =
args.armPaneTarget && !routeFragment
- ? ' (note: armPaneTarget was set but no docName/folder was given, so nothing was armed)'
+ ? ' (note: armPaneTarget was set but no document/folder was given, so nothing was armed)'
: '';
if (baseUrl === null) {
diff --git a/packages/server/src/mcp/tools/get-history.test.ts b/packages/server/src/mcp/tools/history.test.ts
similarity index 74%
rename from packages/server/src/mcp/tools/get-history.test.ts
rename to packages/server/src/mcp/tools/history.test.ts
index 315c5c7f0..4d98ffea3 100644
--- a/packages/server/src/mcp/tools/get-history.test.ts
+++ b/packages/server/src/mcp/tools/history.test.ts
@@ -15,7 +15,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { type GetHistoryDeps, register } from './get-history.ts';
+import { type GetHistoryDeps, register } from './history.ts';
import type { ServerInstance } from './shared.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({});
@@ -27,7 +27,7 @@ interface ToolResult {
}
interface RegisteredTool {
- handler: (args: { docName: string }) => Promise<ToolResult>;
+ handler: (args: { document: string }) => Promise<ToolResult>;
}
function createFakeServer() {
@@ -55,7 +55,21 @@ beforeAll(() => {
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/api/history') {
- return Response.json({ ok: true, entries: [{ hash: 'abc', date: '2026-04-01' }] });
+ return Response.json({
+ ok: true,
+ entries: [
+ {
+ sha: 'abc',
+ timestamp: '2026-04-01T00:00:00Z',
+ author: 'Tim',
+ authorEmail: '[email protected]',
+ type: 'checkpoint',
+ message: 'init',
+ contributors: [],
+ checkpoint: null,
+ },
+ ],
+ });
}
return new Response('Not found', { status: 404 });
},
@@ -85,16 +99,16 @@ function makeDeps(): GetHistoryDeps {
};
}
-describe('get_history — previewUrl emission', () => {
+describe('history — previewUrl emission', () => {
test('emits route-only previewUrl + source alongside entries when resolver resolves', async () => {
bindTestUiLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps());
- const result = await getTool().handler({ docName: 'notes' });
+ const result = await getTool().handler({ document: 'notes' });
expect(result.structuredContent).toMatchObject({
- entries: [{ hash: 'abc', date: '2026-04-01' }],
+ entries: [{ version: 'abc', kind: 'checkpoint', author: 'Tim' }],
previewUrl: '/#/notes',
previewUrlSource: 'lock',
});
@@ -104,10 +118,10 @@ describe('get_history — previewUrl emission', () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps());
- const result = await getTool().handler({ docName: 'notes' });
+ const result = await getTool().handler({ document: 'notes' });
expect(result.structuredContent).toMatchObject({
- entries: [{ hash: 'abc', date: '2026-04-01' }],
+ entries: [{ version: 'abc', kind: 'checkpoint' }],
previewUrl: null,
});
});
diff --git a/packages/server/src/mcp/tools/get-history.ts b/packages/server/src/mcp/tools/history.ts
similarity index 52%
rename from packages/server/src/mcp/tools/get-history.ts
rename to packages/server/src/mcp/tools/history.ts
index 325760bc6..a102b25db 100644
--- a/packages/server/src/mcp/tools/get-history.ts
+++ b/packages/server/src/mcp/tools/history.ts
@@ -4,24 +4,50 @@ import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './sh
import {
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpGet,
+ looseObjectArray,
normalizeDocName,
+ outputSchemaWithText,
+ previewUrlOutputField,
+ previewUrlSourceField,
ROUTED_CWD_DESCRIPTION,
resolveProjectServerContext,
textPlusStructured,
textResult,
} from './shared.ts';
+const HISTORY_KINDS = ['checkpoint', 'wip', 'upstream'] as const;
+
+const HistoryEntryOutputSchema = z.object({
+ version: z
+ .string()
+ .describe(
+ '40-char commit SHA for this entry — pass to `restore_version({ document, version })`.',
+ ),
+ timestamp: z.string().describe('ISO timestamp of the entry.'),
+ author: z.string().describe('Author display name.'),
+ authorEmail: z.string().describe('Author email.'),
+ kind: z.enum(HISTORY_KINDS).describe('Entry kind: checkpoint / wip / upstream.'),
+ message: z.string().describe('Commit subject (the checkpoint summary, when one was set).'),
+ contributors: looseObjectArray.describe(
+ 'Per-contributor records parsed from the commit (writer id, name, docs, summaries).',
+ ),
+ checkpoint: z
+ .unknown()
+ .nullable()
+ .describe('Checkpoint metadata when this entry is a checkpoint, else null.'),
+});
+
export const DESCRIPTION = [
'[Requires: Hocuspocus server] List version history for a document.',
'Returns timeline entries from the shadow repo, sorted by timestamp descending.',
- 'Each entry includes a commit SHA that can be passed to `version({ action: "rollback" })`.',
+ 'Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.',
'',
'**Parameters:**',
- '- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.',
+ '- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.',
'- `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)',
- '- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',
+ '- `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',
].join('\n');
@@ -34,11 +60,11 @@ export interface GetHistoryDeps {
export function register(server: ServerInstance, deps: GetHistoryDeps): void {
server.registerTool(
- 'get_history',
+ 'history',
{
description: DESCRIPTION,
inputSchema: {
- docName: z.string().describe('Document name to query history for'),
+ document: z.string().describe('Document name to query history for'),
branch: z.string().optional().describe('Branch name (default: current branch)'),
limit: z
.number()
@@ -53,7 +79,10 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
.min(0)
.optional()
.describe('Number of entries to skip for pagination (default 0)'),
- type: z.enum(['checkpoint', 'upstream', 'wip']).optional().describe('Filter by entry type'),
+ kind: z
+ .enum(['checkpoint', 'upstream', 'wip'])
+ .optional()
+ .describe('Filter by entry type (`checkpoint` / `upstream` / `wip`).'),
author: z.string().optional().describe('Filter to entries by this author name or email'),
excludeAuthor: z
.string()
@@ -61,13 +90,29 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
.describe('Exclude entries by this author name or email'),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
+ outputSchema: outputSchemaWithText({
+ entries: z
+ .array(HistoryEntryOutputSchema)
+ .describe(
+ 'Timeline entries, newest first. Each carries a `version` for `restore_version`.',
+ ),
+ total: z.number().int().optional().describe('Total entries available (pre-pagination).'),
+ truncated: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether more entries exist beyond this returned page (the result was limit-capped).',
+ ),
+ previewUrl: previewUrlOutputField,
+ previewUrlSource: previewUrlSourceField,
+ }),
},
async (args: {
- docName: string;
+ document: string;
branch?: string;
limit?: number;
offset?: number;
- type?: string;
+ kind?: string;
author?: string;
excludeAuthor?: string;
cwd?: string;
@@ -82,7 +127,7 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
const { cwd, url } = context;
if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
- const normalized = normalizeDocName(args.docName);
+ const normalized = normalizeDocName(args.document);
if (!normalized.ok) return textResult(normalized.error, true);
const params = new URLSearchParams();
@@ -90,7 +135,7 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
if (args.branch) params.set('branch', args.branch);
if (args.limit != null) params.set('limit', String(args.limit));
if (args.offset != null) params.set('offset', String(args.offset));
- if (args.type) params.set('type', args.type);
+ if (args.kind) params.set('type', args.kind);
if (args.author) params.set('author', args.author);
if (args.excludeAuthor) params.set('excludeAuthor', args.excludeAuthor);
@@ -98,6 +143,25 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
if (!result.ok) return textResult(`Error: ${result.error}`, true);
const { ok: _ok, ...data } = result;
+ const rawEntries = Array.isArray((data as { entries?: unknown }).entries)
+ ? (data as { entries: unknown[] }).entries
+ : [];
+ const entries = rawEntries.map((raw) => {
+ const e = raw as Record<string, unknown>;
+ return {
+ version: e.sha,
+ timestamp: e.timestamp,
+ author: e.author,
+ authorEmail: e.authorEmail,
+ kind: e.type,
+ message: e.message,
+ contributors: e.contributors,
+ checkpoint: e.checkpoint ?? null,
+ };
+ });
+ const total = (data as { total?: unknown }).total;
+ const hasMore = (data as { hasMore?: unknown }).hasMore;
+
const preview = await resolvePreviewUrlForTool(
normalized.docName,
{
@@ -106,8 +170,13 @@ export function register(server: ServerInstance, deps: GetHistoryDeps): void {
},
cwd,
);
- return textPlusStructured(JSON.stringify(data, null, 2), {
- ...data,
+ const projected = {
+ entries,
+ ...(typeof total === 'number' ? { total } : {}),
+ ...(typeof hasMore === 'boolean' ? { truncated: hasMore } : {}),
+ };
+ return textPlusStructured(JSON.stringify(projected, null, 2), {
+ ...projected,
previewUrl: preview?.url ?? null,
...(preview ? { previewUrlSource: preview.source } : {}),
});
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index 5df4155c9..b0c02b73a 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -2,97 +2,58 @@ import type { AgentIdentity } from '../agent-identity.ts';
import { getCurrentMcpLogger, type McpLogger } from '../logger.ts';
import { createLoggedServer } from '../tool-logging.ts';
import {
- DESCRIPTION as CONSOLIDATE_DESCRIPTION,
- register as registerConsolidate,
-} from './consolidate.ts';
+ DESCRIPTION as CHECKPOINT_DESCRIPTION,
+ register as registerCheckpoint,
+} from './checkpoint.ts';
+import { DESCRIPTION as CONFIG_DESCRIPTION, register as registerConfig } from './config.ts';
import {
- DESCRIPTION as DELETE_DOCUMENT_DESCRIPTION,
- register as registerDeleteDocument,
-} from './delete-document.ts';
-import { DESCRIPTION as DISCOVER_DESCRIPTION, register as registerDiscover } from './discover.ts';
-import {
- DESCRIPTION as EDIT_DOCUMENT_DESCRIPTION,
- register as registerEditDocument,
-} from './edit-document.ts';
-import {
- DESCRIPTION as EDIT_FRONTMATTER_DESCRIPTION,
- register as registerEditFrontmatter,
-} from './edit-frontmatter.ts';
+ DESCRIPTION as CONFLICTS_DESCRIPTION,
+ register as registerConflicts,
+} from './conflicts.ts';
+import { DESCRIPTION as DELETE_DESCRIPTION, register as registerDelete } from './delete.ts';
+import { DESCRIPTION as EDIT_DESCRIPTION, register as registerEdit } from './edit.ts';
import { DESCRIPTION as EXEC_DESCRIPTION, register as registerExec } from './exec.ts';
import {
- DESCRIPTION as FOLDER_CONFIG_DESCRIPTION,
- register as registerFolderConfig,
-} from './folder-config.ts';
-import {
- DESCRIPTION as GET_AUTHORING_PALETTE_DESCRIPTION,
- register as registerGetAuthoringPalette,
-} from './get-authoring-palette.ts';
-import {
- DESCRIPTION as GET_COMPONENTS_DESCRIPTION,
- register as registerGetComponents,
-} from './get-components.ts';
-import {
- DESCRIPTION as GET_CONFIG_DESCRIPTION,
- register as registerGetConfig,
-} from './get-config.ts';
-import {
- DESCRIPTION as GET_CONFLICT_CONTENT_DESCRIPTION,
- register as registerGetConflictContent,
-} from './get-conflict-content.ts';
-import {
- DESCRIPTION as GET_HISTORY_DESCRIPTION,
- register as registerGetHistory,
-} from './get-history.ts';
-import {
- DESCRIPTION as GET_PREVIEW_URL_DESCRIPTION,
- register as registerGetPreviewUrl,
+ DESCRIPTION as PREVIEW_URL_DESCRIPTION,
+ register as registerPreviewUrl,
} from './get-preview-url.ts';
-import { DESCRIPTION as INGEST_DESCRIPTION, register as registerIngest } from './ingest.ts';
+import { DESCRIPTION as HISTORY_DESCRIPTION, register as registerHistory } from './history.ts';
import { DESCRIPTION as LINKS_DESCRIPTION, register as registerLinks } from './links.ts';
-import {
- DESCRIPTION as LIST_CONFLICTS_DESCRIPTION,
- register as registerListConflicts,
-} from './list-conflicts.ts';
-import { DESCRIPTION as RENAME_DESCRIPTION, register as registerRename } from './rename.ts';
-import { DESCRIPTION as RESEARCH_DESCRIPTION, register as registerResearch } from './research.ts';
+import { DESCRIPTION as MOVE_DESCRIPTION, register as registerMove } from './move.ts';
+import { DESCRIPTION as PALETTE_DESCRIPTION, register as registerPalette } from './palette.ts';
import {
DESCRIPTION as RESOLVE_CONFLICT_DESCRIPTION,
register as registerResolveConflict,
} from './resolve-conflict.ts';
+import {
+ DESCRIPTION as RESTORE_VERSION_DESCRIPTION,
+ register as registerRestoreVersion,
+} from './restore-version.ts';
import { register as registerSearch, DESCRIPTION as SEARCH_DESCRIPTION } from './search.ts';
import {
register as registerShareLink,
DESCRIPTION as SHARE_LINK_DESCRIPTION,
} from './share-link.ts';
import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import { register as registerVersion, DESCRIPTION as VERSION_DESCRIPTION } from './version.ts';
-import {
- register as registerWriteDocument,
- DESCRIPTION as WRITE_DOCUMENT_DESCRIPTION,
-} from './write-document.ts';
+import { register as registerWorkflow, DESCRIPTION as WORKFLOW_DESCRIPTION } from './workflow.ts';
+import { register as registerWrite, DESCRIPTION as WRITE_DESCRIPTION } from './write.ts';
const _TOOL_DESCRIPTIONS = {
exec: EXEC_DESCRIPTION,
- ingest: INGEST_DESCRIPTION,
- research: RESEARCH_DESCRIPTION,
- consolidate: CONSOLIDATE_DESCRIPTION,
- discover: DISCOVER_DESCRIPTION,
- rename: RENAME_DESCRIPTION,
+ workflow: WORKFLOW_DESCRIPTION,
+ move: MOVE_DESCRIPTION,
search: SEARCH_DESCRIPTION,
links: LINKS_DESCRIPTION,
- write_document: WRITE_DOCUMENT_DESCRIPTION,
- edit_document: EDIT_DOCUMENT_DESCRIPTION,
- edit_frontmatter: EDIT_FRONTMATTER_DESCRIPTION,
- delete_document: DELETE_DOCUMENT_DESCRIPTION,
- get_history: GET_HISTORY_DESCRIPTION,
- version: VERSION_DESCRIPTION,
- get_components: GET_COMPONENTS_DESCRIPTION,
- get_authoring_palette: GET_AUTHORING_PALETTE_DESCRIPTION,
- get_config: GET_CONFIG_DESCRIPTION,
- get_preview_url: GET_PREVIEW_URL_DESCRIPTION,
- folder_config: FOLDER_CONFIG_DESCRIPTION,
- list_conflicts: LIST_CONFLICTS_DESCRIPTION,
- get_conflict_content: GET_CONFLICT_CONTENT_DESCRIPTION,
+ write: WRITE_DESCRIPTION,
+ edit: EDIT_DESCRIPTION,
+ delete: DELETE_DESCRIPTION,
+ history: HISTORY_DESCRIPTION,
+ checkpoint: CHECKPOINT_DESCRIPTION,
+ restore_version: RESTORE_VERSION_DESCRIPTION,
+ palette: PALETTE_DESCRIPTION,
+ config: CONFIG_DESCRIPTION,
+ preview_url: PREVIEW_URL_DESCRIPTION,
+ conflicts: CONFLICTS_DESCRIPTION,
resolve_conflict: RESOLVE_CONFLICT_DESCRIPTION,
share_link: SHARE_LINK_DESCRIPTION,
} as const;
@@ -138,14 +99,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
config: opts.config,
});
- registerIngest(registrationServer, { config: opts.config, resolveCwd: named('ingest') });
- registerResearch(registrationServer, { config: opts.config, resolveCwd: named('research') });
- registerConsolidate(registrationServer, {
- config: opts.config,
- resolveCwd: named('consolidate'),
- });
-
- registerDiscover(registrationServer, { config: opts.config, resolveCwd: named('discover') });
+ registerWorkflow(registrationServer, { config: opts.config, resolveCwd: named('workflow') });
registerSearch(registrationServer, {
resolveCwd: named('search'),
@@ -158,78 +112,64 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
resolveCwd: named('links'),
});
- registerWriteDocument(registrationServer, {
+ registerWrite(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('write_document'),
+ resolveCwd: named('write'),
identityRef: opts.identityRef,
});
- registerEditDocument(registrationServer, {
+ registerEdit(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('edit_document'),
+ resolveCwd: named('edit'),
identityRef: opts.identityRef,
});
- registerDeleteDocument(registrationServer, {
+ registerDelete(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('delete_document'),
+ resolveCwd: named('delete'),
identityRef: opts.identityRef,
});
- registerEditFrontmatter(registrationServer, {
+ registerMove(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('edit_frontmatter'),
+ resolveCwd: named('move'),
identityRef: opts.identityRef,
});
- registerRename(registrationServer, {
+ registerHistory(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('rename'),
- identityRef: opts.identityRef,
+ resolveCwd: named('history'),
});
- registerGetHistory(registrationServer, {
+ registerCheckpoint(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('get_history'),
+ resolveCwd: named('checkpoint'),
+ identityRef: opts.identityRef,
});
- registerVersion(registrationServer, {
+ registerRestoreVersion(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('version'),
+ resolveCwd: named('restore_version'),
identityRef: opts.identityRef,
});
- registerGetComponents(registrationServer, {
- resolveCwd: named('get_components'),
- config: opts.config,
- });
- registerGetAuthoringPalette(registrationServer, {
- resolveCwd: named('get_authoring_palette'),
+ registerPalette(registrationServer, {
+ resolveCwd: named('palette'),
config: opts.config,
});
- registerGetConfig(registrationServer, {
+ registerConfig(registrationServer, {
config: opts.config,
- resolveCwd: named('get_config'),
+ resolveCwd: named('config'),
});
- registerGetPreviewUrl(registrationServer, {
- config: opts.config,
- resolveCwd: named('get_preview_url'),
- });
- registerFolderConfig(registrationServer, {
- config: opts.config,
- resolveCwd: named('folder_config'),
- });
-
- registerListConflicts(registrationServer, {
- serverUrl: opts.serverUrl,
+ registerPreviewUrl(registrationServer, {
config: opts.config,
- resolveCwd: named('list_conflicts'),
+ resolveCwd: named('preview_url'),
});
- registerGetConflictContent(registrationServer, {
+ registerConflicts(registrationServer, {
serverUrl: opts.serverUrl,
config: opts.config,
- resolveCwd: named('get_conflict_content'),
+ resolveCwd: named('conflicts'),
});
registerResolveConflict(registrationServer, {
serverUrl: opts.serverUrl,
diff --git a/packages/server/src/mcp/tools/ingest.ts b/packages/server/src/mcp/tools/ingest-body.ts
similarity index 93%
rename from packages/server/src/mcp/tools/ingest.ts
rename to packages/server/src/mcp/tools/ingest-body.ts
index 08bd51ac2..b2e32201e 100644
--- a/packages/server/src/mcp/tools/ingest.ts
+++ b/packages/server/src/mcp/tools/ingest-body.ts
@@ -1,9 +1,6 @@
import { OK_DIR } from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import type { ServerInstance, WorkflowToolDeps } from './shared.ts';
-import { buildWorkflowHandler, ROUTED_CWD_DESCRIPTION } from './shared.ts';
-function buildBody(source: string, contentDir: string): string {
+export function buildIngestBody(source: string, contentDir: string): string {
return `Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
**Bias toward binary preservation.** When the source is a binary file (PDF, image, audio, video, Office doc, archive, dataset), preserve the raw bytes — do NOT settle for a text scrape. OK already ships a complete asset-embed surface (\`![[file.ext]]\` wiki-embed, file-watcher pickup, sha256 dedup, blocked-extension enforcement); this tool's job is to bridge \`ingest\` to it via your shell tool.
@@ -146,7 +143,7 @@ tags:
The body is just the wiki-embed reference. For images, video, and audio, the embed renders inline. **For PDFs and other opaque file-attachment types (docx, xlsx, zip, etc.), the \`![[file.ext]]\` form renders as a Notion-style File row that click-dispatches to the appropriate viewer** — the pdfjs canvas viewer is opt-in via the explicit \`<Pdf src="./<slug>.pdf" />\` JSX form, NOT the wiki-embed default. If the user wants the inline canvas viewer for this specific PDF, they can post-edit the wrapper body to replace \`![[<slug>.pdf]]\` with \`<Pdf src="./<slug>.pdf" />\`.
-Write via \`write_document\` (NOT native \`Write\` — the CRDT path is mandatory for in-scope markdown).
+Write 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)
@@ -229,7 +226,7 @@ After preservation, briefly surface back to the user what the source actually co
If the source is directly relevant to an existing article or research doc, update that doc to link the new raw source. A preserved source that no doc points at is an island. Limit this to 1–3 high-signal neighbors — don't touch everything tangentially related.
-- Follow the \`write_document\` / \`edit_document\` contract from the skill (preview-before-edit).
+- Follow the \`write\` / \`edit\` contract from the skill (preview-before-edit).
- For binary wrappers, prefer linking to the wrapper (the markdown doc), not the binary directly: \`[Source title](./external-sources/<slug>.md)\`. The wrapper is the closed-loop citation target; the binary is the embedded asset within it.
- Do NOT mass-update every neighbor. Karpathy's pattern rewards focused cross-linking; noisy neighbor-pings degrade the signal.
@@ -244,23 +241,3 @@ If the source is directly relevant to an existing article or research doc, updat
- **No executable / scripted-document auto-fetch** — hard-blocked at Step 1b STOP gate 1 (write-path only). User runs \`curl\` manually outside the agent if they need to archive such a file.
`;
}
-
-export const DESCRIPTION = [
- 'Returns a step-by-step plan to capture an external source (URL or local file) into the knowledge base as raw, verbatim reference material — no analysis. Does NOT fetch or write — you execute the plan.',
- 'Biases toward preserving raw binary files (PDF, image, audio, video) via the shell + `![[file.ext]]` embed, falling back to text extraction on shell-less hosts. The KB is closed-loop: cite the captured local doc, never a bare URL.',
- 'Use when a source needs preserving before analysis — including URLs you fetched yourself to ground a KB claim.',
-].join('\n');
-
-export function register(server: ServerInstance, deps: WorkflowToolDeps): void {
- server.registerTool(
- 'ingest',
- {
- description: DESCRIPTION,
- inputSchema: {
- source: z.string().describe('URL, file path, or identifier of the source to ingest'),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- buildWorkflowHandler('ingest', deps, 'source', buildBody),
- );
-}
diff --git a/packages/server/src/mcp/tools/ingest.test.ts b/packages/server/src/mcp/tools/ingest.test.ts
deleted file mode 100644
index 6ce891fd7..000000000
--- a/packages/server/src/mcp/tools/ingest.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { describe as _bunDescribe, expect, test } from 'bun:test';
-
-const describeCiSkippable = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-const describe = _bunDescribe;
-
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './ingest.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
-}
-
-function captureTool() {
- let captured: ((args: { source: string; cwd?: string }) => Promise<ToolResult>) | undefined;
- const server = {
- registerTool(
- _name: string,
- _config: unknown,
- handler: (args: { source: string; cwd?: string }) => Promise<ToolResult>,
- ) {
- captured = handler;
- },
- } as unknown as ServerInstance;
- return {
- server,
- async call(source: string) {
- if (!captured) throw new Error('Tool was not registered');
- return await captured({ source });
- },
- };
-}
-
-describeCiSkippable('ingest — previewUrl emission', () => {
- test('returns structuredContent with previewUrl: null (workflow primer)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/article');
- expect(result.structuredContent).toMatchObject({ previewUrl: null });
- expect(result.content[0]?.text).toContain('https://example.com/article');
- });
-});
-
-describe('ingest — binary preservation plan body (SPEC 2026-05-19)', () => {
- test('plan mentions binary-handling tokens (external-sources/, ![[, sha256, --max-filesize)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://arxiv.org/pdf/2401.12345v1.pdf');
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('external-sources/');
- expect(body).toContain('![[');
- expect(body).toContain('sha256');
- expect(body).toContain('--max-filesize');
- });
-
- test('plan names streaming-host STOP examples and the yt-dlp pointer', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/source');
- const body = result.content[0]?.text ?? '';
- const namesAtLeastOneStreamingHost = [
- 'youtube.com',
- 'youtu.be',
- 'vimeo.com',
- 'twitch.tv',
- 'spotify.com',
- ].some((host) => body.includes(host));
- expect(namesAtLeastOneStreamingHost).toBe(true);
- expect(body).toContain('yt-dlp');
- });
-
- test('plan hard-blocks executable extensions (references EXECUTABLE_BLOCKLIST_EXTENSIONS)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/source');
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('EXECUTABLE_BLOCKLIST_EXTENSIONS');
- const namesAtLeastOneBlockedExtension = ['.exe', '.dmg', '.sh', '.html', '.webloc'].some(
- (ext) => body.includes(ext),
- );
- expect(namesAtLeastOneBlockedExtension).toBe(true);
- });
-
- test('plan documents shell-less fallback with preservation flag and admonition', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/source');
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('preservation');
- expect(body).toContain('text-only');
- expect(body).toContain('Binary not preserved');
- });
-
- test('plan includes curl --proto scheme restriction (SSRF defense)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/source');
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('--proto =http,=https');
- expect(body).toContain('--proto-redir =http,=https');
- });
-
- test('plan documents slug shape constraint (path traversal defense)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('https://example.com/source');
- const body = result.content[0]?.text ?? '';
- expect(body).toContain('^[a-z0-9]');
- });
-});
diff --git a/packages/server/src/mcp/tools/links.test.ts b/packages/server/src/mcp/tools/links.test.ts
index b7ffb9fa2..b6a4e49ed 100644
--- a/packages/server/src/mcp/tools/links.test.ts
+++ b/packages/server/src/mcp/tools/links.test.ts
@@ -30,8 +30,8 @@ type LinkKind = 'backlinks' | 'forward' | 'dead' | 'orphans' | 'hubs' | 'suggest
interface LinksHandlerArgs {
kind: LinkKind | LinkKind[];
- docName?: string;
- sourceDocNames?: string[];
+ document?: string;
+ sourceDocuments?: string[];
mode?: 'incoming' | 'outgoing' | 'both';
limit?: number;
}
@@ -184,7 +184,7 @@ describe('links — registration + DESCRIPTION', () => {
expect(DESCRIPTION).toContain('`orphans`');
expect(DESCRIPTION).toContain('`hubs`');
expect(DESCRIPTION).toContain('`suggest`');
- expect(DESCRIPTION).toContain('sourceDocNames');
+ expect(DESCRIPTION).toContain('sourceDocuments');
expect(DESCRIPTION).toContain('mode');
expect(DESCRIPTION).toContain('limit');
});
@@ -203,7 +203,7 @@ describe('links — kind=backlinks', () => {
bindTestUiLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'backlinks', docName: 'target.md' });
+ const result = await getTool().handler({ kind: 'backlinks', document: 'target.md' });
expect(seenRequests).toContain('/api/backlinks?docName=target');
const s = result.structuredContent as {
backlinks: Array<{ source: string; previewUrl: string; previewUrlSource: string }>;
@@ -221,13 +221,13 @@ describe('links — kind=backlinks', () => {
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'backlinks' });
expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('kind=backlinks requires `docName`');
+ expect(result.content[0]?.text).toContain('kind=backlinks requires `document`');
});
test('previewUrl null when no UI lock is present', async () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'backlinks', docName: 'target' });
+ const result = await getTool().handler({ kind: 'backlinks', document: 'target' });
const s = result.structuredContent as {
backlinks: Array<{ previewUrl: string | null }>;
ui?: unknown;
@@ -242,7 +242,7 @@ describe('links — kind=forward', () => {
bindTestUiLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'forward', docName: 'source' });
+ const result = await getTool().handler({ kind: 'forward', document: 'source' });
const s = result.structuredContent as {
forwardLinks: Array<{
kind: string;
@@ -264,7 +264,7 @@ describe('links — kind=forward', () => {
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'forward' });
expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('kind=forward requires `docName`');
+ expect(result.content[0]?.text).toContain('kind=forward requires `document`');
});
});
@@ -274,14 +274,14 @@ describe('links — kind=dead', () => {
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({
kind: 'dead',
- sourceDocNames: ['alpha.md', 'beta'],
+ sourceDocuments: ['alpha.md', 'beta'],
});
expect(seenRequests).toContain('/api/dead-links?sourceDocName=alpha&sourceDocName=beta');
expect(result.content[0]?.text).toContain('missing-target');
expect(result.structuredContent).toBeDefined();
});
- test('hits /api/dead-links with no query when sourceDocNames is absent', async () => {
+ test('hits /api/dead-links with no query when sourceDocuments is absent', async () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
await getTool().handler({ kind: 'dead' });
@@ -364,7 +364,7 @@ describe('links — kind=suggest', () => {
test('normalizes trailing markdown extensions and returns the suggest payload', async () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'suggest', docName: 'project-alpha.md' });
+ const result = await getTool().handler({ kind: 'suggest', document: 'project-alpha.md' });
expect(result.content[0]?.text).toContain('"docName": "project-alpha"');
const expectedBody = {
target: { docName: 'project-alpha', title: 'Project Alpha', aliases: ['PA'] },
@@ -386,7 +386,7 @@ describe('links — kind=suggest', () => {
bindTestUiLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'suggest', docName: 'project-alpha' });
+ const result = await getTool().handler({ kind: 'suggest', document: 'project-alpha' });
expect(result.structuredContent).toMatchObject({
suggest: {
previewUrl: '/#/project-alpha',
@@ -398,7 +398,7 @@ describe('links — kind=suggest', () => {
test('propagates HTTP endpoint errors to the caller', async () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ kind: 'suggest', docName: 'missing-page' });
+ const result = await getTool().handler({ kind: 'suggest', document: 'missing-page' });
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toBe('Error: Page not found');
});
@@ -408,7 +408,7 @@ describe('links — kind=suggest', () => {
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'suggest' });
expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('kind=suggest requires `docName`');
+ expect(result.content[0]?.text).toContain('kind=suggest requires `document`');
});
});
@@ -438,7 +438,7 @@ describe('links — multi-kind (array)', () => {
errors: Record<string, string>;
};
expect(s.deadLinks).toHaveLength(1);
- expect(s.errors?.backlinks).toContain('requires `docName`');
+ expect(s.errors?.backlinks).toContain('requires `document`');
});
test('a single-element array behaves like the scalar form', async () => {
diff --git a/packages/server/src/mcp/tools/links.ts b/packages/server/src/mcp/tools/links.ts
index e52342203..78d7c08e3 100644
--- a/packages/server/src/mcp/tools/links.ts
+++ b/packages/server/src/mcp/tools/links.ts
@@ -5,7 +5,9 @@ import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './sh
import {
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpGet,
+ looseObjectArray,
normalizeDocName,
+ outputSchemaWithText,
ROUTED_CWD_DESCRIPTION,
resolveProjectServerContext,
textPlusStructured,
@@ -18,8 +20,8 @@ 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 `docName`. `suggest` finds prose mentions of the page not yet wrapped in link syntax (each mention `offset` works with `edit_document`).',
- '- `dead` — missing internal link targets corpus-wide; optional `sourceDocNames` filter (OR semantics).',
+ '- `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).',
'- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.',
'- `hubs` — most-linked pages; optional `limit` (default 20).',
].join('\n');
@@ -58,8 +60,8 @@ export interface LinksDeps extends PreviewUrlDeps {
interface LinksArgs {
kind: LinkKind | LinkKind[];
- docName?: string;
- sourceDocNames?: string[];
+ document?: string;
+ sourceDocuments?: string[];
mode?: OrphanMode;
limit?: number;
cwd?: string;
@@ -80,11 +82,13 @@ export function register(server: ServerInstance, deps: LinksDeps): void {
.describe(
'Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).',
),
- docName: z
+ document: z
.string()
.optional()
- .describe('Target page docName. Required for kind=backlinks|forward|suggest.'),
- sourceDocNames: z
+ .describe(
+ 'Target page (path, extension-less). Required for kind=backlinks|forward|suggest.',
+ ),
+ sourceDocuments: z
.array(z.string())
.optional()
.describe(
@@ -98,10 +102,35 @@ export function register(server: ServerInstance, deps: LinksDeps): void {
.number()
.int()
.positive()
+ .max(100)
.optional()
- .describe('Maximum number of hubs to return. Used by kind=hubs.'),
+ .describe('Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.'),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
},
+ outputSchema: outputSchemaWithText({
+ backlinks: looseObjectArray
+ .optional()
+ .describe('kind=backlinks: pages that link TO the target.'),
+ forwardLinks: looseObjectArray
+ .optional()
+ .describe('kind=forward: links FROM the target (doc + external).'),
+ deadLinks: looseObjectArray
+ .optional()
+ .describe('kind=dead: internal links whose target does not exist.'),
+ orphans: looseObjectArray.optional().describe('kind=orphans: disconnected pages.'),
+ hubs: looseObjectArray.optional().describe('kind=hubs: the most-linked pages.'),
+ suggest: z
+ .record(z.string(), z.unknown())
+ .optional()
+ .describe(
+ 'kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`).',
+ ),
+ errors: z
+ .record(z.string(), z.string())
+ .optional()
+ .describe('Per-kind failures on a multi-kind call: `{ kind: message }`.'),
+ cwd: z.string().describe('Absolute directory the read ran against.'),
+ }),
},
async (args: LinksArgs) => {
const context = await resolveProjectServerContext(
@@ -176,8 +205,8 @@ async function runBacklinks(
url: string,
resolve: ListResolve,
): Promise<KindOutcome> {
- if (!args.docName) return { ok: false, error: 'kind=backlinks requires `docName`.' };
- const normalized = normalizeDocName(args.docName);
+ if (!args.document) return { ok: false, error: 'kind=backlinks requires `document`.' };
+ const normalized = normalizeDocName(args.document);
if (!normalized.ok) return { ok: false, error: normalized.error };
const result = await httpGet(
url,
@@ -203,8 +232,8 @@ async function runForwardLinks(
url: string,
resolve: ListResolve,
): Promise<KindOutcome> {
- if (!args.docName) return { ok: false, error: 'kind=forward requires `docName`.' };
- const normalized = normalizeDocName(args.docName);
+ if (!args.document) return { ok: false, error: 'kind=forward requires `document`.' };
+ const normalized = normalizeDocName(args.document);
if (!normalized.ok) return { ok: false, error: normalized.error };
const result = await httpGet(
url,
@@ -231,7 +260,7 @@ async function runDeadLinks(
resolve: ListResolve,
): Promise<KindOutcome> {
const params = new URLSearchParams();
- for (const sourceDocName of args.sourceDocNames ?? []) {
+ for (const sourceDocName of args.sourceDocuments ?? []) {
const normalized = normalizeDocName(sourceDocName);
if (!normalized.ok) return { ok: false, error: normalized.error };
params.append('sourceDocName', normalized.docName);
@@ -309,8 +338,8 @@ async function runSuggest(
cwd: string,
deps: LinksDeps,
): Promise<KindOutcome> {
- if (!args.docName) return { ok: false, error: 'kind=suggest requires `docName`.' };
- const normalized = normalizeDocName(args.docName);
+ if (!args.document) return { ok: false, error: 'kind=suggest requires `document`.' };
+ const normalized = normalizeDocName(args.document);
if (!normalized.ok) return { ok: false, error: normalized.error };
const result = await httpGet(
url,
diff --git a/packages/server/src/mcp/tools/list-conflicts.test.ts b/packages/server/src/mcp/tools/list-conflicts.test.ts
deleted file mode 100644
index ca944790f..000000000
--- a/packages/server/src/mcp/tools/list-conflicts.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './list-conflicts.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;
- handler: (args: Record<string, unknown>) => Promise<ToolResult>;
-}
-
-function createCapturingServer() {
- const registrations: RegisteredTool[] = [];
- const server = {
- registerTool(name: string, _cfg: unknown, handler: RegisteredTool['handler']) {
- registrations.push({ name, 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-list-conflicts-'));
-});
-
-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('list_conflicts MCP tool', () => {
- test('returns empty conflicts array when none are tracked', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: true, conflicts: [] }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'list_conflicts');
- const result = await tool.handler({});
-
- expect(result.isError).toBeUndefined();
- expect(result.structuredContent).toMatchObject({ conflicts: [] });
- expect(result.content[0]?.text).toContain('No conflicts tracked');
- });
-
- test('returns populated conflicts with full entry shape', async () => {
- const { server, registrations } = createCapturingServer();
- const seeded = [
- {
- file: 'notes/alpha.md',
- detectedAt: '2026-05-19T10:00:00.000Z',
- oursSha: 'aaa111',
- theirsSha: 'bbb222',
- baseSha: 'ccc333',
- },
- {
- file: 'docs/beta.md',
- detectedAt: '2026-05-19T11:30:00.000Z',
- },
- ];
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: true, conflicts: seeded }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'list_conflicts');
- const result = await tool.handler({});
-
- expect(result.isError).toBeUndefined();
- const sc = result.structuredContent as { conflicts: Array<Record<string, unknown>> };
- expect(sc.conflicts).toHaveLength(2);
- expect(sc.conflicts[0]).toMatchObject({
- file: 'notes/alpha.md',
- oursSha: 'aaa111',
- theirsSha: 'bbb222',
- baseSha: 'ccc333',
- });
- expect(sc.conflicts[1]).toMatchObject({
- file: 'docs/beta.md',
- });
- expect(result.content[0]?.text).toContain('notes/alpha.md');
- expect(result.content[0]?.text).toContain('docs/beta.md');
- });
-
- test('surfaces HTTP error to the agent', async () => {
- const { server, registrations } = createCapturingServer();
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ ok: false, error: 'Sync engine not active.' }), {
- status: 503,
- headers: { 'Content-Type': 'application/json' },
- })) as typeof fetch;
-
- register(server, makeDeps('http://localhost:4321'));
- const tool = getTool(registrations, 'list_conflicts');
- const result = await tool.handler({});
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('Sync engine not active');
- });
-
- 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, 'list_conflicts');
- const result = await tool.handler({});
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
- });
-});
diff --git a/packages/server/src/mcp/tools/list-conflicts.ts b/packages/server/src/mcp/tools/list-conflicts.ts
deleted file mode 100644
index 024f94c88..000000000
--- a/packages/server/src/mcp/tools/list-conflicts.ts
+++ /dev/null
@@ -1,78 +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';
-
-export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Enumerate every document currently tracked as in a merge-conflict state.',
- 'Returns one entry per file (relative-path, detection timestamp, optional git SHAs). When no conflicts are tracked, returns `conflicts: []`.',
- '',
- 'Use as the entry point to the conflict-resolution flow: `list_conflicts` to discover, `get_conflict_content` to inspect stages, `resolve_conflict` to write a chosen version.',
-].join('\n');
-
-interface ListConflictsDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
-}
-
-const OutputSchema = outputSchemaWithText({
- conflicts: z.array(ConflictEntrySchema),
-});
-
-export function register(server: ServerInstance, deps: ListConflictsDeps): void {
- server.registerTool(
- 'list_conflicts',
- {
- description: DESCRIPTION,
- inputSchema: {
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- outputSchema: OutputSchema,
- annotations: {
- readOnlyHint: true,
- idempotentHint: true,
- },
- },
- async (args: { 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 result = await httpGet(url, '/api/sync/conflicts');
- if (!result.ok) {
- const error = result.error as string;
- return textPlusStructured(`Error: ${error}`, { conflicts: [] }, 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 file =
- row && typeof row === 'object' && 'file' in row
- ? String((row as Record<string, unknown>).file ?? '')
- : '';
- return `- ${file}`;
- })
- .join('\n')}`;
- return textPlusStructured(text, { conflicts });
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.ts
new file mode 100644
index 000000000..f73e95c8f
--- /dev/null
+++ b/packages/server/src/mcp/tools/move.ts
@@ -0,0 +1,301 @@
+import { existsSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { z } from 'zod';
+import type { AgentIdentity } from '../agent-identity.ts';
+import { resolveWithinRoot } from './path-safety.ts';
+import { type PreviewUrlSource, resolvePreviewUrlForTool } from './preview-url.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpPost,
+ looseObjectArray,
+ normalizeDocName,
+ outputSchemaWithText,
+ parseRenameCollidingPairs,
+ previewUrlSourceField,
+ previousPreviewUrlField,
+ type RenameCollisionPair,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ summaryOutputSchema,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+
+export 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`.',
+ '- `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).',
+].join('\n');
+
+interface RenameMapping {
+ fromDocName: string;
+ toDocName: string;
+}
+interface RenameRewrittenDoc {
+ docName: string;
+ rewrites: number;
+}
+interface RenamedAsset {
+ fromPath: string;
+ toPath: string;
+}
+
+export interface MoveDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+interface MoveArgs {
+ from: string;
+ to: string;
+ summary?: string;
+ cwd?: string;
+}
+
+function parseRenameMappings(value: unknown): RenameMapping[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object') return [];
+ const { fromDocName, toDocName } = entry as Record<string, unknown>;
+ return typeof fromDocName === 'string' && typeof toDocName === 'string'
+ ? [{ fromDocName, toDocName }]
+ : [];
+ });
+}
+
+function parseRewrittenDocs(value: unknown): RenameRewrittenDoc[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object') return [];
+ const { docName, rewrites } = entry as Record<string, unknown>;
+ return typeof docName === 'string' && typeof rewrites === 'number'
+ ? [{ docName, rewrites }]
+ : [];
+ });
+}
+
+function parseRenamedAssets(value: unknown): RenamedAsset[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object') return [];
+ const { fromPath, toPath } = entry as Record<string, unknown>;
+ return typeof fromPath === 'string' && typeof toPath === 'string' ? [{ fromPath, toPath }] : [];
+ });
+}
+
+function isValidFolderPath(path: string): boolean {
+ if (typeof path !== 'string' || path.length === 0) return false;
+ if (path.startsWith('/') || path.endsWith('/')) return false;
+ if (path.includes('..')) return false;
+ return true;
+}
+
+function pluralize(count: number, singular: string, plural = `${singular}s`): string {
+ return count === 1 ? singular : plural;
+}
+
+function resolveMoveKind(contentDir: string, from: string): 'file' | 'folder' | 'asset' | null {
+ const contained = resolveWithinRoot(contentDir, from);
+ if (!contained.ok) return null;
+ const absBase = contained.abs;
+ if (existsSync(absBase)) {
+ try {
+ const stat = statSync(absBase);
+ if (stat.isDirectory()) return 'folder';
+ if (stat.isFile()) {
+ return absBase.endsWith('.md') || absBase.endsWith('.mdx') ? 'file' : 'asset';
+ }
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === 'EACCES' || code === 'EPERM') return 'file';
+ }
+ }
+ for (const ext of ['.md', '.mdx']) {
+ if (existsSync(`${absBase}${ext}`)) return 'file';
+ }
+ return null;
+}
+
+export function register(server: ServerInstance, deps: MoveDeps): void {
+ server.registerTool(
+ 'move',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ from: z.string().describe('Current path of a document, folder, or asset.'),
+ to: z
+ .string()
+ .describe('New path. All inbound wiki-links + inline links are rewritten automatically.'),
+ summary: summaryArgSchema.describe(
+ 'Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.',
+ ),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ ok: z.boolean().describe('Whether the move succeeded.'),
+ kind: z
+ .enum(['file', 'folder', 'asset'])
+ .optional()
+ .describe('What was moved, as auto-detected from `from`.'),
+ renamed: z
+ .array(z.object({ fromDocName: z.string(), toDocName: z.string() }))
+ .optional()
+ .describe('docName remappings performed.'),
+ rewrittenDocs: looseObjectArray
+ .optional()
+ .describe('Docs whose inbound links were rewritten.'),
+ renamedAssets: looseObjectArray
+ .optional()
+ .describe('Referenced assets that were moved alongside.'),
+ previewUrls: z
+ .record(z.string(), z.string())
+ .optional()
+ .describe('Route-only preview URL per new docName.'),
+ previewUrlSource: previewUrlSourceField,
+ previousPreviewUrl: previousPreviewUrlField,
+ summary: summaryOutputSchema.optional(),
+ error: z.string().optional().describe('Present when `ok` is false.'),
+ colliding: looseObjectArray
+ .optional()
+ .describe('On a 409 collision: the conflicting from→to pairs.'),
+ }),
+ },
+ async (args: MoveArgs) => {
+ const context = await resolveProjectServerContext(
+ deps.resolveCwd,
+ deps.config,
+ deps.serverUrl,
+ args.cwd,
+ );
+ if (!context.ok) return textResult(`Error: ${context.error}`, true);
+ const { cwd, config, url } = context;
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ const contentDir = join(cwd, config.content.dir);
+ const kind = resolveMoveKind(contentDir, args.from);
+ if (kind === null) {
+ return textResult(
+ `Error: \`${args.from}\` does not exist as a doc, folder, or asset under the content directory.`,
+ true,
+ );
+ }
+
+ let fromPath = args.from;
+ let toPath = args.to;
+ if (kind === 'file') {
+ const nf = normalizeDocName(args.from);
+ if (!nf.ok) return textResult(nf.error, true);
+ const nt = normalizeDocName(args.to);
+ if (!nt.ok) return textResult(nt.error, true);
+ fromPath = nf.docName;
+ toPath = nt.docName;
+ } else if (kind === 'folder') {
+ if (!isValidFolderPath(args.from) || !isValidFolderPath(args.to)) {
+ return textResult(
+ 'Error: folder `from`/`to` must be relative paths with no leading/trailing slash.',
+ true,
+ );
+ }
+ }
+
+ const result = await httpPost(url, '/api/rename-path', {
+ kind,
+ fromPath,
+ toPath,
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(deps.identityRef?.current),
+ });
+ if (!result.ok) {
+ const error = result.error as string;
+ const colliding = parseRenameCollidingPairs(result.colliding);
+ const structured: { ok: false; error: string; colliding?: RenameCollisionPair[] } = {
+ ok: false,
+ error,
+ ...(colliding.length > 0 ? { colliding } : {}),
+ };
+ return textPlusStructured(`Error: ${error}`, structured, true);
+ }
+
+ const renamed = parseRenameMappings(result.renamed);
+ const rewrittenDocs = parseRewrittenDocs(result.rewrittenDocs);
+ const renamedAssets = parseRenamedAssets(result.renamedAssets);
+
+ const previewDeps = { config: deps.config, resolveCwd: deps.resolveCwd };
+ const previewUrls: Record<string, string> = {};
+ let previewUrlSource: PreviewUrlSource | undefined;
+ let previousPreviewUrl: string | undefined;
+ if (kind === 'file') {
+ const newPreview = await resolvePreviewUrlForTool(toPath, previewDeps, cwd);
+ const oldPreview = await resolvePreviewUrlForTool(fromPath, previewDeps, cwd);
+ if (newPreview) {
+ previewUrls[toPath] = newPreview.url;
+ previewUrlSource = newPreview.source;
+ }
+ if (oldPreview) previousPreviewUrl = oldPreview.url;
+ } else if (kind === 'folder') {
+ for (const { toDocName } of renamed) {
+ const preview = await resolvePreviewUrlForTool(toDocName, previewDeps, cwd);
+ if (preview) {
+ previewUrls[toDocName] = preview.url;
+ previewUrlSource ??= preview.source;
+ }
+ }
+ }
+
+ const summaryResult =
+ result.summary && typeof result.summary === 'object'
+ ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
+ : undefined;
+ const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
+
+ const textLines: string[] = [];
+ if (kind === 'asset') {
+ textLines.push(`Moved asset ${fromPath} → ${toPath}.`);
+ } else if (kind === 'folder') {
+ textLines.push(
+ renamed.length === 0
+ ? `No managed docs under ${args.from}/ — nothing to rename. Empty folders are not tracked.`
+ : `Renamed folder ${args.from}/ → ${args.to}/ (${renamed.length} doc${renamed.length === 1 ? '' : 's'}, ${rewrittenDocs.length} rewrite${rewrittenDocs.length === 1 ? '' : 's'}).`,
+ );
+ } else {
+ const renamedSummary =
+ renamed
+ .map(({ fromDocName, toDocName }) => `${fromDocName} -> ${toDocName}`)
+ .join(', ') || `${fromPath} -> ${toPath}`;
+ const rewrittenSummary =
+ rewrittenDocs.length === 0
+ ? 'No inbound links required updates.'
+ : `Rewrote ${rewrittenDocs.length} ${pluralize(rewrittenDocs.length, 'document')}.`;
+ textLines.push(`Renamed ${renamedSummary}. ${rewrittenSummary}`);
+ }
+ if (renamedAssets.length > 0) {
+ textLines.push(
+ `Moved ${renamedAssets.length} referenced ${pluralize(renamedAssets.length, 'asset')}.`,
+ );
+ }
+ if (summaryHint) textLines.push(summaryHint);
+
+ return textPlusStructured(textLines.join('\n'), {
+ ok: true,
+ kind,
+ renamed,
+ rewrittenDocs,
+ ...(renamedAssets.length > 0 ? { renamedAssets } : {}),
+ ...(Object.keys(previewUrls).length > 0 ? { previewUrls } : {}),
+ ...(previewUrlSource ? { previewUrlSource } : {}),
+ ...(previousPreviewUrl ? { previousPreviewUrl } : {}),
+ ...(summaryResult ? { summary: summaryResult } : {}),
+ });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index 41b0dc66d..2bbc6ba63 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -6,11 +6,9 @@ import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-comp
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv.js';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register as registerDiscover } from './discover.ts';
-import { register as registerFolderConfig } from './folder-config.ts';
-import { register as registerGetComponents } from './get-components.ts';
-import { register as registerGetConfig } from './get-config.ts';
+import { register as registerConfig } from './config.ts';
import { registerAllTools } from './index.ts';
+import { register as registerPalette } from './palette.ts';
import { register as registerSearch } from './search.ts';
import type { ServerInstance } from './shared.ts';
@@ -66,76 +64,6 @@ function compileOutputSchemaForClient(rawShape: unknown): Record<string, unknown
}) as Record<string, unknown>;
}
-function validateStrict(
- jsonSchema: Record<string, unknown>,
- data: unknown,
-): {
- valid: boolean;
- error?: string;
-} {
- const validator = new AjvJsonSchemaValidator();
- const fn = validator.getValidator(jsonSchema);
- const result = fn(data);
- if (result.valid) return { valid: true };
- return { valid: false, error: result.errorMessage };
-}
-
-describe('MCP outputSchema strictness — structuredContent must validate (PRD-6655 + PRD-6656)', () => {
- test('discover: structuredContent validates against compiled outputSchema (PRD-6656)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(registerDiscover, {
- config: BASE_CONFIG,
- resolveCwd: async () => cwd,
- });
- const result = await captured.handler({});
- expect(result.isError).toBeFalsy();
- expect(result.structuredContent).toBeDefined();
-
- const jsonSchema = compileOutputSchemaForClient(captured.cfg.outputSchema);
- const validation = validateStrict(jsonSchema, result.structuredContent);
- expect(validation.error).toBeUndefined();
- expect(validation.valid).toBe(true);
- });
-
- test('folder_config (action=set-rule, success path): structuredContent validates against compiled outputSchema (PRD-6655)', async () => {
- const cwd = newProject();
- const captured = captureRegistration(registerFolderConfig, {
- config: BASE_CONFIG,
- resolveCwd: async () => cwd,
- });
- const result = await captured.handler({
- action: 'set-rule',
- rules: [{ match: 'projects/**', frontmatter: { tags: ['project'] } }],
- });
- expect(result.isError).toBeFalsy();
- expect(result.structuredContent).toBeDefined();
-
- const jsonSchema = compileOutputSchemaForClient(captured.cfg.outputSchema);
- const validation = validateStrict(jsonSchema, result.structuredContent);
- expect(validation.error).toBeUndefined();
- expect(validation.valid).toBe(true);
- });
-
- test('folder_config (action=set-rule, error path): error structuredContent ALSO validates', async () => {
- const cwd = newProject();
- const captured = captureRegistration(registerFolderConfig, {
- config: BASE_CONFIG,
- resolveCwd: async () => cwd,
- });
- const result = await captured.handler({
- action: 'set-rule',
- rules: [{ match: 'specs/*/evidence/**', frontmatter: {} }],
- });
- expect(result.isError).toBe(true);
- expect(result.structuredContent).toBeDefined();
-
- const jsonSchema = compileOutputSchemaForClient(captured.cfg.outputSchema);
- const validation = validateStrict(jsonSchema, result.structuredContent);
- expect(validation.error).toBeUndefined();
- expect(validation.valid).toBe(true);
- });
-});
-
describe('MCP outputSchema strictness — every registerTool+textPlusStructured tool must admit `text`', () => {
function compileFromRegistration<TDeps>(
register: (server: ServerInstance, deps: TDeps) => void,
@@ -154,15 +82,10 @@ describe('MCP outputSchema strictness — every registerTool+textPlusStructured
};
const cases: Array<{ name: string; build: () => Record<string, unknown> }> = [
- { name: 'discover', build: () => compileFromRegistration(registerDiscover, deps) },
- {
- name: 'folder_config',
- build: () => compileFromRegistration(registerFolderConfig, deps),
- },
- { name: 'get_config', build: () => compileFromRegistration(registerGetConfig, deps) },
+ { name: 'config', build: () => compileFromRegistration(registerConfig, deps) },
{
- name: 'get_components',
- build: () => compileFromRegistration(registerGetComponents, deps),
+ name: 'palette',
+ build: () => compileFromRegistration(registerPalette, deps),
},
{ name: 'search', build: () => compileFromRegistration(registerSearch, depsWithServer) },
];
@@ -204,17 +127,23 @@ describe('MCP outputSchema strictness — auto-discovered registerTool sweep (no
}
const KNOWN_REGISTER_TOOL_NAMES = new Set([
- 'discover',
- 'folder_config',
- 'get_authoring_palette',
- 'get_components',
- 'get_config',
- 'get_conflict_content',
- 'get_preview_url',
- 'list_conflicts',
+ 'palette',
+ 'config',
+ 'preview_url',
'resolve_conflict',
'search',
'share_link',
+ 'history',
+ 'checkpoint',
+ 'restore_version',
+ 'delete',
+ 'move',
+ 'conflicts',
+ 'workflow',
+ 'exec',
+ 'edit',
+ 'write',
+ 'links',
]);
test('every registerTool registration declares `text` in its outputSchema', () => {
diff --git a/packages/server/src/mcp/tools/get-authoring-palette.test.ts b/packages/server/src/mcp/tools/palette.test.ts
similarity index 96%
rename from packages/server/src/mcp/tools/get-authoring-palette.test.ts
rename to packages/server/src/mcp/tools/palette.test.ts
index fc8a32d8f..22c6207a0 100644
--- a/packages/server/src/mcp/tools/get-authoring-palette.test.ts
+++ b/packages/server/src/mcp/tools/palette.test.ts
@@ -5,7 +5,7 @@ import {
PREVIEW_THEME_TOKENS,
} from '@inkeep/open-knowledge-core';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './get-authoring-palette.ts';
+import { register } from './palette.ts';
import type { ServerInstance } from './shared.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({ content: { dir: '.' } });
@@ -40,7 +40,7 @@ function captureRegistration(): ToolHandler {
captured = handler;
},
tool() {
- throw new Error('legacy tool() should not be called by get_authoring_palette');
+ throw new Error('legacy tool() should not be called by palette');
},
} as unknown as ServerInstance;
register(server, {
@@ -51,7 +51,7 @@ function captureRegistration(): ToolHandler {
return captured;
}
-describe('get_authoring_palette tool', () => {
+describe('palette tool', () => {
test('returns the three-section payload with a version stamp', async () => {
const handler = captureRegistration();
const result = await handler({});
diff --git a/packages/server/src/mcp/tools/get-authoring-palette.ts b/packages/server/src/mcp/tools/palette.ts
similarity index 75%
rename from packages/server/src/mcp/tools/get-authoring-palette.ts
rename to packages/server/src/mcp/tools/palette.ts
index 4e2b1ad26..55cad4fec 100644
--- a/packages/server/src/mcp/tools/get-authoring-palette.ts
+++ b/packages/server/src/mcp/tools/palette.ts
@@ -1,8 +1,10 @@
import {
+ type ComponentEntryFull,
getAgentCanonicalDescriptors,
PREVIEW_EMBED_STARTERS,
PREVIEW_THEME_TOKENS,
previewEmbedFence,
+ projectFull,
} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import type { ConfigOrResolver, ServerInstance } from './shared.ts';
@@ -16,9 +18,10 @@ export const DESCRIPTION = [
'- `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.',
'',
- 'For the full JSX-form prop schema of a specific canonical, call `get_components({ ids })`.',
+ '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).',
].join('\n');
@@ -28,6 +31,13 @@ interface GetAuthoringPaletteDeps {
}
const InputSchema = {
+ components: z
+ .array(z.string().min(1))
+ .max(32)
+ .optional()
+ .describe(
+ 'Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`.',
+ ),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
} as const;
@@ -68,6 +78,14 @@ const OutputSchema = outputSchemaWithText({
}),
)
.describe('Theme tokens injected into every preview iframe — reference with `var(--name)`.'),
+ componentDetails: z
+ .array(z.record(z.string(), z.unknown()))
+ .optional()
+ .describe('Full JSX-form prop schema for the requested `components` ids (when provided).'),
+ notFound: z
+ .array(z.string())
+ .optional()
+ .describe('Requested `components` ids that did not match any canonical.'),
});
interface AuthoringFormSeed {
@@ -163,7 +181,7 @@ function buildComponents(): AuthoringComponent[] {
export function register(server: ServerInstance, _deps: GetAuthoringPaletteDeps): void {
server.registerTool(
- 'get_authoring_palette',
+ 'palette',
{
description: DESCRIPTION,
inputSchema: InputSchema,
@@ -173,10 +191,17 @@ export function register(server: ServerInstance, _deps: GetAuthoringPaletteDeps)
idempotentHint: true,
},
},
- async (args: { cwd?: string }) => {
+ async (args: { components?: string[]; cwd?: string }) => {
void args.cwd;
- const payload = {
- version: 1 as const,
+ const payload: {
+ version: 1;
+ components: ReturnType<typeof buildComponents>;
+ embedPatterns: Array<{ id: string; title: string; description: string; snippet: string }>;
+ tokens: Array<{ name: string; light: string; dark: string }>;
+ componentDetails?: ComponentEntryFull[];
+ notFound?: string[];
+ } = {
+ version: 1,
components: buildComponents(),
embedPatterns: PREVIEW_EMBED_STARTERS.map((s) => ({
id: s.id,
@@ -184,12 +209,26 @@ export function register(server: ServerInstance, _deps: GetAuthoringPaletteDeps)
description: s.description,
snippet: previewEmbedFence(s),
})),
- tokens: PREVIEW_THEME_TOKENS.map((t) => ({
- name: t.name,
- light: t.light,
- dark: t.dark,
- })),
+ tokens: PREVIEW_THEME_TOKENS.map((t) => ({ name: t.name, light: t.light, dark: t.dark })),
};
+ if (args.components && args.components.length > 0) {
+ const byId = new Map(getAgentCanonicalDescriptors().map((d) => [d.name, d]));
+ const details: ComponentEntryFull[] = [];
+ const notFound: string[] = [];
+ const seen = new Set<string>();
+ for (const id of args.components) {
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const descriptor = byId.get(id);
+ if (descriptor === undefined) {
+ notFound.push(id);
+ continue;
+ }
+ details.push(projectFull(descriptor));
+ }
+ payload.componentDetails = details;
+ payload.notFound = notFound;
+ }
return textPlusStructured(JSON.stringify(payload, null, 2), payload);
},
);
diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.ts
index 4417b582c..d0ade3cce 100644
--- a/packages/server/src/mcp/tools/preview-url.ts
+++ b/packages/server/src/mcp/tools/preview-url.ts
@@ -45,7 +45,7 @@ type PreviewAttachWarning =
const START_UI_MESSAGE =
'No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
const ATTACH_PREVIEW_ONCE_MESSAGE =
- 'No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.';
+ 'No browser is attached to the preview. Open it with preview_start, or call preview_url for the URL.';
export function buildPreviewAttachWarning(
preview: { url: string } | null,
diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.ts
index f02a489bc..cc9e66663 100644
--- a/packages/server/src/mcp/tools/registry.test.ts
+++ b/packages/server/src/mcp/tools/registry.test.ts
@@ -11,27 +11,21 @@ const BASE_CONFIG: Config = ConfigSchema.parse({});
const EXPECTED_TOOLS = [
'exec',
'search',
- 'get_history',
+ 'history',
'links',
- 'get_config',
- 'get_components',
- 'get_authoring_palette',
- 'get_preview_url',
+ 'config',
+ 'palette',
+ 'preview_url',
'share_link',
- 'write_document',
- 'edit_document',
- 'edit_frontmatter',
- 'delete_document',
- 'rename',
- 'version',
- 'folder_config',
- 'list_conflicts',
- 'get_conflict_content',
+ 'write',
+ 'edit',
+ 'delete',
+ 'move',
+ 'checkpoint',
+ 'restore_version',
+ 'conflicts',
'resolve_conflict',
- 'ingest',
- 'research',
- 'consolidate',
- 'discover',
+ 'workflow',
] as const;
const RETIRED_TOOL_NAMES = [
@@ -45,13 +39,29 @@ const RETIRED_TOOL_NAMES = [
'rename_folder',
'save_version',
'rollback_to_version',
+ 'version',
'set_folder_rule',
'write_template',
'delete_template',
'frontmatter_patch',
+ 'write_document',
+ 'edit_document',
+ 'edit_frontmatter',
+ 'delete_document',
+ 'rename',
+ 'folder_config',
'read_document',
'grep',
'list_documents',
+ 'get_components',
+ 'get_authoring_palette',
+ 'ingest',
+ 'research',
+ 'consolidate',
+ 'discover',
+ 'get_history',
+ 'get_config',
+ 'get_preview_url',
] as const;
function captureRegistered(): string[] {
@@ -73,13 +83,13 @@ function captureRegistered(): string[] {
return names;
}
-describe('registerAllTools — 23-tool surface (SPEC.md §9.1 / AC8)', () => {
- test('registers exactly 23 tools', () => {
+describe('registerAllTools — 17-tool surface (SPEC.md §9.1 / AC8)', () => {
+ test('registers exactly 17 tools', () => {
const names = captureRegistered();
- expect(names.length).toBe(23);
+ expect(names.length).toBe(17);
});
- test('the 23 expected tool names are all present', () => {
+ test('the 17 expected tool names are all present', () => {
const names = new Set(captureRegistered());
for (const expected of EXPECTED_TOOLS) {
expect(names).toContain(expected);
diff --git a/packages/server/src/mcp/tools/rename.test.ts b/packages/server/src/mcp/tools/rename.test.ts
deleted file mode 100644
index aa8ef83ef..000000000
--- a/packages/server/src/mcp/tools/rename.test.ts
+++ /dev/null
@@ -1,344 +0,0 @@
-import {
- describe as _bunDescribe,
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- expect,
- test,
-} from 'bun:test';
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
-import { DESCRIPTION, type RenameDeps, register } from './rename.ts';
-import type { ServerInstance } from './shared.ts';
-import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
-
-const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: boolean;
-}
-
-interface RenameHandlerArgs {
- from: string;
- to: string;
- summary?: string;
-}
-
-interface RegisteredTool {
- name: string;
- description: string;
- schema: Record<string, unknown>;
- handler: (args: RenameHandlerArgs) => Promise<ToolResult>;
-}
-
-function createFakeServer() {
- let registered: RegisteredTool | undefined;
- const server = {
- registerTool(
- name: string,
- cfg: { description?: string; inputSchema?: Record<string, unknown> },
- handler: (args: RenameHandlerArgs) => Promise<ToolResult>,
- ) {
- registered = {
- name,
- description: cfg.description ?? '',
- schema: cfg.inputSchema ?? {},
- handler,
- };
- },
- } as unknown as ServerInstance;
- return {
- server,
- getTool(): RegisteredTool {
- if (!registered) throw new Error('Tool was not registered');
- return registered;
- },
- };
-}
-
-function makeDeps(serverUrl: string | undefined, cwdDir: string): RenameDeps {
- return {
- serverUrl,
- config: BASE_CONFIG,
- resolveCwd: async () => cwdDir,
- };
-}
-
-let testServer: ReturnType<typeof Bun.serve>;
-let baseUrl: string;
-let tmpDir: string;
-const seenRequests: Array<{ method: string; pathname: string; body: Record<string, unknown> }> = [];
-let mockServerResponse: Record<string, unknown> = {};
-
-beforeAll(() => {
- testServer = Bun.serve({
- port: 0,
- async fetch(req) {
- const url = new URL(req.url);
- const body =
- req.method === 'POST'
- ? ((await req.json()) as Record<string, unknown>)
- : ({} as Record<string, unknown>);
- seenRequests.push({ method: req.method, pathname: url.pathname, body });
-
- if (url.pathname === '/api/rename-path' && req.method === 'POST') {
- if (mockServerResponse.error) {
- return Response.json({ ok: false, ...mockServerResponse }, { status: 409 });
- }
- const summary = body.summary as string | undefined;
- const summaryShape =
- summary !== undefined ? { value: summary, hint: 'summary recorded' } : undefined;
- return Response.json({
- ok: true,
- renamed: mockServerResponse.renamed ?? [],
- renamedAssets: mockServerResponse.renamedAssets ?? [],
- rewrittenDocs: mockServerResponse.rewrittenDocs ?? [],
- ...(summaryShape ? { summary: summaryShape } : {}),
- });
- }
- return new Response('Not found', { status: 404 });
- },
- });
- baseUrl = `http://localhost:${testServer.port}`;
-});
-
-afterAll(() => {
- testServer.stop();
-});
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-rename-test-'));
- await mkdir(resolve(tmpdir(), tmpDir, '.ok'), { recursive: true });
- seenRequests.length = 0;
- mockServerResponse = {};
-});
-
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-describe('rename — registration + DESCRIPTION', () => {
- test('registers exactly one tool named "rename"', () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- expect(getTool().name).toBe('rename');
- });
-
- test('DESCRIPTION explains both kinds and the file/folder probe behavior', () => {
- expect(DESCRIPTION).toContain('doc');
- expect(DESCRIPTION).toContain('folder');
- expect(DESCRIPTION).toContain('previewUrl');
- expect(DESCRIPTION).toContain('previewUrls');
- expect(DESCRIPTION).toContain('colliding');
- });
-
- test('returns Hocuspocus-unavailable error when no serverUrl is configured', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(undefined, tmpDir));
- const result = await getTool().handler({ from: 'a', to: 'b' });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
- });
-});
-
-describe('rename — resolveRenameKind dispatch', () => {
- test('non-existent `from` returns a tool-level error', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'ghost', to: 'phantom' });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('does not exist as a doc or folder');
- expect(seenRequests).toHaveLength(0);
- });
-});
-
-describe('rename — file branch', () => {
- test('resolves `.md` file → POSTs kind:file with normalized docNames', async () => {
- await writeFile(resolve(tmpDir, 'notes.md'), '# notes');
- mockServerResponse = {
- renamed: [{ fromDocName: 'notes', toDocName: 'thoughts' }],
- rewrittenDocs: [],
- };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes.md', to: 'thoughts.md' });
-
- expect(result.isError).toBeUndefined();
- expect(seenRequests[0]?.body).toMatchObject({
- kind: 'file',
- fromPath: 'notes',
- toPath: 'thoughts',
- });
- const structured = result.structuredContent as { kind: string; previewUrl: string | null };
- expect(structured.kind).toBe('file');
- expect(structured.previewUrl).toBeNull();
- });
-
- test('emits route-only previewUrl + previousPreviewUrl when UI lock is bound', async () => {
- await writeFile(resolve(tmpDir, 'old.md'), '# old');
- bindTestUiLock(tmpDir);
- mockServerResponse = {
- renamed: [{ fromDocName: 'old', toDocName: 'new' }],
- rewrittenDocs: [{ docName: 'sibling', rewrites: 2 }],
- };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'old', to: 'new' });
-
- const structured = result.structuredContent as {
- previewUrl: string;
- previousPreviewUrl: string;
- rewrittenDocs: Array<{ docName: string; rewrites: number }>;
- };
- expect(structured.previewUrl).toBe('/#/new');
- expect(structured.previousPreviewUrl).toBe('/#/old');
- expect(structured.rewrittenDocs).toHaveLength(1);
- });
-
- test('threads identity passthrough into the rename body', async () => {
- await writeFile(resolve(tmpDir, 'foo.md'), '# foo');
- mockServerResponse = { renamed: [], rewrittenDocs: [] };
- const { server, getTool } = createFakeServer();
- register(server, {
- ...makeDeps(baseUrl, tmpDir),
- identityRef: {
- current: {
- connectionId: 'conn-7',
- displayName: 'Cody',
- colorSeed: 'seed-7',
- clientInfo: { name: 'claude', version: '1.0.0' },
- },
- },
- });
- await getTool().handler({ from: 'foo', to: 'bar', summary: 'Aligned naming' });
-
- expect(seenRequests[0]?.body).toMatchObject({
- kind: 'file',
- agentId: 'conn-7',
- agentName: 'Cody',
- colorSeed: 'seed-7',
- summary: 'Aligned naming',
- });
- });
-
- test('surfaces 409 collision via structured `colliding` field', async () => {
- await writeFile(resolve(tmpDir, 'src.md'), '# src');
- mockServerResponse = {
- error: 'destination exists',
- colliding: [{ existing: 'dest', incoming: 'src', to: 'dest' }],
- };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'src', to: 'dest' });
-
- expect(result.isError).toBe(true);
- const structured = result.structuredContent as {
- ok: boolean;
- colliding: Array<{ existing: string; incoming: string; to: string }>;
- };
- expect(structured.ok).toBe(false);
- expect(structured.colliding).toEqual([{ existing: 'dest', incoming: 'src', to: 'dest' }]);
- });
-});
-
-describe('rename — folder branch', () => {
- test('resolves directory → POSTs kind:folder with raw folder paths', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- await writeFile(resolve(tmpDir, 'notes', 'a.md'), '# a');
- mockServerResponse = {
- renamed: [{ fromDocName: 'notes/a', toDocName: 'essays/a' }],
- rewrittenDocs: [{ docName: 'index', rewrites: 1 }],
- };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes', to: 'essays' });
-
- expect(result.isError).toBeUndefined();
- expect(seenRequests[0]?.body).toMatchObject({
- kind: 'folder',
- fromPath: 'notes',
- toPath: 'essays',
- });
- const structured = result.structuredContent as {
- kind: string;
- previewUrls: Record<string, string>;
- };
- expect(structured.kind).toBe('folder');
- expect(structured.previewUrls).toEqual({});
- });
-
- test('emits route-only previewUrls map for every renamed doc when UI lock is bound', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- await writeFile(resolve(tmpDir, 'notes', 'a.md'), '# a');
- bindTestUiLock(tmpDir);
- mockServerResponse = {
- renamed: [
- { fromDocName: 'notes/a', toDocName: 'essays/a' },
- { fromDocName: 'notes/b', toDocName: 'essays/b' },
- ],
- rewrittenDocs: [],
- };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes', to: 'essays' });
-
- const structured = result.structuredContent as {
- previewUrls: Record<string, string>;
- previewUrlSource: string;
- };
- expect(structured.previewUrls['essays/a']).toBe('/#/essays/a');
- expect(structured.previewUrls['essays/b']).toBe('/#/essays/b');
- expect(structured.previewUrlSource).toBe('lock');
- });
-
- test('rejects folder path with leading/trailing slash', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes', to: '/essays' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('relative path');
- });
-
- test('rejects folder path with `..`', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes', to: '../escape' });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('relative path');
- });
-
- test('passes summary through to the rename body', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- mockServerResponse = { renamed: [], rewrittenDocs: [] };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- await getTool().handler({ from: 'notes', to: 'essays', summary: 'Reorganized layout' });
-
- expect(seenRequests[0]?.body).toMatchObject({
- kind: 'folder',
- summary: 'Reorganized layout',
- });
- });
-
- test('emits an empty-folder message when no docs were renamed', async () => {
- await mkdir(resolve(tmpDir, 'notes'), { recursive: true });
- mockServerResponse = { renamed: [], rewrittenDocs: [] };
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const result = await getTool().handler({ from: 'notes', to: 'essays' });
-
- expect(result.content[0]?.text).toContain('No managed docs under notes/');
- });
-});
diff --git a/packages/server/src/mcp/tools/rename.ts b/packages/server/src/mcp/tools/rename.ts
deleted file mode 100644
index 298b40685..000000000
--- a/packages/server/src/mcp/tools/rename.ts
+++ /dev/null
@@ -1,347 +0,0 @@
-import { existsSync, statSync } from 'node:fs';
-import { join } from 'node:path';
-import { z } from 'zod';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { resolveWithinRoot } from './path-safety.ts';
-import { type PreviewUrlSource, resolvePreviewUrlForTool } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpPost,
- normalizeDocName,
- parseRenameCollidingPairs,
- type RenameCollisionPair,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- summaryArgSchema,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Rename a doc or a folder through the managed rename flow at `POST /api/rename-path`. The tool probes the content directory to decide whether `from` is a doc or a folder, then sets `kind` (`file` vs `folder`) accordingly. Renaming rewrites inbound wiki-links plus supported internal inline Markdown links across affected docs.',
- '',
- '**Parameters:**',
- '- `from` — Source path. For a doc, the docName (typically without extension; trailing `.md`/`.mdx` is stripped). For a folder, the folder path relative to the content directory with no leading/trailing slash (e.g. `notes/drafts`).',
- '- `to` — Destination path. Same shape as `from`. For a folder rename, parent directories are auto-created.',
- '- `summary` — Optional one-line user-outcome description (≤80 chars). If omitted, defaults to "Renamed X → Y". Appears as a bullet in the timeline. Avoid secrets or PII — summaries persist to git history.',
- '',
- '**Output:**',
- '- Doc rename — `{previewUrl, previousPreviewUrl?, renamed, rewrittenDocs, ...}`.',
- '- Folder rename — `{previewUrls: Record<newDocName, url>, renamed, rewrittenDocs, ...}`.',
- '',
- '**Errors:**',
- '- 400 — destination excluded by `.gitignore` / `.okignore`; invalid path shape.',
- '- 404 — source doc or folder does not exist.',
- '- 409 — destination already exists; server returns a structured `colliding[]` list in this case.',
-].join('\n');
-
-interface RenameMapping {
- fromDocName: string;
- toDocName: string;
-}
-
-interface RenameRewrittenDoc {
- docName: string;
- rewrites: number;
-}
-
-interface RenameFileSuccess {
- ok: true;
- kind: 'file';
- renamed: RenameMapping[];
- rewrittenDocs: RenameRewrittenDoc[];
- previewUrl: string | null;
- previewUrlSource?: PreviewUrlSource;
- previousPreviewUrl?: string;
- summary?: { value: string; truncatedFrom?: number; hint?: string };
-}
-
-interface RenameFolderSuccess {
- ok: true;
- kind: 'folder';
- renamed: RenameMapping[];
- rewrittenDocs: RenameRewrittenDoc[];
- previewUrls: Record<string, string>;
- previewUrlSource?: PreviewUrlSource;
- summary?: { value: string; truncatedFrom?: number; hint?: string };
-}
-
-interface RenameError {
- ok: false;
- error: string;
- colliding?: RenameCollisionPair[];
-}
-
-export interface RenameDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- /** Same identity passthrough pattern as write-document. Without this,
- * MCP-driven renames post no agentId → the server-side guard skips
- * attribution, so summaries would have no contributor entry to live on. */
- identityRef?: { current: AgentIdentity };
-}
-
-interface RenameArgs {
- from: string;
- to: string;
- summary?: string;
- cwd?: string;
-}
-
-function parseRenameMappings(value: unknown): RenameMapping[] {
- if (!Array.isArray(value)) return [];
- return value.flatMap((entry) => {
- if (!entry || typeof entry !== 'object') return [];
- const { fromDocName, toDocName } = entry as Record<string, unknown>;
- return typeof fromDocName === 'string' && typeof toDocName === 'string'
- ? [{ fromDocName, toDocName }]
- : [];
- });
-}
-
-function parseRewrittenDocs(value: unknown): RenameRewrittenDoc[] {
- if (!Array.isArray(value)) return [];
- return value.flatMap((entry) => {
- if (!entry || typeof entry !== 'object') return [];
- const { docName, rewrites } = entry as Record<string, unknown>;
- return typeof docName === 'string' && typeof rewrites === 'number'
- ? [{ docName, rewrites }]
- : [];
- });
-}
-
-function isValidFolderPath(path: string): boolean {
- if (typeof path !== 'string' || path.length === 0) return false;
- if (path.startsWith('/') || path.endsWith('/')) return false;
- if (path.includes('..')) return false;
- return true;
-}
-
-function pluralize(count: number, singular: string, plural = `${singular}s`): string {
- return count === 1 ? singular : plural;
-}
-
-function resolveRenameKind(contentDir: string, from: string): 'file' | 'folder' | null {
- const contained = resolveWithinRoot(contentDir, from);
- if (!contained.ok) return null;
- const absBase = contained.abs;
- if (existsSync(absBase)) {
- try {
- const stat = statSync(absBase);
- if (stat.isDirectory()) return 'folder';
- if (stat.isFile() && (absBase.endsWith('.md') || absBase.endsWith('.mdx'))) return 'file';
- } catch (err) {
- const code = (err as NodeJS.ErrnoException).code;
- if (code === 'EACCES' || code === 'EPERM') return 'file';
- }
- }
- for (const ext of ['.md', '.mdx']) {
- if (existsSync(`${absBase}${ext}`)) return 'file';
- }
- return null;
-}
-
-export function register(server: ServerInstance, deps: RenameDeps): void {
- server.registerTool(
- 'rename',
- {
- description: DESCRIPTION,
- inputSchema: {
- from: z
- .string()
- .describe(
- 'Current path. Doc: docName (typically extensionless). Folder: relative path with no leading/trailing slash.',
- ),
- to: z
- .string()
- .describe(
- 'New path. Doc: docName (typically extensionless). Folder: relative path with no leading/trailing slash.',
- ),
- summary: summaryArgSchema.describe(
- 'Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Persisted to git history.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: RenameArgs) => {
- const context = await resolveProjectServerContext(
- deps.resolveCwd,
- deps.config,
- deps.serverUrl,
- args.cwd,
- );
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- const { cwd, config, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
-
- const contentDir = join(cwd, config.content.dir);
- const kind = resolveRenameKind(contentDir, args.from);
- if (kind === null) {
- return textResult(
- `Error: \`${args.from}\` does not exist as a doc or folder under the content directory.`,
- true,
- );
- }
-
- if (kind === 'file') {
- return handleFileRename(args, url, cwd, deps);
- }
- return handleFolderRename(args, url, cwd, deps);
- },
- );
-}
-
-async function handleFileRename(args: RenameArgs, url: string, cwd: string, deps: RenameDeps) {
- const normalizedFrom = normalizeDocName(args.from);
- if (!normalizedFrom.ok) return textResult(normalizedFrom.error, true);
- const normalizedTo = normalizeDocName(args.to);
- if (!normalizedTo.ok) return textResult(normalizedTo.error, true);
-
- const identity = deps.identityRef?.current;
- const result = await httpPost(url, '/api/rename-path', {
- kind: 'file',
- fromPath: normalizedFrom.docName,
- toPath: normalizedTo.docName,
- ...(args.summary !== undefined ? { summary: args.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
-
- if (!result.ok) {
- const error = result.error as string;
- const colliding = parseRenameCollidingPairs(result.colliding);
- const structured: RenameError = {
- ok: false,
- error,
- ...(colliding.length > 0 ? { colliding } : {}),
- };
- return textPlusStructured(`Error: ${error}`, structured, true);
- }
-
- const renamed = parseRenameMappings(result.renamed);
- const rewrittenDocs = parseRewrittenDocs(result.rewrittenDocs);
- const renamedSummary =
- renamed.map(({ fromDocName, toDocName }) => `${fromDocName} -> ${toDocName}`).join(', ') ||
- `${normalizedFrom.docName} -> ${normalizedTo.docName}`;
- const rewrittenSummary =
- rewrittenDocs.length === 0
- ? 'No inbound links required updates.'
- : `Rewrote ${rewrittenDocs.length} ${pluralize(rewrittenDocs.length, 'document')}.`;
-
- const previewDeps = { config: deps.config, resolveCwd: deps.resolveCwd };
- const newPreview = await resolvePreviewUrlForTool(normalizedTo.docName, previewDeps, cwd);
- const oldPreview = await resolvePreviewUrlForTool(normalizedFrom.docName, previewDeps, cwd);
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const structured: RenameFileSuccess = {
- ok: true,
- kind: 'file',
- renamed,
- rewrittenDocs,
- previewUrl: newPreview?.url ?? null,
- ...(newPreview ? { previewUrlSource: newPreview.source } : {}),
- ...(oldPreview ? { previousPreviewUrl: oldPreview.url } : {}),
- ...(summaryResult ? { summary: summaryResult } : {}),
- };
-
- const textLines = [`Renamed ${renamedSummary}. ${rewrittenSummary}`];
- if (summaryHint) textLines.push(summaryHint);
- return textPlusStructured(textLines.join('\n'), structured);
-}
-
-async function handleFolderRename(args: RenameArgs, url: string, cwd: string, deps: RenameDeps) {
- if (!isValidFolderPath(args.from)) {
- return textResult(
- 'Error: `from` must be a relative path with no leading/trailing slash.',
- true,
- );
- }
- if (!isValidFolderPath(args.to)) {
- return textResult('Error: `to` must be a relative path with no leading/trailing slash.', true);
- }
-
- const identity = deps.identityRef?.current;
- const result = await httpPost(url, '/api/rename-path', {
- kind: 'folder',
- fromPath: args.from,
- toPath: args.to,
- ...(args.summary !== undefined ? { summary: args.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
-
- if (!result.ok) {
- const error = result.error as string;
- const colliding = parseRenameCollidingPairs(result.colliding);
- const structured: RenameError = {
- ok: false,
- error,
- ...(colliding.length > 0 ? { colliding } : {}),
- };
- return textPlusStructured(`Error: ${error}`, structured, true);
- }
-
- const renamed = parseRenameMappings(result.renamed);
- const rewrittenDocs = parseRewrittenDocs(result.rewrittenDocs);
-
- const previewDeps = { config: deps.config, resolveCwd: deps.resolveCwd };
- const previewUrls: Record<string, string> = {};
- let previewUrlSource: PreviewUrlSource | undefined;
- for (const { toDocName } of renamed) {
- const preview = await resolvePreviewUrlForTool(toDocName, previewDeps, cwd);
- if (preview) {
- previewUrls[toDocName] = preview.url;
- previewUrlSource ??= preview.source;
- }
- }
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const structured: RenameFolderSuccess = {
- ok: true,
- kind: 'folder',
- renamed,
- rewrittenDocs,
- previewUrls,
- ...(previewUrlSource ? { previewUrlSource } : {}),
- ...(summaryResult ? { summary: summaryResult } : {}),
- };
-
- const textLines: string[] = [];
- if (renamed.length === 0) {
- textLines.push(
- `No managed docs under ${args.from}/ — nothing to rename. Empty folders are not tracked; create a doc inside the folder first.`,
- );
- } else {
- textLines.push(
- `Renamed folder ${args.from}/ → ${args.to}/ (${renamed.length} doc${
- renamed.length === 1 ? '' : 's'
- }, ${rewrittenDocs.length} rewrite${rewrittenDocs.length === 1 ? '' : 's'}).`,
- );
- }
- if (summaryHint) textLines.push(summaryHint);
- return textPlusStructured(textLines.join('\n'), structured);
-}
diff --git a/packages/server/src/mcp/tools/research.ts b/packages/server/src/mcp/tools/research-body.ts
similarity index 94%
rename from packages/server/src/mcp/tools/research.ts
rename to packages/server/src/mcp/tools/research-body.ts
index cfe4bde9e..72c430aa7 100644
--- a/packages/server/src/mcp/tools/research.ts
+++ b/packages/server/src/mcp/tools/research-body.ts
@@ -1,9 +1,6 @@
import { OK_DIR } from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import type { ServerInstance, WorkflowToolDeps } from './shared.ts';
-import { buildWorkflowHandler, ROUTED_CWD_DESCRIPTION } from './shared.ts';
-function buildBody(topic: string, contentDir: string): string {
+export function buildResearchBody(topic: string, contentDir: string): string {
return `Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
Topic: ${topic}
@@ -356,23 +353,3 @@ In headless mode, write the recap into the research article's "Further reading"
- **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
`;
}
-
-export const DESCRIPTION = [
- 'Returns a step-by-step plan to research a topic: scan existing coverage, scope a rubric, capture sources via `ingest`, then write a provisional research article. Does NOT fetch or write — you execute the plan.',
- 'Provisional, not canonical — findings live here until decisions solidify (`consolidate` promotes them).',
- 'Use when exploring a decision space, comparing alternatives, or synthesizing sources into structured analysis.',
-].join('\n');
-
-export function register(server: ServerInstance, deps: WorkflowToolDeps): void {
- server.registerTool(
- 'research',
- {
- description: DESCRIPTION,
- inputSchema: {
- topic: z.string().describe('The topic, question, or anchor URL to research'),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- buildWorkflowHandler('research', deps, 'topic', buildBody),
- );
-}
diff --git a/packages/server/src/mcp/tools/research.test.ts b/packages/server/src/mcp/tools/research.test.ts
deleted file mode 100644
index 4b504be0b..000000000
--- a/packages/server/src/mcp/tools/research.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe as _bunDescribe, expect, test } from 'bun:test';
-
-const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register } from './research.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
-}
-
-function captureTool() {
- let captured: ((args: { topic: string; cwd?: string }) => Promise<ToolResult>) | undefined;
- const server = {
- registerTool(
- _name: string,
- _config: unknown,
- handler: (args: { topic: string; cwd?: string }) => Promise<ToolResult>,
- ) {
- captured = handler;
- },
- } as unknown as ServerInstance;
- return {
- server,
- async call(topic: string) {
- if (!captured) throw new Error('Tool was not registered');
- return await captured({ topic });
- },
- };
-}
-
-describe('research — previewUrl emission', () => {
- test('returns structuredContent with previewUrl: null (workflow primer)', async () => {
- const { server, call } = captureTool();
- register(server, { config: BASE_CONFIG, resolveCwd: async () => process.cwd() });
- const result = await call('CRDT alternatives');
- expect(result.structuredContent).toMatchObject({ previewUrl: null });
- expect(result.content[0]?.text).toContain('CRDT alternatives');
- });
-});
diff --git a/packages/server/src/mcp/tools/resolve-conflict.test.ts b/packages/server/src/mcp/tools/resolve-conflict.test.ts
index aacac036b..5d37f20c8 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.test.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.test.ts
@@ -83,7 +83,7 @@ describe('resolve_conflict MCP tool', () => {
register(server, makeDeps('http://localhost:4321'));
const tool = getTool(registrations, 'resolve_conflict');
- expect(tool.config.description).toContain('list_conflicts');
+ 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');
diff --git a/packages/server/src/mcp/tools/resolve-conflict.ts b/packages/server/src/mcp/tools/resolve-conflict.ts
index 1d30f4ff9..910e2d45a 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.ts
@@ -14,12 +14,12 @@ export const DESCRIPTION = [
'[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.',
'',
'Strategy:',
- '- `mine` — writes `git show :2:<file>` (your committed ours stage). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.',
- '- `theirs` — writes `git show :3:<file>` (their committed stage). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.',
+ '- `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 provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty — use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).',
- '- `delete` — runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `kind` field on `get_conflict_content` to pick the right strategy for the conflict shape.',
+ '- `delete` — runs `git rm <file>` then commits the deletion. 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.',
'',
- 'Returns 200 on success; 500 indicates commit failure (re-call `list_conflicts` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',
+ 'Returns 200 on success; 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 creates a git commit.',
'',
diff --git a/packages/server/src/mcp/tools/restore-version.test.ts b/packages/server/src/mcp/tools/restore-version.test.ts
new file mode 100644
index 000000000..e94979177
--- /dev/null
+++ b/packages/server/src/mcp/tools/restore-version.test.ts
@@ -0,0 +1,142 @@
+import {
+ describe as _bunDescribe,
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+} from 'bun:test';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { DESCRIPTION, type RestoreVersionDeps, register } from './restore-version.ts';
+import type { ServerInstance } from './shared.ts';
+import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
+
+const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+const SHA = '0123456789abcdef0123456789abcdef01234567';
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: boolean;
+}
+interface RegisteredTool {
+ name: string;
+ description: string;
+ handler: (args: {
+ document?: string;
+ version?: string;
+ summary?: string;
+ cwd?: string;
+ }) => Promise<ToolResult>;
+}
+
+function createFakeServer() {
+ let registered: RegisteredTool | undefined;
+ const server = {
+ registerTool(name: string, cfg: { description?: string }, handler: RegisteredTool['handler']) {
+ registered = { name, description: cfg.description ?? '', handler };
+ },
+ } as unknown as ServerInstance;
+ return {
+ server,
+ getTool(): RegisteredTool {
+ if (!registered) throw new Error('Tool was not registered');
+ return registered;
+ },
+ };
+}
+
+function makeDeps(serverUrl: string | undefined, cwdDir: string): RestoreVersionDeps {
+ return { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwdDir };
+}
+
+let testServer: ReturnType<typeof Bun.serve>;
+let baseUrl: string;
+let tmpDir: string;
+const seenRequests: string[] = [];
+const seenBodies: Array<Record<string, unknown>> = [];
+let mockRollbackWarning: Record<string, unknown> | undefined;
+
+beforeAll(() => {
+ testServer = Bun.serve({
+ port: 0,
+ async fetch(req) {
+ const url = new URL(req.url);
+ const body = req.method === 'POST' ? ((await req.json()) as Record<string, unknown>) : {};
+ seenRequests.push(`${req.method} ${url.pathname}`);
+ if (req.method === 'POST') seenBodies.push(body);
+ if (url.pathname.startsWith('/api/history/') && req.method === 'GET') {
+ return Response.json({ ok: true, author: 'Alice', timestamp: '2026-05-20T00:00:00Z' });
+ }
+ if (url.pathname === '/api/rollback' && req.method === 'POST') {
+ return Response.json({
+ ok: true,
+ ...(mockRollbackWarning !== undefined ? { warning: mockRollbackWarning } : {}),
+ });
+ }
+ return new Response('Not found', { status: 404 });
+ },
+ });
+ baseUrl = `http://localhost:${testServer.port}`;
+});
+afterAll(() => testServer.stop());
+beforeEach(async () => {
+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-restore-version-test-'));
+ seenRequests.length = 0;
+ seenBodies.length = 0;
+ mockRollbackWarning = undefined;
+});
+afterEach(async () => {
+ await rm(tmpDir, { recursive: true, force: true });
+});
+
+describe('restore_version — registration + behavior', () => {
+ test('registers exactly one tool named "restore_version"', () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ expect(getTool().name).toBe('restore_version');
+ expect(DESCRIPTION).toContain('version');
+ });
+
+ test('verifies the version (GET /api/history) then POSTs /api/rollback with commitSha', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const result = await getTool().handler({ document: 'notes/x', version: SHA });
+ expect(result.isError).toBeFalsy();
+ expect(seenRequests.some((r) => r.startsWith('GET /api/history/'))).toBe(true);
+ expect(seenRequests).toContain('POST /api/rollback');
+ expect(seenBodies.at(-1)?.commitSha).toBe(SHA);
+ expect(seenBodies.at(-1)?.docName).toBe('notes/x');
+ expect(result.content[0]?.text).toContain('Restored "notes/x"');
+ expect(result.structuredContent?.document).toBe('notes/x');
+ expect(result.structuredContent?.version).toBe(SHA);
+ });
+
+ test('relays a content-divergence warning into structuredContent', async () => {
+ mockRollbackWarning = {
+ kind: 'content-divergence',
+ intendedBytes: 100,
+ actualBytes: 98,
+ byteDelta: -2,
+ divergenceType: 'residue',
+ };
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const result = await getTool().handler({ document: 'notes/x', version: SHA });
+ expect(result.structuredContent?.contentDivergence).toBeDefined();
+ expect(result.content[0]?.text).toContain('Content divergence');
+ });
+
+ test('returns Hocuspocus-unavailable error when no serverUrl is configured', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(undefined, tmpDir));
+ const result = await getTool().handler({ document: 'notes/x', version: SHA });
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain(HOCUSPOCUS_NOT_RUNNING_ERROR);
+ });
+});
diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.ts
new file mode 100644
index 000000000..c1cd9c0bb
--- /dev/null
+++ b/packages/server/src/mcp/tools/restore-version.ts
@@ -0,0 +1,138 @@
+import { WriteWarningSchema } from '@inkeep/open-knowledge-core';
+import { z } from 'zod';
+import type { AgentIdentity } from '../agent-identity.ts';
+import { formatContentDivergenceLine, parseContentDivergence } from './content-divergence.ts';
+import { resolvePreviewUrlForTool } from './preview-url.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpGet,
+ httpPost,
+ normalizeDocName,
+ outputSchemaWithText,
+ previewUrlOutputField,
+ previewUrlSourceField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ summaryOutputSchema,
+ textPlusStructured,
+ textResult,
+ versionInputSchema,
+} from './shared.ts';
+
+export const DESCRIPTION = [
+ '[Requires: Hocuspocus server] Restore a single document to a historical version via the CRDT layer — append-only (creates a new version with the old content; all connected editors see the change live).',
+ '',
+ '**Parameters:**',
+ '- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped).',
+ '- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).',
+ '- `summary` — Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Avoid secrets or PII — persisted to git history.',
+ '',
+ 'A response may include `structuredContent.contentDivergence` when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.',
+].join('\n');
+
+export interface RestoreVersionDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+export function register(server: ServerInstance, deps: RestoreVersionDeps): void {
+ server.registerTool(
+ 'restore_version',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ document: z.string().describe('Document to restore (path, no extension).'),
+ version: versionInputSchema.describe(
+ "The 40-character commit SHA to restore to — copy it straight from a `history` entry's `version` field (same name there).",
+ ),
+ summary: summaryArgSchema.describe(
+ 'Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Persisted to git history.',
+ ),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ document: z.string().describe('The document that was restored (echo of the input).'),
+ version: z
+ .string()
+ .describe('The version the document was restored to (echo of the input).'),
+ previewUrl: previewUrlOutputField,
+ previewUrlSource: previewUrlSourceField,
+ summary: summaryOutputSchema.optional(),
+ contentDivergence: WriteWarningSchema.optional().describe(
+ 'Present only when the restored Y.Text did not byte-match the target version.',
+ ),
+ }),
+ },
+ async (args: { document: string; version: string; summary?: 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 { cwd, url } = context;
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+
+ const normalized = normalizeDocName(args.document);
+ if (!normalized.ok) return textResult(normalized.error, true);
+ const docName = normalized.docName;
+
+ const versionResult = await httpGet(
+ url,
+ `/api/history/${args.version}?docName=${encodeURIComponent(docName)}`,
+ );
+ if (!versionResult.ok) {
+ return textResult(`Error: ${versionResult.error ?? 'Version not found'}`, true);
+ }
+
+ const identity = deps.identityRef?.current;
+ const result = await httpPost(url, '/api/rollback', {
+ docName,
+ commitSha: args.version,
+ ...(args.summary !== undefined ? { summary: args.summary } : {}),
+ ...agentIdentityFields(identity),
+ });
+ if (!result.ok) return textResult(`Error: ${result.error}`, true);
+
+ const summaryResult =
+ result.summary && typeof result.summary === 'object'
+ ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
+ : undefined;
+ const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
+
+ const contentDivergence = parseContentDivergence(result.warning);
+
+ const author = typeof versionResult.author === 'string' ? versionResult.author : undefined;
+ const timestamp =
+ typeof versionResult.timestamp === 'string' ? versionResult.timestamp : undefined;
+ const provenance = author && timestamp ? ` (${author}, ${timestamp})` : '';
+ const textLines = [
+ `Restored "${docName}" to version ${args.version.slice(0, 8)}${provenance}. The change has been applied to all connected editors.`,
+ ];
+ if (summaryHint) textLines.push(summaryHint);
+ if (contentDivergence) {
+ textLines.push(formatContentDivergenceLine(contentDivergence));
+ }
+
+ const preview = await resolvePreviewUrlForTool(
+ docName,
+ { config: deps.config, resolveCwd: deps.resolveCwd },
+ cwd,
+ );
+ return textPlusStructured(textLines.join('\n'), {
+ document: docName,
+ version: args.version,
+ previewUrl: preview?.url ?? null,
+ ...(preview ? { previewUrlSource: preview.source } : {}),
+ ...(summaryResult ? { summary: summaryResult } : {}),
+ ...(contentDivergence ? { contentDivergence } : {}),
+ });
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index d4a65f20c..a659e0439 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -1,10 +1,22 @@
-import { validateDocName } from '@inkeep/open-knowledge-core';
+import { validateDocName, WriteWarningSchema } from '@inkeep/open-knowledge-core';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import type { Config } from '../../config/schema.ts';
+import type { AgentIdentity } from '../agent-identity.ts';
export type ServerInstance = McpServer;
export type ConfigOrResolver = Config | ((cwd?: string) => Promise<Config>);
+
+export function agentIdentityFields(identity: AgentIdentity | undefined): Record<string, unknown> {
+ return identity
+ ? {
+ agentId: identity.connectionId,
+ agentName: identity.displayName,
+ clientName: identity.clientInfo?.name,
+ colorSeed: identity.colorSeed,
+ }
+ : {};
+}
export const ROUTED_CWD_DESCRIPTION =
'Absolute host path inside the target Open Knowledge 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).';
@@ -18,6 +30,67 @@ export const summaryArgSchema = z
'Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.',
);
+export const VERSION_FIELD_DESCRIBE =
+ 'A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.';
+
+export const versionInputSchema = z
+ .string()
+ .length(40)
+ .regex(/^[0-9a-f]+$/i)
+ .describe(VERSION_FIELD_DESCRIBE);
+
+export const previewUrlOutputField = z
+ .string()
+ .nullable()
+ .describe('Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running.');
+
+export const previewUrlSourceField = z
+ .string()
+ .optional()
+ .describe('How the previewUrl was resolved (e.g. the UI lock).');
+
+export const previousPreviewUrlField = z
+ .string()
+ .optional()
+ .describe('Route of the prior/removed path, for closing a stale preview tab.');
+
+export const summaryOutputSchema = z
+ .object({
+ value: z.string(),
+ truncatedFrom: z.number().optional(),
+ hint: z.string().optional(),
+ })
+ .describe('Normalized change-note summary, when one was recorded.');
+
+export const looseObjectArray = z.array(z.record(z.string(), z.unknown()));
+
+export const previewAttachWarningField = z
+ .record(z.string(), z.unknown())
+ .optional()
+ .describe('Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant.');
+
+export const documentResultBaseShape = {
+ summary: summaryOutputSchema.optional(),
+ contentDivergence: WriteWarningSchema.optional().describe(
+ "Present when the converged Y.Text didn't byte-match the bytes you composed, or when an out-of-band disk edit was reconciled in before your write landed.",
+ ),
+} as const;
+
+export function nestDocResult(
+ preview: { url: string; source: string } | null | undefined,
+ warning: Record<string, unknown> | undefined,
+ docFields: Record<string, unknown>,
+): Record<string, unknown> {
+ const structured: Record<string, unknown> = {};
+ if (preview) {
+ structured.previewUrl = preview.url;
+ structured.previewUrlSource = preview.source;
+ }
+ if (warning) structured.warning = warning;
+ if (Object.keys(docFields).length > 0) structured.document = docFields;
+ return structured;
+}
+
export function textResult(text: string, isError?: boolean) {
return {
content: [{ type: 'text' as const, text }],
@@ -89,7 +162,7 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
- **Wiki, provisional** — \`research\`
- **Wiki, canonical** — \`consolidate\`
-(Project-level folder structure: \`ok seed\` for fresh repos with the Karpathy three-layer; \`discover\` MCP tool for existing-content repos that need conventions extracted from siblings. Neither is required — these three tools work against any folder structure the project already uses.)
+(Project-level folder structure: \`ok seed\` for fresh repos with the Karpathy three-layer; \`workflow({ kind: "discover" })\` for existing-content repos that need conventions extracted from siblings. Neither is required — these three tools work against any folder structure the project already uses.)
**This tool operates in the ${ROLE_LABEL[role]}.**
@@ -183,7 +256,7 @@ export function normalizeDocName(
if (lower.endsWith('.markdown')) {
return {
ok: false,
- error: `Error: docName "${raw}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`,
+ error: `Error: "${raw}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`,
};
}
let candidate = raw;
@@ -194,7 +267,7 @@ export function normalizeDocName(
}
const validation = validateDocName(candidate);
if (!validation.ok) {
- return { ok: false, error: `Error: docName "${raw}" is invalid — ${validation.reason}.` };
+ return { ok: false, error: `Error: "${raw}" is invalid — ${validation.reason}.` };
}
return { ok: true, docName: candidate };
}
diff --git a/packages/server/src/mcp/tools/summary-passthrough.test.ts b/packages/server/src/mcp/tools/summary-passthrough.test.ts
index 43ac9adfd..f5986d094 100644
--- a/packages/server/src/mcp/tools/summary-passthrough.test.ts
+++ b/packages/server/src/mcp/tools/summary-passthrough.test.ts
@@ -16,11 +16,11 @@ import { resolve } from 'node:path';
import type { z } from 'zod';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { AgentIdentity } from '../agent-identity.ts';
-import { register as registerEditDocument } from './edit-document.ts';
-import { register as registerRename } from './rename.ts';
+import { register as registerEdit } from './edit.ts';
+import { register as registerMove } from './move.ts';
+import { register as registerRestoreVersion } from './restore-version.ts';
import type { ServerInstance } from './shared.ts';
-import { register as registerVersion } from './version.ts';
-import { register as registerWriteDocument } from './write-document.ts';
+import { register as registerWrite } from './write.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({});
@@ -36,9 +36,6 @@ function createCaptureServer() {
const tools: Array<{
name: string;
description: string;
- /** Raw Zod schema object captured at register() time — exposed so
- * transport-safety tests can exercise the real Zod runtime guard
- * rather than a passthrough. */
schema: Record<string, z.ZodType>;
handler: Handler;
}> = [];
@@ -135,18 +132,13 @@ function baseDeps() {
};
}
-describe('US-005 — summary + identityRef passthrough across MCP write tools', () => {
- describe('write_document', () => {
+describe('summary + identityRef passthrough across MCP write-path tools', () => {
+ describe('write', () => {
test('summary is forwarded in the HTTP body when present', async () => {
const cap = createCaptureServer();
- registerWriteDocument(cap.server, {
- ...baseDeps(),
- identityRef: { current: TEST_IDENTITY },
- });
- await cap.getTool('write_document').handler({
- docName: 'foo',
- markdown: '# hi',
- position: 'append',
+ registerWrite(cap.server, { ...baseDeps(), identityRef: { current: TEST_IDENTITY } });
+ await cap.getTool('write').handler({
+ document: { path: 'foo', content: '# hi', position: 'append' },
summary: 'Fixed typo',
});
expect(recordedRequest?.body.summary).toBe('Fixed typo');
@@ -155,11 +147,9 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
test('summary omitted from body when arg is undefined', async () => {
const cap = createCaptureServer();
- registerWriteDocument(cap.server, baseDeps());
- await cap.getTool('write_document').handler({
- docName: 'foo',
- markdown: '# hi',
- position: 'append',
+ registerWrite(cap.server, baseDeps());
+ await cap.getTool('write').handler({
+ document: { path: 'foo', content: '# hi', position: 'append' },
});
expect(recordedRequest?.body).not.toHaveProperty('summary');
});
@@ -173,14 +163,14 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
},
};
const cap = createCaptureServer();
- registerWriteDocument(cap.server, baseDeps());
- const result = await cap.getTool('write_document').handler({
- docName: 'foo',
- markdown: '# hi',
- position: 'append',
+ registerWrite(cap.server, baseDeps());
+ const result = await cap.getTool('write').handler({
+ document: { path: 'foo', content: '# hi', position: 'append' },
summary: 'x'.repeat(200),
});
- expect(result.structuredContent?.summary).toEqual({
+ expect(
+ (result.structuredContent?.document as { summary?: unknown } | undefined)?.summary,
+ ).toEqual({
value: 'fixed',
truncatedFrom: 200,
hint: 'Summary truncated from 200 chars to 80 (max 80).',
@@ -190,13 +180,13 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
test('Zod schema: summary 200 chars accepted, 201 chars rejected, non-string rejected', () => {
const cap = createCaptureServer();
- registerWriteDocument(cap.server, baseDeps());
- const summarySchema = cap.getTool('write_document').schema.summary;
- if (!summarySchema) throw new Error('summary schema missing from write_document');
+ registerWrite(cap.server, baseDeps());
+ const summarySchema = cap.getTool('write').schema.summary;
+ if (!summarySchema) throw new Error('summary schema missing from write');
expect(summarySchema.safeParse('x'.repeat(200)).success).toBe(true);
expect(summarySchema.safeParse('short').success).toBe(true);
- expect(summarySchema.safeParse(undefined).success).toBe(true); // optional()
+ expect(summarySchema.safeParse(undefined).success).toBe(true);
const over = summarySchema.safeParse('x'.repeat(201));
expect(over.success).toBe(false);
@@ -211,12 +201,10 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
test('200-char summary passes through to HTTP body unchanged (server-side truncation, not MCP)', async () => {
const cap = createCaptureServer();
- registerWriteDocument(cap.server, baseDeps());
+ registerWrite(cap.server, baseDeps());
const input = 'x'.repeat(200);
- const result = await cap.getTool('write_document').handler({
- docName: 'foo',
- markdown: 'hi',
- position: 'append',
+ const result = await cap.getTool('write').handler({
+ document: { path: 'foo', content: 'hi', position: 'append' },
summary: input,
});
expect(recordedRequest?.body.summary).toBe(input);
@@ -224,17 +212,12 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
});
});
- describe('edit_document', () => {
+ describe('edit', () => {
test('summary + identityRef flow through to /api/agent-patch', async () => {
const cap = createCaptureServer();
- registerEditDocument(cap.server, {
- ...baseDeps(),
- identityRef: { current: TEST_IDENTITY },
- });
- await cap.getTool('edit_document').handler({
- docName: 'foo',
- find: 'old',
- replace: 'new',
+ registerEdit(cap.server, { ...baseDeps(), identityRef: { current: TEST_IDENTITY } });
+ await cap.getTool('edit').handler({
+ document: { path: 'foo', find: 'old', replace: 'new' },
summary: 'Renamed constant',
});
expect(recordedRequest?.url).toBe('/api/agent-patch');
@@ -243,27 +226,26 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
});
});
- describe('rename — FR11 description sentinel', () => {
- test('description mentions the default substitution sentence', async () => {
+ describe('move — description sentinel', () => {
+ test('description mentions the default substitution sentence', () => {
const cap = createCaptureServer();
- registerRename(cap.server, baseDeps());
- const desc = cap.getTool('rename').description;
+ registerMove(cap.server, baseDeps());
+ const desc = cap.getTool('move').description;
expect(desc).toContain('If omitted');
expect(desc).toContain('Renamed X → Y');
});
});
- describe('version (rollback action) — D15 identity passthrough', () => {
+ describe('restore_version — identity passthrough', () => {
test('identityRef when present puts agentId in the /api/rollback body', async () => {
const cap = createCaptureServer();
- registerVersion(cap.server, {
+ registerRestoreVersion(cap.server, {
...baseDeps(),
identityRef: { current: TEST_IDENTITY },
});
- await cap.getTool('version').handler({
- action: 'rollback',
- docName: 'foo',
- commitSha: 'a'.repeat(40),
+ await cap.getTool('restore_version').handler({
+ document: 'foo',
+ version: 'a'.repeat(40),
});
expect(recordedRequest?.url).toBe('/api/rollback');
expect(recordedRequest?.body.agentId).toBe('claude-1');
@@ -271,59 +253,49 @@ describe('US-005 — summary + identityRef passthrough across MCP write tools',
test('no identityRef → body omits agentId (UI-style anonymous call)', async () => {
const cap = createCaptureServer();
- registerVersion(cap.server, baseDeps());
- await cap.getTool('version').handler({
- action: 'rollback',
- docName: 'foo',
- commitSha: 'a'.repeat(40),
+ registerRestoreVersion(cap.server, baseDeps());
+ await cap.getTool('restore_version').handler({
+ document: 'foo',
+ version: 'a'.repeat(40),
});
expect(recordedRequest?.body).not.toHaveProperty('agentId');
});
test('summary is forwarded when provided', async () => {
const cap = createCaptureServer();
- registerVersion(cap.server, {
+ registerRestoreVersion(cap.server, {
...baseDeps(),
identityRef: { current: TEST_IDENTITY },
});
- await cap.getTool('version').handler({
- action: 'rollback',
- docName: 'foo',
- commitSha: 'a'.repeat(40),
+ await cap.getTool('restore_version').handler({
+ document: 'foo',
+ version: 'a'.repeat(40),
summary: 'Reverted risky refactor',
});
expect(recordedRequest?.body.summary).toBe('Reverted risky refactor');
});
-
- test('description mentions the default substitution sentence (FR11)', async () => {
- const cap = createCaptureServer();
- registerVersion(cap.server, baseDeps());
- const desc = cap.getTool('version').description;
- expect(desc).toContain('If omitted');
- expect(desc).toContain('Restored to');
- });
});
- describe('No-PII reminder in all five tool descriptions (FR15)', () => {
- test('write_document description mentions no secrets/PII', () => {
+ describe('No-PII reminder in the write-path tool descriptions', () => {
+ test('write description mentions no secrets/PII', () => {
const cap = createCaptureServer();
- registerWriteDocument(cap.server, baseDeps());
- expect(cap.getTool('write_document').description).toContain('secrets or PII');
+ registerWrite(cap.server, baseDeps());
+ expect(cap.getTool('write').description).toContain('secrets or PII');
});
- test('edit_document description mentions no secrets/PII', () => {
+ test('edit description mentions no secrets/PII', () => {
const cap = createCaptureServer();
- registerEditDocument(cap.server, baseDeps());
- expect(cap.getTool('edit_document').description).toContain('secrets or PII');
+ registerEdit(cap.server, baseDeps());
+ expect(cap.getTool('edit').description).toContain('secrets or PII');
});
- test('rename description mentions no secrets/PII', () => {
+ test('move description mentions no secrets/PII', () => {
const cap = createCaptureServer();
- registerRename(cap.server, baseDeps());
- expect(cap.getTool('rename').description).toContain('secrets or PII');
+ registerMove(cap.server, baseDeps());
+ expect(cap.getTool('move').description).toContain('secrets or PII');
});
- test('version (rollback action) description mentions no secrets/PII', () => {
+ test('restore_version description mentions no secrets/PII', () => {
const cap = createCaptureServer();
- registerVersion(cap.server, baseDeps());
- expect(cap.getTool('version').description).toContain('secrets or PII');
+ registerRestoreVersion(cap.server, baseDeps());
+ expect(cap.getTool('restore_version').description).toContain('secrets or PII');
});
});
});
diff --git a/packages/server/src/mcp/tools/templates-input-strictness.test.ts b/packages/server/src/mcp/tools/templates-input-strictness.test.ts
deleted file mode 100644
index 22f8a9933..000000000
--- a/packages/server/src/mcp/tools/templates-input-strictness.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import {
- normalizeObjectSchema,
- safeParseAsync,
-} from '@modelcontextprotocol/sdk/server/zod-compat.js';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { register as registerFolderConfig } from './folder-config.ts';
-import type { ServerInstance } from './shared.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-function captureInputSchema<TDeps>(
- register: (server: ServerInstance, deps: TDeps) => void,
- deps: TDeps,
-): { inputSchema: unknown } {
- let captured: { inputSchema: unknown } | null = null;
- const server = {
- registerTool(_name: string, cfg: { inputSchema?: unknown }, _handler: unknown) {
- captured = { inputSchema: cfg.inputSchema };
- },
- tool() {
- throw new Error('not used');
- },
- } as unknown as ServerInstance;
- register(server, deps);
- if (!captured) throw new Error('tool did not register');
- return captured;
-}
-
-function newProject(): string {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-folder-config-strict-'));
- mkdirSync(join(cwd, '.ok'), { recursive: true });
- return cwd;
-}
-
-async function parseArgs(
- inputSchema: unknown,
- args: Record<string, unknown>,
-): Promise<{ success: boolean; errorText: string }> {
- const normalized = normalizeObjectSchema(
- inputSchema as Parameters<typeof normalizeObjectSchema>[0],
- );
- if (!normalized) throw new Error('inputSchema did not normalize to an object schema');
- const result = await safeParseAsync(normalized, args);
- if (result.success) return { success: true, errorText: '' };
- const errAny = (result as { error?: unknown }).error;
- const errorText =
- errAny && typeof errAny === 'object' && 'message' in errAny
- ? String((errAny as { message: unknown }).message)
- : JSON.stringify(errAny);
- return { success: false, errorText };
-}
-
-describe('folder_config (action=write-template) — branch InputSchema strictness', () => {
- const baseDeps = { config: BASE_CONFIG, resolveCwd: async () => newProject() };
- const validArgs = {
- action: 'write-template',
- folder: '',
- name: 'foo',
- body: '# hello',
- frontmatter: { title: 'Hello' },
- };
-
- test('accepts a well-formed args payload', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, validArgs);
- expect(result.errorText).toBe('');
- expect(result.success).toBe(true);
- });
-
- test('rejects stale `target: "user"` with an unrecognized-key error', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, target: 'user' });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/target/i);
- });
-
- test('rejects stale `target: "project"` — the entire `target` field is gone', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, target: 'project' });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/target/);
- });
-
- test('rejects any unknown key (defense-in-depth — not just `target`)', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, somethingElse: 1 });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/somethingElse/);
- });
-});
-
-describe('folder_config (action=delete-template) — branch InputSchema strictness', () => {
- const baseDeps = { config: BASE_CONFIG, resolveCwd: async () => newProject() };
- const validArgs = { action: 'delete-template', folder: '', name: 'foo' };
-
- test('accepts a well-formed args payload', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, validArgs);
- expect(result.errorText).toBe('');
- expect(result.success).toBe(true);
- });
-
- test('rejects stale `target: "user"` with an unrecognized-key error', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, target: 'user' });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/target/i);
- });
-
- test('rejects stale `target: "project"` — the entire `target` field is gone', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, target: 'project' });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/target/);
- });
-
- test('rejects any unknown key (defense-in-depth — not just `target`)', async () => {
- const { inputSchema } = captureInputSchema(registerFolderConfig, baseDeps);
- const result = await parseArgs(inputSchema, { ...validArgs, somethingElse: 1 });
- expect(result.success).toBe(false);
- expect(result.errorText).toMatch(/somethingElse/);
- });
-});
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
new file mode 100644
index 000000000..9db368965
--- /dev/null
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -0,0 +1,64 @@
+import { FrontmatterValueSchema } from '@inkeep/open-knowledge-core';
+import { z } from 'zod';
+
+const FrontmatterPatchValue = z.union([FrontmatterValueSchema, z.null()]);
+
+export const FrontmatterArg = z
+ .record(z.string(), FrontmatterPatchValue)
+ .describe(
+ 'Metadata as a flat key→value map (string | number | boolean | string[]). ' +
+ 'Merge-patch: include a key to set it, set a key to null to delete it; keys you omit are unchanged. ' +
+ 'Example: { title: "Q3 Planning", tags: ["planning"], status: "draft" }.',
+ );
+
+const POSITIONS = ['append', 'prepend', 'replace'] as const;
+export const PositionArg = z
+ .enum(POSITIONS)
+ .describe(
+ 'Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). ' +
+ 'append / prepend = add to the end / start.',
+ );
+
+export function splitTargetPath(path: string): { folder: string; name: string } {
+ const clean = path.replace(/^\/+/, '').replace(/\/+$/, '');
+ const idx = clean.lastIndexOf('/');
+ return idx === -1
+ ? { folder: '', name: clean }
+ : { folder: clean.slice(0, idx), name: clean.slice(idx + 1) };
+}
+
+const TEMPLATE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;
+export const TEMPLATE_PATH_DESCRIBE =
+ 'Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.';
+export const TEMPLATE_CONTENT_DESCRIBE =
+ 'Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.';
+
+export function resolveTemplatePath(
+ path: string,
+): { ok: true; folder: string; name: string } | { ok: false; error: string } {
+ const { folder, name } = splitTargetPath(path);
+ if (!TEMPLATE_NAME_REGEX.test(name)) {
+ return {
+ ok: false,
+ error: `the final segment of a template path is its name — "${name}" must be letters, digits, \`_\`, \`-\` only (no dots/spaces). e.g. { template: { path: "fishing-log/trip-log" } }.`,
+ };
+ }
+ return { ok: true, folder, name };
+}
+
+export function exactlyOneTargetError(
+ args: Record<string, unknown>,
+ keys: readonly string[],
+): string | null {
+ const present = keys.filter((k) => args[k] !== undefined);
+ if (present.length === 1) return null;
+ const quoted = keys.map((k) => `\`${k}\``).join(', ');
+ if (present.length === 0) {
+ return (
+ `Name exactly one of ${quoted} — the one thing you are addressing. ` +
+ "Nest that target's fields under its key (e.g. `{ document: { path, … } }`); " +
+ "see this tool's parameter docs for which fields each target takes."
+ );
+ }
+ return `You named ${present.map((k) => `\`${k}\``).join(' and ')} — name exactly ONE target.`;
+}
diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.ts
new file mode 100644
index 000000000..c5814009f
--- /dev/null
+++ b/packages/server/src/mcp/tools/verb-tools.test.ts
@@ -0,0 +1,236 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parse as parseYaml } from 'yaml';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { register as registerDelete } from './delete.ts';
+import { register as registerEdit } from './edit.ts';
+import type { ServerInstance } from './shared.ts';
+import { register as registerWrite } from './write.ts';
+
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+
+interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: true;
+}
+type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;
+
+function capture<D>(register: (server: ServerInstance, deps: D) => void, cwd: string): Handler {
+ let handler: Handler | undefined;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, h: Handler) {
+ handler = h;
+ },
+ } as unknown as ServerInstance;
+ register(server, {
+ serverUrl: undefined,
+ config: BASE_CONFIG,
+ resolveCwd: async () => cwd,
+ } as unknown as D);
+ if (!handler) throw new Error('tool did not register');
+ return handler;
+}
+
+function newProject(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-verb-tools-'));
+}
+
+function textOf(r: ToolResult): string {
+ return r.content.map((c) => c.text).join('\n');
+}
+
+describe('write — exactly-one-target teaching error (D8/D9 mitigation)', () => {
+ test('zero targets returns the corrective shape', async () => {
+ const write = capture(registerWrite, newProject());
+ const r = await write({});
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('Name exactly one of');
+ expect(textOf(r)).toContain('document'); // the corrective example names the targets
+ });
+
+ test('two targets returns a "name exactly ONE" error', async () => {
+ const write = capture(registerWrite, newProject());
+ const r = await write({ document: { path: 'a', content: '# a' }, folder: { path: 'b' } });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toMatch(/name exactly ONE/i);
+ expect(textOf(r)).toContain('document');
+ expect(textOf(r)).toContain('folder');
+ });
+});
+
+describe('edit — body-XOR-frontmatter + exactly-one-target teaching errors', () => {
+ test('find without replace teaches the corrective shape', async () => {
+ const edit = capture(registerEdit, newProject());
+ const r = await edit({ document: { path: 'a', find: 'x' } });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('`find` needs a `replace`');
+ });
+
+ test('body + frontmatter in one call is rejected', async () => {
+ const edit = capture(registerEdit, newProject());
+ const r = await edit({
+ document: { path: 'a', find: 'x', replace: 'y', frontmatter: { t: 1 } },
+ });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toMatch(/Pick ONE/i);
+ });
+
+ test('zero targets teaches exactly-one-target', async () => {
+ const edit = capture(registerEdit, newProject());
+ const r = await edit({});
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('Name exactly one of');
+ });
+});
+
+describe('delete — exactly-one-target teaching error', () => {
+ test('two targets rejected', async () => {
+ const del = capture(registerDelete, newProject());
+ const r = await del({ document: 'a', folder: 'b' });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toMatch(/name exactly ONE/i);
+ });
+});
+
+describe('edit({ folder }) — fs-direct round-trip to <folder>/.ok/frontmatter.yml', () => {
+ test('sets, then merge-patches, then clears the folder frontmatter file', async () => {
+ const cwd = newProject();
+ const edit = capture(registerEdit, cwd);
+ const fmPath = join(cwd, 'meetings', '.ok', 'frontmatter.yml');
+
+ let r = await edit({
+ folder: { path: 'meetings', frontmatter: { title: 'Meetings', tags: ['m'] } },
+ });
+ expect(r.isError).toBeUndefined();
+ expect(existsSync(fmPath)).toBe(true);
+ expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({ title: 'Meetings', tags: ['m'] });
+
+ r = await edit({ folder: { path: 'meetings', frontmatter: { description: 'All-hands' } } });
+ expect(r.isError).toBeUndefined();
+ expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({
+ title: 'Meetings',
+ tags: ['m'],
+ description: 'All-hands',
+ });
+
+ r = await edit({ folder: { path: 'meetings', frontmatter: { tags: null } } });
+ expect(r.isError).toBeUndefined();
+ expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual({
+ title: 'Meetings',
+ description: 'All-hands',
+ });
+
+ r = await edit({ folder: { path: 'meetings', frontmatter: {} } });
+ expect(r.isError).toBeUndefined();
+ expect(existsSync(fmPath)).toBe(false);
+ });
+
+ test('the on-disk shape has no glob/match key (the fossil is gone)', async () => {
+ const cwd = newProject();
+ const edit = capture(registerEdit, cwd);
+ await edit({ folder: { path: 'specs', frontmatter: { title: 'Specs' } } });
+ const parsed = parseYaml(readFileSync(join(cwd, 'specs', '.ok', 'frontmatter.yml'), 'utf-8'));
+ expect(parsed).not.toHaveProperty('match');
+ expect(parsed).not.toHaveProperty('rules');
+ });
+});
+
+describe('write/edit/delete({ template }) — fs-direct round-trip', () => {
+ test('create → body edit → frontmatter patch → delete', async () => {
+ const cwd = newProject();
+ const write = capture(registerWrite, cwd);
+ const edit = capture(registerEdit, cwd);
+ const del = capture(registerDelete, cwd);
+ const tplPath = join(cwd, 'fishing-log', '.ok', 'templates', 'trip-log.md');
+
+ let r = await write({
+ template: {
+ path: 'fishing-log/trip-log',
+ content: '# {{date}}\n\nCatch: \n',
+ frontmatter: { title: 'Trip Log' },
+ },
+ });
+ expect(r.isError).toBeUndefined();
+ expect(existsSync(tplPath)).toBe(true);
+ expect(readFileSync(tplPath, 'utf-8')).toContain('Catch:');
+
+ r = await edit({
+ template: { path: 'fishing-log/trip-log', find: 'Catch:', replace: 'Total catch:' },
+ });
+ expect(r.isError).toBeUndefined();
+ expect(readFileSync(tplPath, 'utf-8')).toContain('Total catch:');
+ expect(readFileSync(tplPath, 'utf-8')).toContain('Trip Log');
+
+ r = await edit({
+ template: {
+ path: 'fishing-log/trip-log',
+ frontmatter: { description: 'one per trip' },
+ },
+ });
+ expect(r.isError).toBeUndefined();
+ expect(readFileSync(tplPath, 'utf-8')).toContain('description: one per trip');
+
+ r = await del({ template: { path: 'fishing-log/trip-log' } });
+ expect(r.isError).toBeUndefined();
+ expect(existsSync(tplPath)).toBe(false);
+ });
+
+ test('invalid template name is rejected by the name grammar', async () => {
+ const cwd = newProject();
+ const write = capture(registerWrite, cwd);
+ const r = await write({
+ template: { path: 'x/a.b', content: 'ok', frontmatter: { title: 'A' } },
+ });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('must be letters, digits');
+ expect(existsSync(join(cwd, 'x', '.ok', 'templates', 'a.b.md'))).toBe(false);
+ });
+});
+
+describe('D13 migration meta-test — no retired tool name survives in the skill surface', () => {
+ const RETIRED = [
+ 'write_document',
+ 'edit_document',
+ 'edit_frontmatter',
+ 'delete_document',
+ 'folder_config',
+ 'set_folder_rule',
+ 'write_template',
+ 'delete_template',
+ 'rename_document',
+ 'rename_folder',
+ 'get_history',
+ 'get_config',
+ 'get_preview_url',
+ 'get_components',
+ 'get_authoring_palette',
+ 'list_conflicts',
+ 'get_conflict_content',
+ ];
+
+ function mdFiles(dir: string): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry);
+ if (statSync(p).isDirectory()) out.push(...mdFiles(p));
+ else if (entry.endsWith('.md') || entry.endsWith('.mdx')) out.push(p);
+ }
+ return out;
+ }
+
+ test('packages/server/assets/skills/** teaches only the verb surface', () => {
+ const skillsDir = fileURLToPath(new URL('../../../assets/skills', import.meta.url));
+ const offenders: string[] = [];
+ for (const file of mdFiles(skillsDir)) {
+ const body = readFileSync(file, 'utf-8');
+ for (const name of RETIRED) {
+ if (body.includes(name)) offenders.push(`${file}: ${name}`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/packages/server/src/mcp/tools/version.test.ts b/packages/server/src/mcp/tools/version.test.ts
deleted file mode 100644
index e92ec6318..000000000
--- a/packages/server/src/mcp/tools/version.test.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-import {
- describe as _bunDescribe,
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- expect,
- test,
-} from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
-import type { ServerInstance } from './shared.ts';
-import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
-import { DESCRIPTION, register, type VersionDeps } from './version.ts';
-
-const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-const SHA = '0123456789abcdef0123456789abcdef01234567';
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: boolean;
-}
-
-interface VersionHandlerArgs {
- action: 'save' | 'rollback';
- docName?: string;
- commitSha?: string;
- summary?: string;
-}
-
-interface RegisteredTool {
- name: string;
- description: string;
- schema: Record<string, unknown>;
- handler: (args: VersionHandlerArgs) => Promise<ToolResult>;
-}
-
-function createFakeServer() {
- let registered: RegisteredTool | undefined;
- const server = {
- registerTool(
- name: string,
- cfg: { description?: string; inputSchema?: Record<string, unknown> },
- handler: (args: VersionHandlerArgs) => Promise<ToolResult>,
- ) {
- registered = {
- name,
- description: cfg.description ?? '',
- schema: cfg.inputSchema ?? {},
- handler,
- };
- },
- } as unknown as ServerInstance;
- return {
- server,
- getTool(): RegisteredTool {
- if (!registered) throw new Error('Tool was not registered');
- return registered;
- },
- };
-}
-
-function makeDeps(serverUrl: string | undefined, cwdDir: string): VersionDeps {
- return {
- serverUrl,
- config: BASE_CONFIG,
- resolveCwd: async () => cwdDir,
- };
-}
-
-let testServer: ReturnType<typeof Bun.serve>;
-let baseUrl: string;
-let tmpDir: string;
-const seenRequests: string[] = [];
-const seenBodies: Array<Record<string, unknown>> = [];
-let mockRollbackWarning: Record<string, unknown> | undefined;
-
-beforeAll(() => {
- testServer = Bun.serve({
- port: 0,
- async fetch(req) {
- const url = new URL(req.url);
- const body = req.method === 'POST' ? ((await req.json()) as Record<string, unknown>) : {};
- seenRequests.push(`${req.method} ${url.pathname}`);
- if (req.method === 'POST') seenBodies.push(body);
-
- if (url.pathname === '/api/save-version' && req.method === 'POST') {
- return Response.json({
- ok: true,
- checkpointRef: 'refs/checkpoints/2026-05-20-deadbeef',
- });
- }
- if (url.pathname.startsWith('/api/history/') && req.method === 'GET') {
- return Response.json({
- ok: true,
- author: 'Alice',
- timestamp: '2026-05-20T00:00:00Z',
- });
- }
- if (url.pathname === '/api/rollback' && req.method === 'POST') {
- const summary = body.summary;
- const summaryShape =
- summary === undefined ? undefined : { value: String(summary), hint: 'summary recorded' };
- return Response.json({
- ok: true,
- ...(summaryShape ? { summary: summaryShape } : {}),
- ...(mockRollbackWarning !== undefined ? { warning: mockRollbackWarning } : {}),
- });
- }
- return new Response('Not found', { status: 404 });
- },
- });
- baseUrl = `http://localhost:${testServer.port}`;
-});
-
-afterAll(() => {
- testServer.stop();
-});
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-version-test-'));
- seenRequests.length = 0;
- seenBodies.length = 0;
- mockRollbackWarning = undefined;
-});
-
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-describe('version — registration + DESCRIPTION', () => {
- test('registers exactly one tool named "version"', () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- expect(getTool().name).toBe('version');
- });
-
- test('DESCRIPTION enumerates both actions and their semantics', () => {
- expect(DESCRIPTION).toContain('action: "save"');
- expect(DESCRIPTION).toContain('action: "rollback"');
- expect(DESCRIPTION).toContain('docName');
- expect(DESCRIPTION).toContain('commitSha');
- expect(DESCRIPTION).toContain('get_history');
- });
-
- test('returns Hocuspocus-unavailable error when no serverUrl is configured', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(undefined, tmpDir));
- const result = await getTool().handler({ action: 'save' });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);
- });
-});
-
-describe('version — action=save (project-wide checkpoint)', () => {
- test('hits POST /api/save-version with no doc parameter and returns checkpointRef + null previewUrl', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- const result = await getTool().handler({ action: 'save' });
-
- expect(seenRequests).toContain('POST /api/save-version');
- expect(result.structuredContent).toMatchObject({
- checkpointRef: 'refs/checkpoints/2026-05-20-deadbeef',
- previewUrl: null,
- });
- expect(result.content[0]?.text).toContain('Checkpoint saved');
- });
-
- test('save body is empty when no identity is provided', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- await getTool().handler({ action: 'save' });
- expect(seenBodies[0]).toEqual({});
- });
-
- test('save body includes writers array when identity is provided', async () => {
- const { server, getTool } = createFakeServer();
- register(server, {
- ...makeDeps(baseUrl, tmpDir),
- identityRef: {
- current: {
- connectionId: 'conn-42',
- displayName: 'Agent 42',
- colorSeed: 'seed-0',
- clientInfo: { name: 'claude', version: '1.0.0' },
- },
- },
- });
- await getTool().handler({ action: 'save' });
- expect(seenBodies[0]).toEqual({
- writers: [
- {
- id: 'agent-conn-42',
- name: 'Agent 42',
- email: '[email protected]',
- },
- ],
- });
- });
-});
-
-describe('version — action=rollback (per-doc restore)', () => {
- test('verifies version exists, posts rollback, returns route-only previewUrl on resolved doc', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- const result = await getTool().handler({
- action: 'rollback',
- docName: 'notes',
- commitSha: SHA,
- });
-
- expect(seenRequests).toContain(`GET /api/history/${SHA}`);
- expect(seenRequests).toContain('POST /api/rollback');
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/notes',
- previewUrlSource: 'lock',
- });
- expect(result.content[0]?.text).toContain('Restored "notes"');
- expect(result.content[0]?.text).toContain('01234567');
- });
-
- test('relays a rollback content-divergence warning as structuredContent.contentDivergence + a text line', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- mockRollbackWarning = {
- kind: 'content-divergence',
- intendedBytes: 40,
- actualBytes: 33,
- byteDelta: -7,
- divergenceType: 'rollback-content-mismatch',
- currentState: { kind: 'inline', content: 'restored body bytes\n' },
- hint: 'currentState carries the converged content.',
- };
-
- const result = await getTool().handler({
- action: 'rollback',
- docName: 'notes',
- commitSha: SHA,
- });
-
- expect(result.structuredContent?.contentDivergence).toMatchObject({
- kind: 'content-divergence',
- byteDelta: -7,
- divergenceType: 'rollback-content-mismatch',
- currentState: { kind: 'inline', content: 'restored body bytes\n' },
- });
- expect(result.content[0]?.text).toContain('⚠ Content divergence');
- });
-
- test('drops a malformed rollback warning at the safeParse boundary', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- mockRollbackWarning = {
- kind: 'content-divergence',
- intendedBytes: 40,
- actualBytes: 33,
- byteDelta: 'minus seven',
- };
-
- const result = await getTool().handler({
- action: 'rollback',
- docName: 'notes',
- commitSha: SHA,
- });
-
- expect(result.structuredContent?.contentDivergence).toBeUndefined();
- expect(result.content[0]?.text).not.toContain('⚠ Content divergence');
- });
-
- test('normalizes trailing .md from docName before history + rollback requests', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- await getTool().handler({
- action: 'rollback',
- docName: 'notes.md',
- commitSha: SHA,
- });
-
- expect(seenBodies[0]).toMatchObject({ docName: 'notes', commitSha: SHA });
- });
-
- test('rejects missing docName at the handler level', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- const result = await getTool().handler({ action: 'rollback', commitSha: SHA });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('action=rollback requires `docName`');
- });
-
- test('rejects missing commitSha at the handler level', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- const result = await getTool().handler({ action: 'rollback', docName: 'notes' });
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('action=rollback requires `commitSha`');
- });
-
- test('passes summary through to /api/rollback and surfaces server summary hint in result text', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
-
- const result = await getTool().handler({
- action: 'rollback',
- docName: 'notes',
- commitSha: SHA,
- summary: 'undo Friday merge',
- });
-
- expect(seenBodies[0]?.summary).toBe('undo Friday merge');
- expect(result.content[0]?.text).toContain('summary recorded');
- expect(result.structuredContent?.summary).toMatchObject({ value: 'undo Friday merge' });
- });
-
- test('rollback body includes identity attribution when identityRef is provided', async () => {
- const { server, getTool } = createFakeServer();
- register(server, {
- ...makeDeps(baseUrl, tmpDir),
- identityRef: {
- current: {
- connectionId: 'conn-7',
- displayName: 'Cody',
- colorSeed: 'seed-12',
- clientInfo: { name: 'claude', version: '1.0.0' },
- },
- },
- });
-
- await getTool().handler({
- action: 'rollback',
- docName: 'notes',
- commitSha: SHA,
- });
-
- expect(seenBodies[0]).toMatchObject({
- docName: 'notes',
- commitSha: SHA,
- agentId: 'conn-7',
- agentName: 'Cody',
- clientName: 'claude',
- colorSeed: 'seed-12',
- });
- });
-
- test('commitSha schema rejects malformed values and accepts a 40-hex SHA', () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps(baseUrl, tmpDir));
- const commitSha = getTool().schema.commitSha as {
- safeParse: (value: unknown) => { success: boolean };
- };
- expect(commitSha.safeParse('abc123').success).toBe(false); // too short
- expect(commitSha.safeParse('z'.repeat(40)).success).toBe(false); // non-hex
- expect(commitSha.safeParse(`${SHA}00`).success).toBe(false); // too long
- expect(commitSha.safeParse(SHA).success).toBe(true); // valid 40-hex
- });
-});
diff --git a/packages/server/src/mcp/tools/version.ts b/packages/server/src/mcp/tools/version.ts
deleted file mode 100644
index 45e6099b5..000000000
--- a/packages/server/src/mcp/tools/version.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-import { WriteWarningSchema } from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { resolvePreviewUrlForTool } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpGet,
- httpPost,
- normalizeDocName,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- summaryArgSchema,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-const ACTIONS = ['save', 'rollback'] as const;
-type VersionAction = (typeof ACTIONS)[number];
-
-export const DESCRIPTION = [
- '[Requires: Hocuspocus server] Project version management. Dispatches on `action`:',
- '',
- '- `action: "save"` — Project-wide checkpoint of every document. No `docName`. Returns `{checkpointRef, previewUrl: null}`. Find checkpoints later via `get_history`.',
- '- `action: "rollback"` — Restore one document to a historical version via the CRDT layer (append-only — creates a new version with the old content; all connected editors see the change in real-time). Requires `docName` and `commitSha`. Find `commitSha` via `get_history`.',
- '',
- '**Parameters:**',
- '- `action` — `save` | `rollback`.',
- '- `docName` — Required for `rollback`. Document name, typically without extension; trailing `.md`/`.mdx` is stripped.',
- '- `commitSha` — Required for `rollback`. 40-character SHA from the shadow-repo timeline.',
- '- `summary` — Optional rollback summary (≤80 chars). If omitted, defaults to "Restored to <sha-short>". Avoid secrets or PII — summaries persist to git history.',
- '',
- 'A `rollback` response may include `structuredContent.contentDivergence` (`{kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint}`) when the restored `Y.Text` does not byte-match the target-version bytes. The rollback still landed; `currentState` carries the converged document inline (or a truncation marker over the soft cap), so you do NOT need to re-read.',
-].join('\n');
-
-export interface VersionDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- /** Identity passthrough. MCP-driven save + rollback both participate
- * in attribution via this ref; UI-driven counterparts stay anonymous. */
- identityRef?: { current: AgentIdentity };
-}
-
-interface VersionArgs {
- action: VersionAction;
- docName?: string;
- commitSha?: string;
- summary?: string;
- cwd?: string;
-}
-
-export function register(server: ServerInstance, deps: VersionDeps): void {
- server.registerTool(
- 'version',
- {
- description: DESCRIPTION,
- inputSchema: {
- action: z.enum(ACTIONS).describe('Which version action to perform.'),
- docName: z.string().optional().describe('Document name. Required for action=rollback.'),
- commitSha: z
- .string()
- .length(40)
- .regex(/^[0-9a-f]+$/i)
- .optional()
- .describe(
- '40-character commit SHA from the shadow-repo timeline. Required for action=rollback. Find via get_history.',
- ),
- summary: summaryArgSchema.describe(
- 'Optional rollback summary (≤80 chars). Defaults to "Restored to <sha-short>". Appears as a bullet in the timeline.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: VersionArgs) => {
- const context = await resolveProjectServerContext(
- deps.resolveCwd,
- deps.config,
- deps.serverUrl,
- args.cwd,
- );
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- const { cwd, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
-
- switch (args.action) {
- case 'save':
- return handleSave(url, deps);
- case 'rollback':
- return handleRollback(args, url, cwd, deps);
- default:
- return textResult('Error: unknown version action.', true);
- }
- },
- );
-}
-
-async function handleSave(url: string, deps: VersionDeps) {
- const identity = deps.identityRef?.current;
- const result = await httpPost(
- url,
- '/api/save-version',
- identity
- ? {
- writers: [
- {
- id: `agent-${identity.connectionId}`,
- name: identity.displayName,
- email: `agent-${identity.connectionId}@openknowledge.local`,
- },
- ],
- }
- : {},
- );
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
-
- return textPlusStructured(`Checkpoint saved. Checkpoint ref: ${result.checkpointRef}`, {
- checkpointRef: result.checkpointRef,
- previewUrl: null,
- });
-}
-
-async function handleRollback(args: VersionArgs, url: string, cwd: string, deps: VersionDeps) {
- if (!args.docName) {
- return textResult('Error: action=rollback requires `docName`.', true);
- }
- if (!args.commitSha) {
- return textResult('Error: action=rollback requires `commitSha`.', true);
- }
- const normalized = normalizeDocName(args.docName);
- if (!normalized.ok) return textResult(normalized.error, true);
- const docName = normalized.docName;
-
- const versionResult = await httpGet(
- url,
- `/api/history/${args.commitSha}?docName=${encodeURIComponent(docName)}`,
- );
- if (!versionResult.ok) {
- return textResult(`Error: ${versionResult.error ?? 'Version not found'}`, true);
- }
-
- const identity = deps.identityRef?.current;
- const result = await httpPost(url, '/api/rollback', {
- docName,
- commitSha: args.commitSha,
- ...(args.summary !== undefined ? { summary: args.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const writeWarningParse = WriteWarningSchema.safeParse(result.warning);
- const writeWarning = writeWarningParse.success ? writeWarningParse.data : undefined;
-
- const author = typeof versionResult.author === 'string' ? versionResult.author : undefined;
- const timestamp =
- typeof versionResult.timestamp === 'string' ? versionResult.timestamp : undefined;
- const provenance = author && timestamp ? ` (${author}, ${timestamp})` : '';
- const textLines = [
- `Restored "${docName}" to version ${args.commitSha.slice(0, 8)}${provenance}. The change has been applied to all connected editors.`,
- ];
- if (summaryHint) textLines.push(summaryHint);
- if (writeWarning) {
- textLines.push(
- writeWarning.kind === 'content-divergence'
- ? `⚠ Content divergence: ${writeWarning.actualBytes} actual bytes vs ${writeWarning.intendedBytes} intended (byteDelta=${writeWarning.byteDelta}). ${writeWarning.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
- : `⚠ ${writeWarning.hint ?? 'An out-of-band edit was reconciled into this document before your change landed on top — re-read for the combined result.'}`,
- );
- }
-
- const preview = await resolvePreviewUrlForTool(
- docName,
- {
- config: deps.config,
- resolveCwd: deps.resolveCwd,
- },
- cwd,
- );
- return textPlusStructured(textLines.join('\n'), {
- previewUrl: preview?.url ?? null,
- ...(preview ? { previewUrlSource: preview.source } : {}),
- ...(summaryResult ? { summary: summaryResult } : {}),
- ...(writeWarning ? { contentDivergence: writeWarning } : {}),
- });
-}
diff --git a/packages/server/src/mcp/tools/workflow.test.ts b/packages/server/src/mcp/tools/workflow.test.ts
new file mode 100644
index 000000000..961ad08b4
--- /dev/null
+++ b/packages/server/src/mcp/tools/workflow.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import type { ServerInstance } from './shared.ts';
+import { DESCRIPTION, register } from './workflow.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: string;
+ source?: string;
+ topic?: string;
+ cwd?: string;
+}) => Promise<ToolResult>;
+
+function capture(cwd: string): { name: string; handler: Handler } {
+ let captured: { name: string; handler: Handler } | undefined;
+ const server = {
+ registerTool(name: string, _cfg: unknown, handler: Handler) {
+ captured = { name, handler };
+ },
+ } as unknown as ServerInstance;
+ register(server, { config: BASE_CONFIG, resolveCwd: async () => cwd });
+ if (!captured) throw new Error('not registered');
+ return captured;
+}
+
+const cwd = mkdtempSync(join(tmpdir(), 'ok-workflow-test-'));
+const textOf = (r: ToolResult) => r.content.map((c) => c.text).join('\n');
+
+describe('workflow — kind discriminator + per-kind teaching errors', () => {
+ test('registers exactly one tool named "workflow"', () => {
+ expect(capture(cwd).name).toBe('workflow');
+ expect(DESCRIPTION).toContain('ingest');
+ expect(DESCRIPTION).toContain('discover');
+ });
+
+ test('kind:ingest with source returns the framed ingest plan', async () => {
+ const r = await capture(cwd).handler({ kind: 'ingest', source: 'https://example.com/spec' });
+ expect(r.isError).toBeFalsy();
+ expect(textOf(r)).toContain('Where this fits'); // the workflow frame
+ });
+
+ test('kind:research with topic returns a plan', async () => {
+ const r = await capture(cwd).handler({ kind: 'research', topic: 'rate limiting' });
+ expect(r.isError).toBeFalsy();
+ expect(textOf(r)).toContain('Where this fits');
+ });
+
+ test('kind:consolidate with topic returns a plan', async () => {
+ const r = await capture(cwd).handler({ kind: 'consolidate', topic: 'rate limiting' });
+ expect(r.isError).toBeFalsy();
+ expect(textOf(r)).toContain('Where this fits');
+ });
+
+ test('kind:discover returns the Discover plan', async () => {
+ const r = await capture(cwd).handler({ kind: 'discover' });
+ expect(r.isError).toBeFalsy();
+ expect(textOf(r)).toContain('# Discover');
+ expect(r.structuredContent?.previewUrl).toBeNull();
+ });
+
+ test('kind:ingest without source returns a teaching error', async () => {
+ const r = await capture(cwd).handler({ kind: 'ingest' });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('requires `source`');
+ });
+
+ test('kind:research without topic returns a teaching error', async () => {
+ const r = await capture(cwd).handler({ kind: 'research' });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('requires `topic`');
+ });
+
+ test('kind:consolidate without topic returns a teaching error', async () => {
+ const r = await capture(cwd).handler({ kind: 'consolidate' });
+ expect(r.isError).toBe(true);
+ expect(textOf(r)).toContain('requires `topic`');
+ });
+});
diff --git a/packages/server/src/mcp/tools/workflow.ts b/packages/server/src/mcp/tools/workflow.ts
new file mode 100644
index 000000000..f181671d0
--- /dev/null
+++ b/packages/server/src/mcp/tools/workflow.ts
@@ -0,0 +1,106 @@
+import { z } from 'zod';
+import { buildConsolidateBody } from './consolidate-body.ts';
+import { buildDiscoverBody } from './discover-body.ts';
+import { buildIngestBody } from './ingest-body.ts';
+import { buildResearchBody } from './research-body.ts';
+import type { ServerInstance, WorkflowToolDeps } from './shared.ts';
+import {
+ buildWorkflowHandler,
+ outputSchemaWithText,
+ previewUrlOutputField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectConfigContext,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+
+export const DESCRIPTION = [
+ 'Procedural guides for the three-layer wiki workflow + brownfield onboarding. Returns a numbered plan (instructional text, not data) — you execute it. Dispatches on `kind`:',
+ '',
+ '- `kind: "ingest"` — capture an external source (URL or local file) into the KB as raw, verbatim reference material (no analysis). Requires `source`.',
+ '- `kind: "research"` — gather sources and write provisional findings for a question. Requires `topic`.',
+ '- `kind: "consolidate"` — fold provisional material into a canonical article. Requires `topic`.',
+ '- `kind: "discover"` — extract conventions from an existing repo (folder frontmatter + templates + link graph). No payload.',
+ '',
+ '**Parameters:**',
+ '- `kind` — `ingest` | `research` | `consolidate` | `discover`.',
+ '- `source` — Required for `ingest`: the URL / file path / identifier to capture.',
+ '- `topic` — Required for `research` / `consolidate`: the topic, question, or anchor URL.',
+ '- `cwd` (optional) — Project root (see `cwd` description below).',
+].join('\n');
+
+export function register(server: ServerInstance, deps: WorkflowToolDeps): void {
+ const ingest = buildWorkflowHandler('ingest', deps, 'source', buildIngestBody);
+ const research = buildWorkflowHandler('research', deps, 'topic', buildResearchBody);
+ const consolidate = buildWorkflowHandler('consolidate', deps, 'topic', buildConsolidateBody);
+
+ server.registerTool(
+ 'workflow',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ kind: z
+ .enum(['ingest', 'research', 'consolidate', 'discover'])
+ .describe('Which workflow guide to return.'),
+ source: z
+ .string()
+ .optional()
+ .describe('Required for `kind: "ingest"` — the URL / file / identifier to capture.'),
+ topic: z
+ .string()
+ .optional()
+ .describe(
+ 'Required for `kind: "research"` / `"consolidate"` — the topic / question / anchor URL.',
+ ),
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ previewUrl: previewUrlOutputField.describe(
+ 'Always null — a workflow guide is prose, not a previewable document.',
+ ),
+ }),
+ },
+ async (args: {
+ kind: 'ingest' | 'research' | 'consolidate' | 'discover';
+ source?: string;
+ topic?: string;
+ cwd?: string;
+ }) => {
+ switch (args.kind) {
+ case 'ingest':
+ if (!args.source) {
+ return textResult(
+ 'Error: workflow({ kind: "ingest" }) requires `source` — the URL / file / identifier to capture. e.g. workflow({ kind: "ingest", source: "https://example.com/spec" }).',
+ true,
+ );
+ }
+ return ingest(args);
+ case 'research':
+ if (!args.topic) {
+ return textResult(
+ 'Error: workflow({ kind: "research" }) requires `topic` — the question or topic to investigate. e.g. workflow({ kind: "research", topic: "rate-limit strategies" }).',
+ true,
+ );
+ }
+ return research(args);
+ case 'consolidate':
+ if (!args.topic) {
+ return textResult(
+ 'Error: workflow({ kind: "consolidate" }) requires `topic` — the topic to fold into a canonical article. e.g. workflow({ kind: "consolidate", topic: "rate-limit strategies" }).',
+ true,
+ );
+ }
+ return consolidate(args);
+ case 'discover': {
+ const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
+ if (!context.ok) return textResult(`Error: ${context.error}`, true);
+ return textPlusStructured(buildDiscoverBody(context.config.content.dir), {
+ previewUrl: null,
+ });
+ }
+ default:
+ return textResult('Error: unknown workflow kind.', true);
+ }
+ },
+ );
+}
diff --git a/packages/server/src/mcp/tools/write-document.test.ts b/packages/server/src/mcp/tools/write-document.test.ts
deleted file mode 100644
index c1aee45cb..000000000
--- a/packages/server/src/mcp/tools/write-document.test.ts
+++ /dev/null
@@ -1,1068 +0,0 @@
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { stripFrontmatter } from '@inkeep/open-knowledge-core';
-import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
-import type { ServerInstance } from './shared.ts';
-import { register } from './write-document.ts';
-
-const BASE_CONFIG: Config = ConfigSchema.parse({});
-
-interface ToolResult {
- content: Array<{ type: 'text'; text: string }>;
- structuredContent?: Record<string, unknown>;
- isError?: true;
-}
-
-interface RegisteredTool {
- name: string;
- handler: (args: {
- docName?: string;
- markdown?: string;
- template?: string;
- position?: 'append' | 'prepend' | 'replace';
- docs?: Array<{
- docName: string;
- markdown?: string;
- template?: string;
- position?: 'append' | 'prepend' | 'replace';
- }>;
- }) => Promise<ToolResult>;
-}
-
-function createFakeServer() {
- let registeredTool: RegisteredTool | undefined;
- const server = {
- registerTool(name: string, _config: unknown, handler: RegisteredTool['handler']) {
- registeredTool = { name, handler };
- },
- } as unknown as ServerInstance;
- return {
- server,
- getTool(): RegisteredTool {
- if (!registeredTool) throw new Error('Tool was not registered');
- return registeredTool;
- },
- };
-}
-
-let testServer: ReturnType<typeof Bun.serve>;
-let baseUrl: string;
-let mockSubscriberCount: number | undefined = 1;
-let mockSystemSubscriberCount: number | undefined = 1;
-let lastWriteRequest: Record<string, unknown> | undefined;
-let mockErrorEnvelope: { status: number; body: Record<string, unknown> } | undefined;
-let mockWarning: Record<string, unknown> | undefined;
-
-beforeAll(() => {
- testServer = Bun.serve({
- port: 0,
- async fetch(req) {
- const url = new URL(req.url);
- if (url.pathname === '/api/agent-write-md') {
- lastWriteRequest = (await req.json()) as Record<string, unknown>;
- if (mockErrorEnvelope) {
- return Response.json(mockErrorEnvelope.body, { status: mockErrorEnvelope.status });
- }
- return Response.json({
- ok: true,
- timestamp: '2026-04-15T00:00:00.000Z',
- ...(mockSubscriberCount !== undefined ? { subscriberCount: mockSubscriberCount } : {}),
- ...(mockSystemSubscriberCount !== undefined
- ? { systemSubscriberCount: mockSystemSubscriberCount }
- : {}),
- ...(mockWarning !== undefined ? { warning: mockWarning } : {}),
- });
- }
- return new Response('Not found', { status: 404 });
- },
- });
- baseUrl = `http://localhost:${testServer.port}`;
-});
-
-afterAll(() => {
- testServer.stop();
-});
-
-let tmpDir: string;
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-write-doc-'));
- mockSubscriberCount = 1;
- mockSystemSubscriberCount = 1;
- lastWriteRequest = undefined;
- mockErrorEnvelope = undefined;
- mockWarning = undefined;
-});
-
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-function makeDeps() {
- return {
- serverUrl: baseUrl,
- config: BASE_CONFIG,
- resolveCwd: async () => tmpDir,
- };
-}
-
-describe('write_document — previewUrl emission', () => {
- test('emits route-only previewUrl + source when resolver resolves', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/docs/test',
- previewUrlSource: 'lock',
- });
- expect(result.content[0]?.text).toContain('Written successfully (append)');
- });
-
- test('omits structuredContent when nothing resolves AND subscribers>0', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'replace',
- });
-
- expect(result.structuredContent).toBeUndefined();
- expect(result.content[0]?.text).toBe('Written successfully (replace).');
- });
-
- test('emits attach-preview-once hint with previewUrl + autoOpen=true (default) when systemSubscriberCount=0', async () => {
- bindTestUiLock(tmpDir);
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/docs/test',
- previewUrlSource: 'lock',
- warning: {
- action: 'attach-preview-once',
- message:
- 'No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.',
- previewUrl: '/#/docs/test',
- autoOpen: true,
- },
- });
- });
-
- test('emits start-ui hint with null previewUrl + autoOpen=true (default) when systemSubscriberCount=0 and no resolver', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'start-ui',
- previewUrl: null,
- autoOpen: true,
- },
- });
- const warning = (result.structuredContent as { warning: { message: string } }).warning;
- expect(warning.message).toContain('ok ui');
- expect(warning.message).toContain('preview_start');
- expect(warning.message).toContain('OK Electron');
- expect(result.structuredContent).not.toHaveProperty('previewUrl');
- });
-
- test('no warning when systemSubscriberCount>0 even if per-doc subscriberCount=0 (second doc, server-push follows)', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 1;
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/second',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent?.warning).toBeUndefined();
- expect(result.content[0]?.text).not.toContain('No preview attached');
- });
-
- test('no warning when server omits systemSubscriberCount (legacy server)', async () => {
- mockSubscriberCount = undefined;
- mockSystemSubscriberCount = undefined;
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toBeUndefined();
- expect(result.content[0]?.text).toBe('Written successfully (append).');
- });
-
- test('strips .md extension before building the preview route', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/test.md',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- previewUrl: '/#/docs/test',
- previewUrlSource: 'lock',
- });
- });
-});
-
-describe('write_document — autoOpen field on PreviewAttachWarning', () => {
- test('attach-preview-once warning carries autoOpen=false when user disabled it', async () => {
- bindTestUiLock(tmpDir);
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- const config = ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } });
- register(server, {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- });
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'attach-preview-once',
- previewUrl: '/#/docs/test',
- autoOpen: false,
- },
- });
- });
-
- test('start-ui warning carries autoOpen=false when user disabled it', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- const config = ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } });
- register(server, {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- });
-
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'hello',
- position: 'append',
- });
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'start-ui',
- previewUrl: null,
- autoOpen: false,
- },
- });
- });
-
- test('reads autoOpen fresh per call (resolver invoked each time — mid-session toggle propagates)', async () => {
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- bindTestUiLock(tmpDir);
-
- let currentAutoOpen = true;
- const configResolver = async () =>
- ConfigSchema.parse({ appearance: { preview: { autoOpen: currentAutoOpen } } });
-
- const { server, getTool } = createFakeServer();
- register(server, {
- serverUrl: baseUrl,
- config: configResolver,
- resolveCwd: async () => tmpDir,
- });
-
- const first = await getTool().handler({
- docName: 'docs/test',
- markdown: 'a',
- position: 'append',
- });
- expect((first.structuredContent as { warning: { autoOpen: boolean } }).warning.autoOpen).toBe(
- true,
- );
-
- currentAutoOpen = false;
-
- const second = await getTool().handler({
- docName: 'docs/test',
- markdown: 'b',
- position: 'append',
- });
- expect((second.structuredContent as { warning: { autoOpen: boolean } }).warning.autoOpen).toBe(
- false,
- );
- });
-
- test('batch path: warning carries autoOpen=false when user disabled it', async () => {
- bindTestUiLock(tmpDir);
- mockSubscriberCount = 0;
- mockSystemSubscriberCount = 0;
- const { server, getTool } = createFakeServer();
- const config = ConfigSchema.parse({ appearance: { preview: { autoOpen: false } } });
- register(server, {
- serverUrl: baseUrl,
- config,
- resolveCwd: async () => tmpDir,
- });
-
- const result = await getTool().handler({
- docs: [{ docName: 'docs/test', markdown: 'hello', position: 'append' }],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.structuredContent).toMatchObject({
- warning: {
- action: 'attach-preview-once',
- previewUrl: '/#/docs/test',
- autoOpen: false,
- },
- });
- });
-});
-
-describe('write_document — template instantiation (FR5)', () => {
- test('instantiates from a local template — markdown payload is template body', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', '.ok', 'templates'), { recursive: true });
- const templateContent =
- '---\ntitle: Meeting Prep\ndescription: Use before a meeting.\ntags: [meeting, prep]\n---\n# {Meeting Title}\n\n**Attendees:** \n';
- await writeFile(
- resolve(tmpDir, 'meetings', '.ok', 'templates', 'prep-notes.md'),
- templateContent,
- );
-
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'meetings/2026-05-01-foo',
- template: 'prep-notes',
- position: 'replace',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest).toBeDefined();
- expect(lastWriteRequest?.markdown).toBe(stripFrontmatter(templateContent).body);
- expect(lastWriteRequest?.position).toBe('replace');
- expect(lastWriteRequest?.docName).toBe('meetings/2026-05-01-foo');
- });
-
- test('inherits template from ancestor folder (walk-up)', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', '.ok', 'templates'), { recursive: true });
- const templateContent = '---\ntitle: Inherited\n---\nbody\n';
- await writeFile(resolve(tmpDir, 'meetings', '.ok', 'templates', 'shared.md'), templateContent);
-
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'meetings/prep-notes/foo',
- template: 'shared',
- position: 'replace',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.markdown).toBe(stripFrontmatter(templateContent).body);
- });
-
- test('rejects unknown template name with helpful menu', async () => {
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'meetings/foo',
- template: 'nonexistent',
- position: 'replace',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('not found');
- expect(lastWriteRequest).toBeUndefined();
- });
-
- test('rejects descendant-scoped template at parent folder', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', 'prep-notes', '.ok', 'templates'), {
- recursive: true,
- });
- await writeFile(
- resolve(tmpDir, 'meetings', 'prep-notes', '.ok', 'templates', 'agenda.md'),
- '---\ntitle: Agenda\n---\nb\n',
- );
-
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'meetings/foo',
- template: 'agenda',
- position: 'replace',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('not found');
- });
-
- test('without template arg, behavior unchanged (markdown passes through)', async () => {
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'foo',
- markdown: 'plain content',
- position: 'append',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.markdown).toBe('plain content');
- expect(lastWriteRequest?.position).toBe('append');
- });
-
- test('strips the template frontmatter so it does not leak into the new doc', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', '.ok', 'templates'), { recursive: true });
- await writeFile(
- resolve(tmpDir, 'meetings', '.ok', 'templates', 'dossier.md'),
- '---\ntitle: Dossier template\ntags: [tpl]\n---\n## Summary\n\nbody\n',
- );
-
- const fakeServer = createFakeServer();
- register(fakeServer.server, makeDeps());
-
- const result = await fakeServer.getTool().handler({
- docName: 'meetings/new-dossier',
- template: 'dossier',
- position: 'replace',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.markdown).not.toContain('title: Dossier template');
- expect(lastWriteRequest?.markdown).not.toContain('tags:');
- expect(lastWriteRequest?.markdown).toContain('## Summary');
- });
-});
-
-describe('write_document — content-divergence relay', () => {
- test('single-doc: relays the server warning as structuredContent.contentDivergence + a text line', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = {
- kind: 'content-divergence',
- intendedBytes: 18,
- actualBytes: 25,
- byteDelta: 7,
- divergenceType: 'replace-content-mismatch',
- currentState: { kind: 'inline', content: 'what actually landed\n' },
- hint: 'currentState carries the converged content.',
- };
-
- const result = await getTool().handler({
- docName: 'notes',
- markdown: 'hello',
- position: 'replace',
- });
-
- expect(result.structuredContent?.contentDivergence).toMatchObject({
- kind: 'content-divergence',
- byteDelta: 7,
- divergenceType: 'replace-content-mismatch',
- currentState: { kind: 'inline', content: 'what actually landed\n' },
- });
- expect(result.content[0]?.text).toContain('⚠ Content divergence');
- });
-
- test('batch: surfaces per-doc contentDivergence from the r.raw.warning path', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = {
- kind: 'content-divergence',
- intendedBytes: 10,
- actualBytes: 14,
- byteDelta: 4,
- divergenceType: 'append-content-mismatch',
- currentState: { kind: 'inline', content: 'batch landed\n' },
- hint: 'currentState carries the converged content.',
- };
-
- const result = await getTool().handler({
- docs: [{ docName: 'docs/test', markdown: 'hello', position: 'append' }],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- const s = result.structuredContent as {
- documents: Array<{ docName: string; contentDivergence?: Record<string, unknown> }>;
- };
- expect(s.documents[0]?.contentDivergence).toMatchObject({
- kind: 'content-divergence',
- byteDelta: 4,
- divergenceType: 'append-content-mismatch',
- });
- });
-
- test('drops a malformed server warning at the safeParse boundary (single-doc)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- mockWarning = {
- kind: 'content-divergence',
- intendedBytes: 18,
- actualBytes: 25,
- byteDelta: 'seven',
- };
-
- const result = await getTool().handler({
- docName: 'notes',
- markdown: 'hello',
- position: 'replace',
- });
-
- expect(result.structuredContent?.contentDivergence).toBeUndefined();
- });
-});
-
-describe('write_document — batch (docs)', () => {
- test('writes each doc in the batch and reports per-doc results', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docs: [
- { docName: 'a', markdown: 'A', position: 'replace' },
- { docName: 'notes/b', markdown: 'B', position: 'append' },
- ],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- const s = result.structuredContent as {
- ok: boolean;
- documents: Array<{ docName: string; ok: boolean }>;
- };
- expect(s.ok).toBe(true);
- expect(s.documents.map((d) => d.docName)).toEqual(['a', 'notes/b']);
- expect(s.documents.every((d) => d.ok)).toBe(true);
- expect(result.content[0]?.text).toContain('2/2 written');
- });
-
- test('a per-doc failure surfaces without blocking the rest', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docs: [
- { docName: 'good', markdown: 'ok', position: 'replace' },
- { docName: 'bad', markdown: 'x', template: 'y', position: 'replace' },
- ],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- const s = result.structuredContent as {
- ok: boolean;
- documents: Array<{ docName: string; ok: boolean; error?: string }>;
- };
- expect(s.ok).toBe(false);
- expect(s.documents.find((d) => d.docName === 'good')?.ok).toBe(true);
- expect(s.documents.find((d) => d.docName === 'bad')?.error).toContain('mutually exclusive');
- });
-
- test('docs together with a top-level single-doc field is rejected', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'x',
- markdown: 'y',
- position: 'replace',
- docs: [{ docName: 'a', markdown: 'A', position: 'replace' }],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('batch form');
- });
-
- test('batch entries default omitted position to replace (new) or fail (existing)', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'already-here.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docs: [
- { docName: 'brand-new', markdown: 'A' },
- { docName: 'already-here', markdown: 'B' },
- ],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- const s = result.structuredContent as {
- ok: boolean;
- documents: Array<{ docName: string; ok: boolean; position?: string; error?: string }>;
- };
- expect(s.ok).toBe(false);
- const fresh = s.documents.find((d) => d.docName === 'brand-new');
- const existing = s.documents.find((d) => d.docName === 'already-here');
- expect(fresh?.ok).toBe(true);
- expect(fresh?.position).toBe('replace');
- expect(existing?.ok).toBe(false);
- expect(existing?.error).toContain('already exists');
- });
-});
-
-describe('write_document — prepend/append frontmatter warning (PRD-6660)', () => {
- test('warns when a prepend payload carries a frontmatter block', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: '---\ntags: [test]\n---\n\nbody',
- position: 'prepend',
- });
- expect(result.content[0]?.text).toContain(
- 'frontmatter block in this `prepend` payload was ignored',
- );
- expect(result.content[0]?.text).toContain('edit_frontmatter');
- });
-
- test('no warning for a plain-text prepend (no frontmatter)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: 'just body text',
- position: 'prepend',
- });
- expect(result.content[0]?.text).not.toContain('was ignored');
- });
-
- test('no warning for replace with frontmatter — replace writes it', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: '---\ntags: [test]\n---\n\nbody',
- position: 'replace',
- });
- expect(result.content[0]?.text).not.toContain('was ignored');
- });
-
- test('warns when an append payload carries a frontmatter block', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- const result = await getTool().handler({
- docName: 'docs/test',
- markdown: '---\ntags: [test]\n---\n\nbody',
- position: 'append',
- });
- expect(result.content[0]?.text).toContain(
- 'frontmatter block in this `append` payload was ignored',
- );
- });
-
- test('warns per-doc in a batch when a spec prepends frontmatter', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
- const result = await getTool().handler({
- docs: [
- { docName: 'docs/plain', markdown: 'body', position: 'append' },
- { docName: 'docs/fm', markdown: '---\ntags: [test]\n---\n\nbody', position: 'prepend' },
- ],
- });
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('docs/fm — Note:');
- expect(text).toContain('was ignored');
- expect(text).not.toContain('docs/plain — Note:');
- });
-});
-
-describe('write_document — position defaulting', () => {
- test('a new doc defaults position to replace when omitted', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'fresh-doc',
- markdown: 'hello',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.position).toBe('replace');
- expect(result.content[0]?.text).toBe('Written successfully (replace).');
- });
-
- test('an existing doc requires an explicit position', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'existing-doc.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'existing-doc',
- markdown: 'new body',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('already exists');
- expect(lastWriteRequest).toBeUndefined();
- });
-
- test('existing-doc guard anchors on contentDir, not the project root', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'docs'), { recursive: true });
- await writeFile(resolve(tmpDir, 'docs', 'existing-doc.md'), '# Existing\n');
-
- const config = ConfigSchema.parse({ content: { dir: 'docs' } });
- const { server, getTool } = createFakeServer();
- register(server, { serverUrl: baseUrl, config, resolveCwd: async () => tmpDir });
-
- const result = await getTool().handler({
- docName: 'existing-doc',
- markdown: 'new body',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('already exists');
- expect(lastWriteRequest).toBeUndefined();
- });
-
- test('a template instantiation defaults position to replace when omitted', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', '.ok', 'templates'), { recursive: true });
- await writeFile(
- resolve(tmpDir, 'meetings', '.ok', 'templates', 'prep-notes.md'),
- '---\ntitle: Prep\n---\nbody\n',
- );
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'meetings/2026-05-21-sync',
- template: 'prep-notes',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.position).toBe('replace');
- });
-
- test('template instantiation onto an existing doc still requires an explicit position', async () => {
- const { mkdir, writeFile } = await import('node:fs/promises');
- await mkdir(resolve(tmpDir, 'meetings', '.ok', 'templates'), { recursive: true });
- await writeFile(
- resolve(tmpDir, 'meetings', '.ok', 'templates', 'prep-notes.md'),
- '---\ntitle: Prep\n---\nbody\n',
- );
- await writeFile(resolve(tmpDir, 'meetings', 'standup.md'), '# Existing standup\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'meetings/standup',
- template: 'prep-notes',
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('already exists');
- expect(lastWriteRequest).toBeUndefined();
- });
-});
-
-describe('write_document — empty / whitespace content (PRD-6835)', () => {
- for (const empty of ['', ' ', '\n', ' \n ']) {
- test(`new doc + whitespace-only markdown ${JSON.stringify(empty)} is rejected before POST`, async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'brand-new',
- markdown: empty,
- position: 'replace',
- });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('does not exist and the content is empty');
- expect(lastWriteRequest).toBeUndefined();
- });
- }
-
- test('new-doc empty rejection fires for any position (explicit append does not skip the existence check)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'brand-new',
- markdown: '',
- position: 'append',
- });
-
- expect(result.isError).toBe(true);
- expect(result.content[0]?.text).toContain('does not exist and the content is empty');
- expect(lastWriteRequest).toBeUndefined();
- });
-
- test('new doc + frontmatter-only payload is NOT rejected (it creates a real doc)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'fresh-fm',
- markdown: '---\ntitle: New\n---',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.markdown).toBe('---\ntitle: New\n---');
- });
-
- test('clearing an EXISTING doc with empty markdown + replace is allowed (posts empty body)', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'existing.md'), '---\ntitle: Keep\n---\n# Body\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'existing',
- markdown: '',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.markdown).toBe('');
- expect(lastWriteRequest?.position).toBe('replace');
- });
-
- test('empty append on an existing doc reports "document unchanged" (not "Written successfully")', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'existing.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'existing',
- markdown: '',
- position: 'append',
- });
-
- expect(result.isError).toBeUndefined();
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('No content to append — document unchanged');
- expect(text).not.toContain('Written successfully');
- });
-
- test('empty prepend on an existing doc reports "document unchanged"', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'existing.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'existing',
- markdown: '',
- position: 'prepend',
- });
-
- expect(result.isError).toBeUndefined();
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('No content to prepend — document unchanged');
- expect(text).not.toContain('Written successfully');
- });
-
- test('a server validation error surfaces the field-level detail, not just the title', async () => {
- mockErrorEnvelope = {
- status: 400,
- body: {
- type: 'urn:ok:error:invalid-request',
- title: 'Request body is invalid.',
- status: 400,
- detail: 'summary: String must contain at most 80 character(s)',
- },
- };
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'docs/will-fail',
- markdown: 'hello',
- position: 'replace',
- });
-
- expect(result.isError).toBe(true);
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('Request body is invalid.');
- expect(text).toContain('summary: String must contain at most 80 character(s)');
- });
-});
-
-describe('write_document — explicit .mdx extension (PRD-6836)', () => {
- test('a new doc with a .mdx docName forwards extension: ".mdx" to the write API', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'guides/widget.mdx',
- markdown: '# Widget\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.extension).toBe('.mdx');
- expect(lastWriteRequest?.docName).toBe('guides/widget');
- });
-
- test('a new doc with a .md docName forwards extension: ".md" (explicit, matches default)', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'guides/widget.md',
- markdown: '# Widget\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.extension).toBe('.md');
- });
-
- test('a doubled .md.md docName fully normalizes — keys the bare name, lands a single .md file (PRD-6837 #2)', async () => {
- bindTestUiLock(tmpDir);
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'guides/widget.md.md',
- markdown: '# Widget\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.docName).toBe('guides/widget');
- expect(lastWriteRequest?.extension).toBe('.md');
- expect(result.structuredContent).toMatchObject({ previewUrl: '/#/guides/widget' });
- });
-
- test('an extension-less docName forwards no extension hint', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'guides/widget',
- markdown: '# Widget\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest).toBeDefined();
- expect(lastWriteRequest).not.toHaveProperty('extension');
- });
-
- test('a .mdx request against a doc that already exists as .md omits the hint and surfaces a note', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'widget.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'widget.mdx',
- markdown: '# New body\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest).not.toHaveProperty('extension');
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('already exists as `widget.md`');
- expect(text).toContain('was not applied');
- expect(text).not.toContain('rename(');
- });
-
- test('no rename note when the requested suffix matches the on-disk extension', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'widget.mdx'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docName: 'widget.mdx',
- markdown: '# New body\n',
- position: 'replace',
- });
-
- expect(result.isError).toBeUndefined();
- expect(result.content[0]?.text ?? '').not.toContain('was not applied');
- });
-
- test('batch: a .mdx request against an existing .md doc surfaces a per-doc rename note', async () => {
- const { writeFile } = await import('node:fs/promises');
- await writeFile(resolve(tmpDir, 'widget.md'), '# Existing\n');
-
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docs: [{ docName: 'widget.mdx', markdown: '# New\n', position: 'replace' }],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- const text = result.content[0]?.text ?? '';
- expect(text).toContain('widget.mdx — Note:');
- expect(text).toContain('already exists as `widget.md`');
- });
-
- test('batch: a new doc with a .mdx docName forwards extension: ".mdx" on the wire', async () => {
- const { server, getTool } = createFakeServer();
- register(server, makeDeps());
-
- const result = await getTool().handler({
- docs: [{ docName: 'batch/widget.mdx', markdown: '# Widget\n', position: 'replace' }],
- } as Parameters<RegisteredTool['handler']>[0]);
-
- expect(result.isError).toBeUndefined();
- expect(lastWriteRequest?.extension).toBe('.mdx');
- expect(lastWriteRequest?.docName).toBe('batch/widget');
- });
-});
diff --git a/packages/server/src/mcp/tools/write-document.ts b/packages/server/src/mcp/tools/write-document.ts
deleted file mode 100644
index 5b2814232..000000000
--- a/packages/server/src/mcp/tools/write-document.ts
+++ /dev/null
@@ -1,484 +0,0 @@
-import { existsSync, readFileSync } from 'node:fs';
-import { resolve as resolvePath } from 'node:path';
-import {
- normalizeBridge,
- renderInventoryFooter,
- stripFrontmatter,
- WriteWarningSchema,
-} from '@inkeep/open-knowledge-core';
-import { z } from 'zod';
-import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
-import { parentFolderOf } from '../../content/nested-folder-rules.ts';
-import { applySubstitution, todayIsoUtc } from '../../content/substitution.ts';
-import { resolveTemplatesAvailable } from '../../content/templates-resolver.ts';
-import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
-import type { AgentIdentity } from '../agent-identity.ts';
-import { resolveWithinRoot } from './path-safety.ts';
-import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
-import {
- HOCUSPOCUS_NOT_RUNNING_ERROR,
- httpPost,
- normalizeDocName,
- ROUTED_CWD_DESCRIPTION,
- resolveProjectServerContext,
- summaryArgSchema,
- textPlusStructured,
- textResult,
-} from './shared.ts';
-
-const POSITIONS = ['append', 'prepend', 'replace'] as const;
-
-const BASE_DESCRIPTION = [
- '[Requires: Hocuspocus server] Write markdown to a document via the CRDT layer. Content propagates to all connected editors in real-time.',
- '',
- 'Frontmatter changes: 1-2 keys → prefer `edit_frontmatter` (field-level CRDT, atomic). Full rewrite (≥3-5 keys or body + frontmatter together) → this tool with `position: "replace"` and the full YAML block in the payload.',
- '',
- 'Templates: `template: "<name>"` resolves against the parent folder\'s `templates_available` (see `exec("ls <folder>/")`) and becomes the new doc verbatim. `template` and `markdown` are mutually exclusive. With `template` set, `position` is forced to `"replace"`.',
- '',
- 'To create several docs in one call (scaffolding a pack, seeding dossiers), pass `docs: [{docName, markdown|template, position?, summary?}, ...]` instead of the single-doc fields. Docs write in order; the response reports each.',
- '',
- '**Parameters:**',
- '- `docName` — A single document (`notes/meeting`). On create, a trailing `.mdx` authors a `.mdx` file; `.md` or no extension authors `.md`. For an existing doc the on-disk extension is preserved regardless of the suffix passed (changing it in place is not available via the MCP today).',
- '- `docs` — Batch form: array of `{docName, markdown?|template?, position?, summary?}`. Mutually exclusive with the single-doc fields.',
- '- `markdown` — Markdown payload. Required unless `template` is set. An empty string with `position: "replace"` clears the document body (frontmatter is preserved); empty `append`/`prepend` is a no-op. Empty content does NOT create a new document.',
- '- `template` — Template name. Mutually exclusive with `markdown`.',
- '- `position` — `append` | `prepend` | `replace`. Optional for a new doc (defaults to `replace`); required for an existing doc. Forced to `replace` with `template`.',
- '- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history.',
- '',
- 'Responses may include a content-divergence warning when the converged Y.Text doesn\'t match the bytes your payload composed to. The write still landed; you do NOT need to re-read — `currentState` carries the converged document inline (`{kind:"inline", content}`, or `{kind:"truncated", byteLength, hint}` over the soft cap). Single-doc shape: `structuredContent.contentDivergence = { kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint }`. Batch shape: per-doc `structuredContent.documents[].contentDivergence` with the same field set.',
-].join('\n');
-
-export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
-
-interface WriteDocumentDeps {
- serverUrl: ServerUrlOrResolver;
- config: ConfigOrResolver;
- resolveCwd: (explicit?: string) => Promise<string>;
- identityRef?: { current: AgentIdentity };
-}
-
-interface DocSpec {
- docName: string;
- markdown?: string;
- template?: string;
- position?: string;
- summary?: string;
-}
-
-type WriteApiResult = Awaited<ReturnType<typeof httpPost>>;
-
-type WriteOneResult =
- | {
- docName: string;
- ok: true;
- position: string;
- fromTemplate?: string;
- extensionNote?: string;
- raw: WriteApiResult;
- }
- | { docName: string; ok: false; error: string };
-
-function frontmatterIgnoredNote(position: string, markdown: string | undefined): string | null {
- if ((position !== 'prepend' && position !== 'append') || !markdown) return null;
- if (stripFrontmatter(markdown).frontmatter.trim() === '') return null;
- return `Note: a \`---\` frontmatter block in this \`${position}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit_frontmatter\` (1-2 keys) or \`write_document({ position: "replace" })\` (full rewrite).`;
-}
-
-function emptyAppendNoOpNote(position: string, markdown: string | undefined): string | null {
- if ((position !== 'prepend' && position !== 'append') || markdown === undefined) return null;
- if (stripFrontmatter(markdown).body !== '') return null;
- return `No content to ${position} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`markdown\`.`;
-}
-
-function docExtensionOnDisk(contentDir: string, docName: string): '.md' | '.mdx' | null {
- for (const ext of SUPPORTED_DOC_EXTENSIONS) {
- const contained = resolveWithinRoot(contentDir, `${docName}${ext}`);
- if (contained.ok && existsSync(contained.abs)) return ext;
- }
- return null;
-}
-
-function requestedDocExtension(rawDocName: string): '.md' | '.mdx' | null {
- const lower = rawDocName.toLowerCase();
- if (lower.endsWith('.mdx')) return '.mdx';
- if (lower.endsWith('.md')) return '.md';
- return null;
-}
-
-function extensionIgnoredNote(
- requestedExt: '.md' | '.mdx' | null,
- existingExt: '.md' | '.mdx' | null,
- docName: string,
-): string | null {
- if (requestedExt === null || existingExt === null || requestedExt === existingExt) return null;
- return `Note: "${docName}" already exists as \`${docName}${existingExt}\`, so the requested \`${requestedExt}\` extension was not applied — the write went to \`${docName}${existingExt}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`;
-}
-
-async function writeOneDoc(
- spec: DocSpec,
- cwd: string,
- contentDir: string,
- url: string,
- deps: WriteDocumentDeps,
-): Promise<WriteOneResult> {
- const normalized = normalizeDocName(spec.docName);
- if (!normalized.ok) return { docName: spec.docName, ok: false, error: normalized.error };
- const docName = normalized.docName;
- const identity = deps.identityRef?.current;
-
- if (spec.template === undefined && spec.markdown === undefined) {
- return {
- docName,
- ok: false,
- error:
- 'either `markdown` or `template` must be provided — omitting both would write empty content.',
- };
- }
- if (spec.template !== undefined && spec.markdown !== undefined) {
- return {
- docName,
- ok: false,
- error:
- 'TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one; fill placeholders via subsequent `edit_document` calls.',
- };
- }
-
- let effectiveMarkdown = spec.markdown ?? '';
-
- const existingExt = docExtensionOnDisk(contentDir, docName);
- const docExists = existingExt !== null;
- const requestedExt = requestedDocExtension(spec.docName);
-
- let effectivePosition: string;
- if (spec.position !== undefined) {
- effectivePosition = spec.position;
- } else if (docExists) {
- return {
- docName,
- ok: false,
- error: `"${docName}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit_document\` for a targeted change.`,
- };
- } else {
- effectivePosition = 'replace';
- }
-
- if (spec.template !== undefined) {
- const parentFolder = parentFolderOf(docName);
- const available = resolveTemplatesAvailable(cwd, parentFolder, { depth: 1 });
- const matched = available.find((t) => t.name === spec.template);
- if (!matched) {
- return {
- docName,
- ok: false,
- error: `template "${spec.template}" not found for folder "${parentFolder || '.'}". Available: ${
- available.length === 0
- ? '(none)'
- : available.map((t) => `${t.name} [${t.scope}]`).join(', ')
- }. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`,
- };
- }
- let templateContent: string;
- try {
- templateContent = readFileSync(resolvePath(cwd, matched.path), 'utf-8');
- } catch (err) {
- return {
- docName,
- ok: false,
- error: `failed to read template at ${matched.path}: ${(err as Error).message}`,
- };
- }
- const { body: templateBody } = stripFrontmatter(templateContent);
- effectiveMarkdown = applySubstitution(templateBody, {
- date: todayIsoUtc(),
- user: identity?.displayName ?? '',
- });
- effectivePosition = 'replace';
- }
-
- if (!docExists && normalizeBridge(effectiveMarkdown) === '') {
- return {
- docName,
- ok: false,
- error: `"${docName}" does not exist and the content is empty — provide non-empty content to create the document.`,
- };
- }
-
- const result = await httpPost(url, '/api/agent-write-md', {
- docName,
- markdown: effectiveMarkdown,
- position: effectivePosition,
- ...(requestedExt !== null && !docExists ? { extension: requestedExt } : {}),
- ...(spec.summary !== undefined ? { summary: spec.summary } : {}),
- ...(identity
- ? {
- agentId: identity.connectionId,
- agentName: identity.displayName,
- clientName: identity.clientInfo?.name,
- colorSeed: identity.colorSeed,
- }
- : {}),
- });
- if (!result.ok) {
- const detail =
- typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
- return {
- docName,
- ok: false,
- error: detail ? `${String(result.error)} (${detail})` : String(result.error),
- };
- }
- const extensionNote = extensionIgnoredNote(requestedExt, existingExt, docName);
- return {
- docName,
- ok: true,
- position: effectivePosition,
- ...(spec.template !== undefined ? { fromTemplate: spec.template } : {}),
- ...(extensionNote ? { extensionNote } : {}),
- raw: result,
- };
-}
-
-export function register(server: ServerInstance, deps: WriteDocumentDeps): void {
- const docSpecShape = {
- docName: z.string().describe('Document name to write to'),
- markdown: z
- .string()
- .optional()
- .describe('Markdown content to write. Optional when `template` is set.'),
- template: z
- .string()
- .min(1)
- .optional()
- .describe(
- "Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder.",
- ),
- position: z
- .enum(POSITIONS)
- .optional()
- .describe(
- 'Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists.',
- ),
- summary: summaryArgSchema,
- };
-
- server.registerTool(
- 'write_document',
- {
- description: DESCRIPTION,
- inputSchema: {
- docName: z.string().optional().describe('A single document to write to.'),
- markdown: z
- .string()
- .optional()
- .describe('Markdown content. Optional when `template` is set.'),
- template: z
- .string()
- .min(1)
- .optional()
- .describe(
- "Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder.",
- ),
- position: z
- .enum(POSITIONS)
- .optional()
- .describe(
- 'Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists.',
- ),
- summary: summaryArgSchema,
- docs: z
- .array(z.object(docSpecShape))
- .min(1)
- .optional()
- .describe(
- 'Batch: documents to write in one call. Mutually exclusive with the single-doc fields.',
- ),
- cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
- },
- },
- async (args: {
- docName?: string;
- markdown?: string;
- template?: string;
- position?: string;
- summary?: string;
- docs?: DocSpec[];
- cwd?: string;
- }) => {
- const context = await resolveProjectServerContext(
- deps.resolveCwd,
- deps.config,
- deps.serverUrl,
- args.cwd,
- );
- if (!context.ok) return textResult(`Error: ${context.error}`, true);
- const { cwd, config, url } = context;
- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
-
- const lockDir = resolveLockDir(cwd);
- const contentDir = resolveContentDir(config, cwd);
- const autoOpen = config.appearance.preview.autoOpen;
-
- if (args.docs !== undefined) {
- if (
- args.docName !== undefined ||
- args.markdown !== undefined ||
- args.template !== undefined ||
- args.position !== undefined ||
- args.summary !== undefined
- ) {
- return textResult(
- 'Error: `docs` is the batch form — do not also pass top-level `docName` / `markdown` / `template` / `position` / `summary` (each `docs[]` entry carries its own).',
- true,
- );
- }
- const results: WriteOneResult[] = [];
- for (const spec of args.docs) {
- results.push(await writeOneDoc(spec, cwd, contentDir, url, deps));
- }
- const documents = results.map((r) => {
- if (!r.ok) return { docName: r.docName, ok: false as const, error: r.error };
- const preview = resolvePreviewUrl(r.docName, { lockDir });
- const divergenceParse = WriteWarningSchema.safeParse(r.raw.warning);
- const divergence = divergenceParse.success ? divergenceParse.data : undefined;
- return {
- docName: r.docName,
- ok: true as const,
- position: r.position,
- ...(preview ? { previewUrl: preview.url } : {}),
- ...(divergence ? { contentDivergence: divergence } : {}),
- };
- });
- const okCount = documents.filter((d) => d.ok).length;
- const allOk = okCount === documents.length;
- const lines = args.docs.map((spec, i) => {
- const r = results[i];
- if (!r?.ok) return `Failed ${spec.docName}: ${r?.error ?? 'unknown error'}`;
- if (emptyAppendNoOpNote(r.position, spec.markdown)) {
- return `No change to ${spec.docName} — empty ${r.position}, document unchanged.`;
- }
- const d = documents[i];
- const base = `Wrote ${spec.docName} (${r.position}).`;
- if (!(d?.ok && d.contentDivergence)) return base;
- return d.contentDivergence.kind === 'content-divergence'
- ? `${base} ⚠ Content divergence: ${d.contentDivergence.actualBytes} actual vs ${d.contentDivergence.intendedBytes} intended (byteDelta=${d.contentDivergence.byteDelta}).`
- : `${base} ⚠ An out-of-band disk edit was reconciled in before your write — re-read for the combined result.`;
- });
- const perDocNotes = args.docs.flatMap((spec, i) => {
- const r = results[i];
- if (!r?.ok) return [];
- const fmNote = frontmatterIgnoredNote(r.position, spec.markdown);
- const notes = [
- ...(fmNote ? [fmNote] : []),
- ...(r.extensionNote ? [r.extensionNote] : []),
- ];
- return notes.map((n) => `${spec.docName} — ${n}`);
- });
- const text = [`${okCount}/${documents.length} written.`, ...lines, ...perDocNotes].join(
- '\n',
- );
- const structured: Record<string, unknown> = { ok: allOk, documents };
- const firstOk = results.find((r): r is Extract<WriteOneResult, { ok: true }> => r.ok);
- if (firstOk && firstOk.raw.systemSubscriberCount === 0) {
- const firstPreview = resolvePreviewUrl(firstOk.docName, { lockDir });
- structured.warning = buildPreviewAttachWarning(firstPreview, autoOpen);
- }
- return textPlusStructured(text, structured, !allOk);
- }
-
- if (args.docName === undefined) {
- return textResult('Error: provide `docName` (single) or `docs` (batch).', true);
- }
- const w = await writeOneDoc(
- {
- docName: args.docName,
- markdown: args.markdown,
- template: args.template,
- position: args.position,
- summary: args.summary,
- },
- cwd,
- contentDir,
- url,
- deps,
- );
- if (!w.ok) return textResult(`Error: ${w.error}`, true);
-
- const result = w.raw;
- const preview = resolvePreviewUrl(w.docName, { lockDir });
- const subscriberCount =
- typeof result.subscriberCount === 'number' ? result.subscriberCount : undefined;
- const systemSubscriberCount =
- typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;
- const noPreviewAnywhere = systemSubscriberCount === 0;
- const noPreviewOnThisDoc = subscriberCount === 0;
-
- const hints = Array.isArray(result.hints) ? result.hints : undefined;
-
- const summaryResult =
- result.summary && typeof result.summary === 'object'
- ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
- : undefined;
- const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
-
- const writeWarningParse = WriteWarningSchema.safeParse(result.warning);
- const writeWarning = writeWarningParse.success ? writeWarningParse.data : undefined;
-
- const noOpNote = emptyAppendNoOpNote(w.position, args.markdown);
- const lines: string[] = [
- noOpNote ??
- (w.fromTemplate !== undefined
- ? `Written successfully (instantiated from template "${w.fromTemplate}").`
- : `Written successfully (${w.position}).`),
- ];
- const fmNote = frontmatterIgnoredNote(w.position, args.markdown);
- if (fmNote) lines.push(fmNote);
- if (w.extensionNote) lines.push(w.extensionNote);
- if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
- if (summaryHint) lines.push(summaryHint);
- if (hints) {
- for (const hint of hints) {
- if (hint.message) lines.push(hint.message);
- }
- }
- if (writeWarning) {
- lines.push(
- writeWarning.kind === 'content-divergence'
- ? `⚠ Content divergence: ${writeWarning.actualBytes} actual bytes vs ${writeWarning.intendedBytes} intended (byteDelta=${writeWarning.byteDelta}). ${writeWarning.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`
- : `⚠ ${writeWarning.hint ?? 'An out-of-band edit was reconciled into this document before your write landed on top — re-read for the combined result.'}`,
- );
- }
- const text = lines.join('\n');
-
- if (
- !preview &&
- !noPreviewAnywhere &&
- !noPreviewOnThisDoc &&
- !hints &&
- !summaryResult &&
- !writeWarning
- ) {
- return textResult(text);
- }
-
- const structured: Record<string, unknown> = {};
- if (writeWarning) {
- structured.contentDivergence = writeWarning;
- }
- if (preview) {
- structured.previewUrl = preview.url;
- structured.previewUrlSource = preview.source;
- }
- if (noPreviewAnywhere) {
- structured.warning = buildPreviewAttachWarning(preview, autoOpen);
- }
- if (hints) {
- structured.hints = hints;
- }
- if (summaryResult) {
- structured.summary = summaryResult;
- }
- return textPlusStructured(text, structured);
- },
- );
-}
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
new file mode 100644
index 000000000..4838165f3
--- /dev/null
+++ b/packages/server/src/mcp/tools/write.ts
@@ -0,0 +1,773 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+import {
+ normalizeBridge,
+ renderInventoryFooter,
+ stripFrontmatter,
+} from '@inkeep/open-knowledge-core';
+import { stringify as stringifyYaml } from 'yaml';
+import { z } from 'zod';
+import { resolveContentDir, resolveLockDir } from '../../config/paths.ts';
+import { applyFolderFrontmatterPatch } from '../../content/folder-frontmatter-write.ts';
+import { dropEmpties } from '../../content/frontmatter-merge.ts';
+import { parentFolderOf } from '../../content/nested-folder-rules.ts';
+import { applySubstitution, todayIsoUtc } from '../../content/substitution.ts';
+import { resolveTemplatesAvailable } from '../../content/templates-resolver.ts';
+import { applyTemplateWrite } from '../../content/templates-write.ts';
+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
+import type { AgentIdentity } from '../agent-identity.ts';
+import {
+ formatContentDivergenceBrief,
+ formatContentDivergenceLine,
+ parseContentDivergence,
+} from './content-divergence.ts';
+import { resolveWithinRoot } from './path-safety.ts';
+import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
+import {
+ agentIdentityFields,
+ documentResultBaseShape,
+ HOCUSPOCUS_NOT_RUNNING_ERROR,
+ httpPost,
+ looseObjectArray,
+ nestDocResult,
+ normalizeDocName,
+ outputSchemaWithText,
+ previewAttachWarningField,
+ previewUrlOutputField,
+ previewUrlSourceField,
+ ROUTED_CWD_DESCRIPTION,
+ resolveProjectServerContext,
+ summaryArgSchema,
+ textPlusStructured,
+ textResult,
+} from './shared.ts';
+import {
+ exactlyOneTargetError,
+ FrontmatterArg,
+ PositionArg,
+ resolveTemplatePath,
+ splitTargetPath,
+ TEMPLATE_CONTENT_DESCRIBE,
+ TEMPLATE_PATH_DESCRIBE,
+} from './verb-schemas.ts';
+
+type FrontmatterPatch = Record<string, string | number | boolean | string[] | null>;
+
+const BASE_DESCRIPTION = [
+ 'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, 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`. 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 (fs-direct). `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',
+ '- `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.',
+].join('\n');
+
+export const DESCRIPTION = `${BASE_DESCRIPTION}\n${renderInventoryFooter()}`;
+
+interface WriteDeps {
+ serverUrl: ServerUrlOrResolver;
+ config: ConfigOrResolver;
+ resolveCwd: (explicit?: string) => Promise<string>;
+ identityRef?: { current: AgentIdentity };
+}
+
+interface DocSpec {
+ path: string;
+ content?: string;
+ template?: string;
+ frontmatter?: FrontmatterPatch;
+ position?: string;
+ summary?: string;
+}
+
+type WriteApiResult = Awaited<ReturnType<typeof httpPost>>;
+
+type WriteOneResult =
+ | {
+ docName: string;
+ ok: true;
+ position: string;
+ fromTemplate?: string;
+ extensionNote?: string;
+ raw: WriteApiResult;
+ }
+ | { docName: string; ok: false; error: string };
+
+function frontmatterIgnoredNote(position: string, markdown: string | undefined): string | null {
+ if ((position !== 'prepend' && position !== 'append') || !markdown) return null;
+ if (stripFrontmatter(markdown).frontmatter.trim() === '') return null;
+ return `Note: a \`---\` frontmatter block in this \`${position}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`;
+}
+
+function emptyAppendNoOpNote(position: string, markdown: string | undefined): string | null {
+ if ((position !== 'prepend' && position !== 'append') || markdown === undefined) return null;
+ if (stripFrontmatter(markdown).body !== '') return null;
+ return `No content to ${position} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`;
+}
+
+function docExtensionOnDisk(contentDir: string, docName: string): '.md' | '.mdx' | null {
+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {
+ const contained = resolveWithinRoot(contentDir, `${docName}${ext}`);
+ if (contained.ok && existsSync(contained.abs)) return ext;
+ }
+ return null;
+}
+
+function requestedDocExtension(rawDocName: string): '.md' | '.mdx' | null {
+ const lower = rawDocName.toLowerCase();
+ if (lower.endsWith('.mdx')) return '.mdx';
+ if (lower.endsWith('.md')) return '.md';
+ return null;
+}
+
+function extensionIgnoredNote(
+ requestedExt: '.md' | '.mdx' | null,
+ existingExt: '.md' | '.mdx' | null,
+ docName: string,
+): string | null {
+ if (requestedExt === null || existingExt === null || requestedExt === existingExt) return null;
+ return `Note: "${docName}" already exists as \`${docName}${existingExt}\`, so the requested \`${requestedExt}\` extension was not applied — the write went to \`${docName}${existingExt}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`;
+}
+
+function composeWithFrontmatter(frontmatter: FrontmatterPatch, body: string): string {
+ const cleaned = dropEmpties(frontmatter as Record<string, unknown>);
+ if (Object.keys(cleaned).length === 0) return body;
+ return `---\n${stringifyYaml(cleaned)}---\n${body}`;
+}
+
+async function writeOneDoc(
+ spec: DocSpec,
+ cwd: string,
+ contentDir: string,
+ url: string,
+ deps: WriteDeps,
+): Promise<WriteOneResult> {
+ const normalized = normalizeDocName(spec.path);
+ if (!normalized.ok) return { docName: spec.path, ok: false, error: normalized.error };
+ const docName = normalized.docName;
+ const identity = deps.identityRef?.current;
+
+ if (spec.template === undefined && spec.content === undefined) {
+ return {
+ docName,
+ ok: false,
+ error:
+ 'either `content` or `template` must be provided — omitting both would write empty content.',
+ };
+ }
+ if (spec.template !== undefined && spec.content !== undefined) {
+ return {
+ docName,
+ ok: false,
+ error:
+ 'TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls.',
+ };
+ }
+
+ let effectiveMarkdown = spec.content ?? '';
+ const hasFrontmatter = spec.frontmatter !== undefined && Object.keys(spec.frontmatter).length > 0;
+
+ const existingExt = docExtensionOnDisk(contentDir, docName);
+ const docExists = existingExt !== null;
+ const requestedExt = requestedDocExtension(spec.path);
+
+ let effectivePosition: string;
+ if (spec.position !== undefined) {
+ effectivePosition = spec.position;
+ } else if (docExists) {
+ return {
+ docName,
+ ok: false,
+ error: `"${docName}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`,
+ };
+ } else {
+ effectivePosition = 'replace';
+ }
+
+ if (spec.template !== undefined) {
+ const parentFolder = parentFolderOf(docName);
+ const available = resolveTemplatesAvailable(cwd, parentFolder, { depth: 1 });
+ const matched = available.find((t) => t.name === spec.template);
+ if (!matched) {
+ return {
+ docName,
+ ok: false,
+ error: `template "${spec.template}" not found for folder "${parentFolder || '.'}". Available: ${
+ available.length === 0
+ ? '(none)'
+ : available.map((t) => `${t.name} [${t.scope}]`).join(', ')
+ }. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`,
+ };
+ }
+ let templateContent: string;
+ try {
+ templateContent = readFileSync(resolvePath(cwd, matched.path), 'utf-8');
+ } catch (err) {
+ return {
+ docName,
+ ok: false,
+ error: `failed to read template at ${matched.path}: ${(err as Error).message}`,
+ };
+ }
+ const { body: templateBody } = stripFrontmatter(templateContent);
+ effectiveMarkdown = applySubstitution(templateBody, {
+ date: todayIsoUtc(),
+ user: identity?.displayName ?? '',
+ });
+ effectivePosition = 'replace';
+ } else if (hasFrontmatter) {
+ effectiveMarkdown = composeWithFrontmatter(
+ spec.frontmatter as FrontmatterPatch,
+ effectiveMarkdown,
+ );
+ effectivePosition = 'replace';
+ }
+
+ if (!docExists && normalizeBridge(effectiveMarkdown) === '') {
+ return {
+ docName,
+ ok: false,
+ error: `"${docName}" does not exist and the content is empty — provide non-empty content to create the document.`,
+ };
+ }
+
+ const result = await httpPost(url, '/api/agent-write-md', {
+ docName,
+ markdown: effectiveMarkdown,
+ position: effectivePosition,
+ ...(requestedExt !== null && !docExists ? { extension: requestedExt } : {}),
+ ...(spec.summary !== undefined ? { summary: spec.summary } : {}),
+ ...agentIdentityFields(identity),
+ });
+ if (!result.ok) {
+ const detail =
+ typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
+ return {
+ docName,
+ ok: false,
+ error: detail ? `${String(result.error)} (${detail})` : String(result.error),
+ };
+ }
+
+ if (spec.template !== undefined && hasFrontmatter) {
+ const fmResult = await httpPost(url, '/api/frontmatter-patch', {
+ docName,
+ patch: spec.frontmatter,
+ ...agentIdentityFields(identity),
+ });
+ if (!fmResult.ok) {
+ return {
+ docName,
+ ok: false,
+ error: `document created from template but frontmatter failed: ${String(fmResult.error)}`,
+ };
+ }
+ }
+
+ const extensionNote = extensionIgnoredNote(requestedExt, existingExt, docName);
+ return {
+ docName,
+ ok: true,
+ position: effectivePosition,
+ ...(spec.template !== undefined ? { fromTemplate: spec.template } : {}),
+ ...(extensionNote ? { extensionNote } : {}),
+ raw: result,
+ };
+}
+
+async function handleFolder(
+ folder: { path: string; frontmatter?: FrontmatterPatch },
+ summary: string | undefined,
+ contentDir: string,
+ url: string | undefined,
+ deps: WriteDeps,
+) {
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ const identity = deps.identityRef?.current;
+ const result = await httpPost(url, '/api/create-folder', {
+ path: folder.path,
+ ...(summary !== undefined ? { summary } : {}),
+ ...agentIdentityFields(identity),
+ });
+ if (!result.ok) {
+ const detail =
+ typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
+ return textResult(
+ detail ? `Error: ${result.error} (${detail})` : `Error: ${result.error}`,
+ true,
+ );
+ }
+
+ const lines = [`Created folder ${folder.path}.`];
+ if (folder.frontmatter !== undefined && Object.keys(folder.frontmatter).length > 0) {
+ const fm = applyFolderFrontmatterPatch({
+ anchorDir: contentDir,
+ folderRel: folder.path,
+ patch: folder.frontmatter as Record<string, unknown>,
+ });
+ if (!fm.ok) {
+ return textPlusStructured(
+ `Created folder ${folder.path}, but writing its properties failed: ${fm.error.message}. Use edit({ folder: { path: "${folder.path}", frontmatter } }) to retry the properties.`,
+ { folder: { ok: true, path: folder.path, frontmatterError: fm.error.message } },
+ );
+ }
+ if (fm.action === 'written') lines.push(`Set folder properties (${fm.path}).`);
+ }
+ return textPlusStructured(lines.join('\n'), { folder: { ok: true, path: folder.path } });
+}
+
+function handleTemplate(
+ template: {
+ path: string;
+ content: string;
+ frontmatter: { title: string } & Record<string, unknown>;
+ },
+ cwd: string,
+) {
+ const resolved = resolveTemplatePath(template.path);
+ if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ const { folder, name } = resolved;
+ const result = applyTemplateWrite({
+ projectDir: cwd,
+ folder,
+ name,
+ body: template.content,
+ frontmatter: {
+ title: template.frontmatter.title,
+ ...(typeof template.frontmatter.description === 'string'
+ ? { description: template.frontmatter.description }
+ : {}),
+ ...(Array.isArray(template.frontmatter.tags)
+ ? { tags: template.frontmatter.tags as string[] }
+ : {}),
+ },
+ });
+ if (!result.ok) {
+ return textResult(`Error: ${result.error.message}`, true);
+ }
+ return textPlusStructured(
+ `${result.created ? 'Created' : 'Updated'} template "${name}" in ${folder || '(root)'} (${result.path}).`,
+ { template: { ok: true, path: result.path, created: result.created } },
+ );
+}
+
+async function handleAsset(
+ asset: { path: string; content?: string; source?: string },
+ cwd: string,
+ url: string | undefined,
+ deps: WriteDeps,
+) {
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ if ((asset.content === undefined) === (asset.source === undefined)) {
+ return textResult(
+ 'Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.',
+ true,
+ );
+ }
+ let bytes: Buffer;
+ try {
+ bytes =
+ asset.content !== undefined
+ ? Buffer.from(asset.content, 'base64')
+ : readFileSync(resolvePath(cwd, asset.source as string));
+ } catch (err) {
+ return textResult(`Error: could not read asset bytes: ${(err as Error).message}`, true);
+ }
+ if (bytes.byteLength === 0) {
+ return textResult('Error: asset is empty (0 bytes).', true);
+ }
+
+ const { folder, name: fileName } = splitTargetPath(asset.path);
+ const parentDocName = folder ? `${folder}/${fileName}` : fileName;
+
+ const identity = deps.identityRef?.current;
+ const query = new URLSearchParams();
+ if (identity?.connectionId) query.set('agentId', identity.connectionId);
+ if (identity?.displayName) query.set('agentName', identity.displayName);
+ const qs = query.toString();
+
+ const form = new FormData();
+ form.append('parentDocName', parentDocName);
+ form.append('file', new Blob([new Uint8Array(bytes)]), fileName);
+
+ let resBody: { ok: boolean; status: number; data?: Record<string, unknown>; error?: string };
+ try {
+ const res = await fetch(`${url}/api/upload${qs ? `?${qs}` : ''}`, {
+ method: 'POST',
+ body: form,
+ });
+ const data = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ resBody = res.ok
+ ? { ok: true, status: res.status, data: data ?? {} }
+ : {
+ ok: false,
+ status: res.status,
+ error:
+ (data && (typeof data.title === 'string' ? data.title : (data.error as string))) ||
+ `Upload failed (HTTP ${res.status}).`,
+ };
+ } catch (err) {
+ return textResult(`Error: upload request failed: ${(err as Error).message}`, true);
+ }
+ if (!resBody.ok) return textResult(`Error: ${resBody.error}`, true);
+
+ const src = typeof resBody.data?.src === 'string' ? resBody.data.src : undefined;
+ const path = typeof resBody.data?.path === 'string' ? resBody.data.path : undefined;
+ const deduped = resBody.data?.deduped === true;
+ const ref = src ?? path ?? fileName;
+ const text = [
+ `Uploaded asset to ${parentDocName}${deduped ? ' (deduplicated — identical bytes already present)' : ''}.`,
+ `Reference it in a doc with: ![${fileName}](${ref})`,
+ ].join('\n');
+ return textPlusStructured(text, {
+ asset: {
+ ok: true,
+ ...(src ? { src } : {}),
+ ...(path ? { path } : {}),
+ ...(deduped ? { deduped } : {}),
+ },
+ });
+}
+
+async function handleBatch(
+ documents: DocSpec[],
+ cwd: string,
+ contentDir: string,
+ url: string,
+ deps: WriteDeps,
+ lockDir: string,
+ autoOpen: boolean,
+) {
+ const results: WriteOneResult[] = [];
+ for (const spec of documents) {
+ results.push(await writeOneDoc(spec, cwd, contentDir, url, deps));
+ }
+ const docOut = results.map((r) => {
+ if (!r.ok) return { docName: r.docName, ok: false as const, error: r.error };
+ const preview = resolvePreviewUrl(r.docName, { lockDir });
+ const divergence = parseContentDivergence(r.raw.warning);
+ return {
+ docName: r.docName,
+ ok: true as const,
+ position: r.position,
+ ...(preview ? { previewUrl: preview.url } : {}),
+ ...(divergence ? { contentDivergence: divergence } : {}),
+ };
+ });
+ const okCount = docOut.filter((d) => d.ok).length;
+ const allOk = okCount === docOut.length;
+ const lines = documents.map((spec, i) => {
+ const r = results[i];
+ if (!r?.ok) return `Failed ${spec.path}: ${r?.error ?? 'unknown error'}`;
+ if (emptyAppendNoOpNote(r.position, spec.content)) {
+ return `No change to ${spec.path} — empty ${r.position}, document unchanged.`;
+ }
+ const d = docOut[i];
+ const base = `Wrote ${spec.path} (${r.position}).`;
+ return d?.ok && d.contentDivergence
+ ? `${base} ${formatContentDivergenceBrief(d.contentDivergence)}`
+ : base;
+ });
+ const perDocNotes = documents.flatMap((spec, i) => {
+ const r = results[i];
+ if (!r?.ok) return [];
+ const fmNote = frontmatterIgnoredNote(r.position, spec.content);
+ const notes = [...(fmNote ? [fmNote] : []), ...(r.extensionNote ? [r.extensionNote] : [])];
+ return notes.map((n) => `${spec.path} — ${n}`);
+ });
+ const text = [`${okCount}/${docOut.length} written.`, ...lines, ...perDocNotes].join('\n');
+ const structured: Record<string, unknown> = { documents: docOut };
+ const firstOk = results.find((r): r is Extract<WriteOneResult, { ok: true }> => r.ok);
+ if (firstOk && firstOk.raw.systemSubscriberCount === 0) {
+ const firstPreview = resolvePreviewUrl(firstOk.docName, { lockDir });
+ structured.warning = buildPreviewAttachWarning(firstPreview, autoOpen);
+ }
+ return textPlusStructured(text, structured, !allOk);
+}
+
+async function handleSingleDoc(
+ spec: DocSpec,
+ cwd: string,
+ contentDir: string,
+ url: string,
+ deps: WriteDeps,
+ lockDir: string,
+ autoOpen: boolean,
+) {
+ const w = await writeOneDoc(spec, cwd, contentDir, url, deps);
+ if (!w.ok) return textResult(`Error: ${w.error}`, true);
+
+ const result = w.raw;
+ const preview = resolvePreviewUrl(w.docName, { lockDir });
+ const subscriberCount =
+ typeof result.subscriberCount === 'number' ? result.subscriberCount : undefined;
+ const systemSubscriberCount =
+ typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;
+ const noPreviewAnywhere = systemSubscriberCount === 0;
+ const noPreviewOnThisDoc = subscriberCount === 0;
+ const hints = Array.isArray(result.hints) ? result.hints : undefined;
+ const summaryResult =
+ result.summary && typeof result.summary === 'object'
+ ? (result.summary as { value: string; truncatedFrom?: number; hint?: string })
+ : undefined;
+ const summaryHint = typeof summaryResult?.hint === 'string' ? summaryResult.hint : undefined;
+ const contentDivergence = parseContentDivergence(result.warning);
+
+ const noOpNote = emptyAppendNoOpNote(w.position, spec.content);
+ const lines: string[] = [
+ noOpNote ??
+ (w.fromTemplate !== undefined
+ ? `Written successfully (instantiated from template "${w.fromTemplate}").`
+ : `Written successfully (${w.position}).`),
+ ];
+ const fmNote = frontmatterIgnoredNote(w.position, spec.content);
+ if (fmNote) lines.push(fmNote);
+ if (w.extensionNote) lines.push(w.extensionNote);
+ if (noPreviewAnywhere && !preview) lines.push(START_UI_TEXT_HINT);
+ if (summaryHint) lines.push(summaryHint);
+ if (hints) {
+ for (const hint of hints) {
+ if (hint.message) lines.push(hint.message);
+ }
+ }
+ if (contentDivergence) {
+ lines.push(formatContentDivergenceLine(contentDivergence));
+ }
+ const text = lines.join('\n');
+
+ if (
+ !preview &&
+ !noPreviewAnywhere &&
+ !noPreviewOnThisDoc &&
+ !hints &&
+ !summaryResult &&
+ !contentDivergence
+ ) {
+ return textResult(text);
+ }
+ const document: Record<string, unknown> = {};
+ if (hints) document.hints = hints;
+ if (summaryResult) document.summary = summaryResult;
+ if (contentDivergence) document.contentDivergence = contentDivergence;
+ const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;
+ return textPlusStructured(text, nestDocResult(preview, warning, document));
+}
+
+export function register(server: ServerInstance, deps: WriteDeps): void {
+ const docTargetShape = {
+ path: z
+ .string()
+ .describe(
+ 'Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".',
+ ),
+ content: z
+ .string()
+ .optional()
+ .describe('The full Markdown body. Mutually exclusive with `template`.'),
+ template: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ "Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder.",
+ ),
+ frontmatter: FrontmatterArg.optional().describe(
+ "The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`.",
+ ),
+ position: PositionArg.optional(),
+ };
+
+ server.registerTool(
+ 'write',
+ {
+ description: DESCRIPTION,
+ inputSchema: {
+ document: z
+ .object(docTargetShape)
+ .optional()
+ .describe(
+ 'Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }',
+ ),
+ folder: z
+ .object({
+ path: z.string().describe('Folder path. Example: "meetings".'),
+ frontmatter: FrontmatterArg.optional().describe(
+ "The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.",
+ ),
+ })
+ .optional()
+ .describe(
+ 'Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }',
+ ),
+ template: z
+ .object({
+ path: z.string().describe(TEMPLATE_PATH_DESCRIBE),
+ content: z.string().describe(TEMPLATE_CONTENT_DESCRIBE),
+ frontmatter: z
+ .object({
+ title: z
+ .string()
+ .min(1)
+ .describe('Required — the label shown when an agent picks this template.'),
+ description: z
+ .string()
+ .optional()
+ .describe('Optional — shown beside the title in the template menu.'),
+ tags: z.array(z.string()).optional().describe('Optional — tags for the template.'),
+ })
+ .describe(
+ 'Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).',
+ ),
+ })
+ .optional()
+ .describe(
+ 'Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }',
+ ),
+ asset: z
+ .object({
+ path: z
+ .string()
+ .describe(
+ 'Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".',
+ ),
+ content: z.string().optional().describe('Base64 of the binary. Use for small files.'),
+ source: z
+ .string()
+ .optional()
+ .describe('Local filesystem path the server reads. Use for large files.'),
+ })
+ .optional()
+ .describe(
+ 'Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`.',
+ ),
+ documents: z
+ .array(z.object({ ...docTargetShape, summary: summaryArgSchema }))
+ .min(1)
+ .optional()
+ .describe(
+ 'Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`.',
+ ),
+ summary: summaryArgSchema,
+ cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
+ },
+ outputSchema: outputSchemaWithText({
+ document: z
+ .object({
+ hints: looseObjectArray.optional().describe('Server-provided write hints, when any.'),
+ ...documentResultBaseShape,
+ })
+ .optional()
+ .describe('Single-document write result (present when there is a doc-specific signal).'),
+ folder: z
+ .object({
+ ok: z.boolean(),
+ path: z.string(),
+ frontmatterError: z
+ .string()
+ .optional()
+ .describe(
+ 'Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.',
+ ),
+ })
+ .optional()
+ .describe('Folder-create result.'),
+ template: z
+ .object({
+ ok: z.boolean(),
+ path: z.string(),
+ created: z
+ .boolean()
+ .describe('true if created, false if an existing template updated.'),
+ })
+ .optional()
+ .describe('Template-create result.'),
+ asset: z
+ .object({
+ ok: z.boolean(),
+ src: z.string().optional().describe('The reference src to embed in a doc.'),
+ path: z.string().optional(),
+ deduped: z
+ .boolean()
+ .optional()
+ .describe('true when identical bytes already existed (no new file written).'),
+ })
+ .optional()
+ .describe('Asset-upload result.'),
+ documents: looseObjectArray
+ .optional()
+ .describe(
+ 'Batch write: per-doc result `{ docName, ok, position?, previewUrl?, contentDivergence?, error? }`.',
+ ),
+ previewUrl: previewUrlOutputField.optional(),
+ previewUrlSource: previewUrlSourceField,
+ warning: previewAttachWarningField,
+ }),
+ },
+ async (args: {
+ document?: Omit<DocSpec, 'summary'>;
+ folder?: { path: string; frontmatter?: FrontmatterPatch };
+ template?: {
+ path: string;
+ content: string;
+ frontmatter: { title: string } & Record<string, unknown>;
+ };
+ asset?: { path: string; content?: string; source?: string };
+ documents?: DocSpec[];
+ summary?: 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 { cwd, config, url } = context;
+ const lockDir = resolveLockDir(cwd);
+ const contentDir = resolveContentDir(config, cwd);
+ const autoOpen = config.appearance.preview.autoOpen;
+
+ if (args.documents !== undefined) {
+ const teaching = exactlyOneTargetError(args as Record<string, unknown>, [
+ 'document',
+ 'folder',
+ 'template',
+ 'asset',
+ 'documents',
+ ]);
+ if (teaching) return textResult(`Error: ${teaching}`, true);
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ return handleBatch(args.documents, cwd, contentDir, url, deps, lockDir, autoOpen);
+ }
+
+ const teaching = exactlyOneTargetError(args as Record<string, unknown>, [
+ 'document',
+ 'folder',
+ 'template',
+ 'asset',
+ ]);
+ if (teaching) return textResult(`Error: ${teaching}`, true);
+
+ if (args.document !== undefined) {
+ if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);
+ return handleSingleDoc(
+ { ...args.document, summary: args.summary },
+ cwd,
+ contentDir,
+ url,
+ deps,
+ lockDir,
+ autoOpen,
+ );
+ }
+ if (args.folder !== undefined)
+ return handleFolder(args.folder, args.summary, contentDir, url, deps);
+ if (args.template !== undefined) return handleTemplate(args.template, cwd);
+ return handleAsset(args.asset as NonNullable<typeof args.asset>, cwd, url, deps);
+ },
+ );
+}
diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.ts
index 7d4497cff..16eea7a08 100644
--- a/packages/server/src/shadow-repo.ts
+++ b/packages/server/src/shadow-repo.ts
@@ -892,6 +892,7 @@ export async function saveVersion(
contentRoot: string,
writers: WriterIdentity[],
branch = 'main',
+ summary?: string,
): Promise<SaveVersionResult> {
return withSpan(
'shadow.saveVersion',
@@ -901,7 +902,7 @@ export async function saveVersion(
'shadow.writer_count': writers.length,
},
},
- async () => saveVersionInner(shadow, contentRoot, writers, branch),
+ async () => saveVersionInner(shadow, contentRoot, writers, branch, summary),
);
}
@@ -910,6 +911,7 @@ async function saveVersionInner(
contentRoot: string,
writers: WriterIdentity[],
branch = 'main',
+ summary?: string,
): Promise<SaveVersionResult> {
const sg = shadowGit(shadow);
const gitPathspec = contentRoot || '.';
@@ -966,7 +968,8 @@ async function saveVersionInner(
color_seed: SERVICE_WRITER.id,
docs: [],
};
- const checkpointMessage = `${formatCheckpointSubject('Checkpoint version')}\n\n${formatOkActor(checkpointActorEntry)}`;
+ const checkpointSubject = summary?.trim() ? summary.trim() : 'Checkpoint version';
+ const checkpointMessage = `${formatCheckpointSubject(checkpointSubject)}\n\n${formatOkActor(checkpointActorEntry)}`;
const checkpointArgs = ['commit-tree', shadowTreeSha, '-m', checkpointMessage];
for (const p of uniqueParents) {
checkpointArgs.push('-p', p);