Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8207 Reject unsafe agent control bytes on main (#5857)

Andrew Mikofalvy6bd0226c6eb9
diff --git a/.changeset/refuse-agent-control-content.md b/.changeset/refuse-agent-control-content.md
new file mode 100644
index 000000000..26928c0a8
--- /dev/null
+++ b/.changeset/refuse-agent-control-content.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge-core": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge": patch
+---
+
+Document, template, skill-body and Markdown bundle-file writes now reject unsupported control characters with actionable errors, including template writes from agents and the app. Stored bytes are not rewritten; existing templates, skills and Markdown bundle files must have these characters removed before full saves or edits.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 7773736ac..b0452b0fb 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -27,7 +27,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `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. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). 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 or folder to send to a teammate (`kind` disambiguates; `path: ""` with `kind: "folder"` shares the content root). Responses carry a `freshness` verdict — `current`, `stale` (unpushed changes), or `absent` (never pushed), omitted when the probe can't run — and prepend a matching warning to relay with the link. Read-only against `.git/`; never publishes |
-| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
+| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) |
| `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |
| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`. Links to the moved document keep pointing to it. The old path stops existing; no redirect or stub is left behind. The move can also edit referring documents to preserve their existing link targets, including links to documents that did not move when the new path would otherwise take precedence. Correctly resolving shorthand stays unchanged; necessary wiki rewrites preserve displayed text, aliases and headings. Renaming or moving a page in the app's sidebar rewrites links the same way, so the old name stays visible as link text. A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything |
@@ -68,6 +68,38 @@ The write tools (`write`, `edit`, `move`, `install`, `checkpoint`, `restore_vers
Cap is 80 characters. Avoid secrets and PII; summaries persist to git history.
+## Markdown input admission
+
+New Markdown text rejects decoded C0 controls U+0000–U+001F except TAB (U+0009), LF (U+000A), and CR (U+000D). Remove unsupported characters or replace them with printable escapes such as literal `\u0000`. Printable escapes, DEL, C1, and other admitted Unicode are preserved; binary assets and non-Markdown bundle files are not covered by this rule.
+
+The shared HTTP request schemas guard these nine fields before any write, rename, agent session, or contributor mutation:
+
+| HTTP input field | MCP surface |
+| --- | --- |
+| `POST /api/agent-write`: `content` | HTTP-only document text input |
+| `POST /api/agent-write-md`: `markdown` | `write.document.content`, including frontmatter composition or template expansion |
+| `POST /api/agent-patch`: `replace` | `edit.document.replace`; `find` remains unrestricted |
+| `POST /api/agent-write-batch`: `docs[i].markdown` | Direct HTTP batch; MCP `documents` uses separate writes |
+| `PUT /api/template`: `body` | `write.template.content` and reconstructed template edits |
+| `POST /api/template`: `body` | Supplied replacement body on an HTTP move |
+| `PUT /api/skill`: `body` | `write.skill.body` and reconstructed skill edits |
+| `POST /api/skill`: `body` | Supplied replacement body on an HTTP move |
+| `PUT /api/skill-file`: `content` | `write.skill.files[i].content` and reconstructed file edits, when the writer's normalized final path segment has a case-insensitive `.md`/`.mdx` suffix |
+
+Markdown bundle admission applies in project and global scope, including Markdown files under `scripts/` or `assets/`; the inferred file kind does not exempt them. Backslashes become slashes, and empty or `.` segments are removed before this decision; MCP forwards the resolver's canonical path. Other suffixes, including `.md.bak`, remain opaque.
+
+A refusal returns HTTP 400 with problem type `urn:ok:error:invalid-request` and server-derived extension `contentControlAdmission: true`. This extension is derived from the control validator's issue metadata, not from echoed input or error-message text; unrelated validation errors do not carry it. Its detail names the field, first offending code point (for example `U+0000`), and **zero-based UTF-16 code-unit offset in that submitted field**, without echoing content. Each invalid field gets its first issue; an invalid HTTP batch may report multiple indexed issues. MCP returns a tool error retaining those details and the remove-or-printable-escape remedy. A document write's `markdown` offset can refer to composed Markdown **including frontmatter**, or generated template Markdown **after substitution**, not just the supplied body. Template and skill offsets refer to the whole submitted `body`; bundle-file offsets include the whole file, including YAML frontmatter.
+
+Existing stored bytes are not rewritten. Document body `find` may match historical controls, and a clean `replace` can repair one occurrence without removing unrelated historical bytes; clean append/prepend deltas, loading, undo, and restore do not rescan old content. HTTP template/skill moves that omit `body` preserve the historical body.
+
+Template metadata/body edits and skill description/body edits through MCP resubmit a full body. Markdown bundle edits resubmit the whole file. These calls refuse while any unsupported historical control remains in that payload, even if the requested edit only changes metadata or repairs another occurrence. Submit a fully cleaned replacement with the required template/skill metadata instead. A NUL-containing bundle file also hits the existing HTTP 415 binary-read refusal before MCP can perform find/replace; use a known complete clean file replacement.
+
+### Batch admission and retries
+
+`POST /api/agent-write-batch` validates the whole request before processing. One invalid entry rejects the request with 400 and **no sibling writes**. After validation succeeds, runtime failures retain per-entry outcomes and partial success.
+
+MCP `write({ documents: [...] })` writes entries sequentially and returns ordered results with an overall tool error if any fails. Successful entries before and after a refused entry stay written. MCP `skill.files` similarly aggregates sequential per-file outcomes. Retry only failed entries after correcting the input; do not resend successful siblings.
+
## Conflict-aware writes
A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OpenKnowledge's own reconciliation of the editor against disk. Reconciliation covers `stale-external-write`, which protects an acknowledged edit when another app restores the exact older file version, even with GitHub sync disabled. Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses a conflicted doc with an RFC 9457 problem response (409) that names the kind and the strategies that apply to it:
@@ -96,7 +128,7 @@ A write whose document path cannot be resolved inside the content directory retu
A write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. Retry only after the filesystem fault is repaired.
-A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so there is nothing to resolve. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which are never refused. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.
+A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so there is nothing to resolve. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). After whole-request schema validation succeeds, `POST /api/agent-write-batch` keeps its `200` success envelope; each concurrent-overwrite refusal carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Invalid input instead rejects the whole request before processing. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.
A write refused because the server is at its limit of concurrent agent write sessions returns `urn:ok:error:too-many-agent-sessions` (503): nothing was written, so it is safe to repeat. The problem body says so in `detail`, carries `committed: false`, and carries `retryAfterSeconds` alongside a matching `Retry-After` header. `POST /api/agent-write-md`, `POST /api/agent-patch`, `POST /api/frontmatter-patch` and `POST /api/lint/fix` answer this way, and the `write`, `edit` and `lint` fix tools append the detail and the bound to their error text (`Retry after 10s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type, `detail`, `committed: false` and `retryAfterSeconds` in its `error`, while sibling entries are unaffected. Wait that long and repeat the request. A `write` from a `template` creates the document before it patches the frontmatter, so when only that patch is refused the tool says so and the document already exists: apply the frontmatter with `edit` instead of repeating the `write`. For any other frontmatter failure on that path, re-read the document before changing it, because the patch may have been applied.
diff --git a/knip.config.ts b/knip.config.ts
index 0004a763a..69344114d 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -149,15 +149,11 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: [
- 'yjs',
- ],
+ ignoreDependencies: ['yjs'],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/package.json b/packages/app/package.json
index 6500f8fa5..57b8955ed 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -39,7 +39,7 @@
"measure:stress": "bash scripts/measure-stress.sh",
"measure:sweep": "bash scripts/measure-sweep.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/empty-bullet-before-link.e2e.ts tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/settings-close-button.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/harness-port-ownership.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts",
+ "test:e2e": "playwright test tests/stress/empty-bullet-before-link.e2e.ts tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/settings-close-button.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/harness-port-ownership.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts tests/stress/template-admission-detail.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
diff --git a/packages/app/src/components/TemplateForm-admission-classification.dom.test.tsx b/packages/app/src/components/TemplateForm-admission-classification.dom.test.tsx
new file mode 100644
index 000000000..730ba5b34
--- /dev/null
+++ b/packages/app/src/components/TemplateForm-admission-classification.dom.test.tsx
@@ -0,0 +1,182 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { toast } from 'sonner';
+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';
+import type { BootedServer } from '../../../server/src/boot.ts';
+import { bootCompositionRig, rawRequest } from '../../../server/src/composition-rig.test-helper.ts';
+import { moveTemplate, saveTemplate } from '../lib/folder-config-api.ts';
+import { composeDocBody, useTemplateForm } from './TemplateForm.tsx';
+
+const nativeFetch = globalThis.fetch;
+let root: string;
+let server: BootedServer;
+let sequence = 0;
+const templatePath = (name: string) => join(root, 'templates', '.ok', 'templates', `${name}.md`);
+
+async function post(method: 'PUT' | 'POST', input: object) {
+ return rawRequest(server.port, '/api/template', {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+}
+
+async function seed(name: string) {
+ const result = await saveTemplate({
+ folder: 'templates',
+ name,
+ frontmatter: { title: 'Existing' },
+ body: 'Existing body.\n',
+ });
+ expect(result.ok, JSON.stringify(result)).toBe(true);
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-template-admission-classification-'));
+ mkdirSync(join(root, 'templates'));
+ server = await bootCompositionRig(root);
+ await server.ready;
+ vi.stubGlobal('fetch', ((input: string | URL | Request, init?: RequestInit) =>
+ nativeFetch(
+ typeof input === 'string' ? new URL(input, `http://127.0.0.1:${server.port}`) : input,
+ init,
+ )) satisfies typeof fetch);
+}, 60_000);
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+afterAll(async () => {
+ vi.unstubAllGlobals();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+test.each([
+ {
+ label: 'invalid frontmatter title',
+ frontmatter: { title: '' },
+ body: 'Safe.',
+ code: 'TEMPLATE_TITLE_REQUIRED',
+ },
+ {
+ label: 'unknown body substitution',
+ frontmatter: { title: 'Existing' },
+ body: '{{unrecognised}}',
+ code: 'TEMPLATE_UNKNOWN_VARIABLE',
+ },
+])(
+ 'real template save $label keeps its previous title-only error',
+ async ({ frontmatter, body, code }) => {
+ const name = `classification-save-${++sequence}`;
+ await seed(name);
+ const original = readFileSync(templatePath(name));
+ const input = { folder: 'templates', name, frontmatter, body };
+ const response = await post('PUT', input);
+ expect(response.status, response.body).toBe(400);
+ const problem = JSON.parse(response.body) as { title: string; detail: string };
+ expect(problem.detail).toBe(code);
+ const result = await saveTemplate(input);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect.soft(result.error).toBe(problem.title);
+ expect.soft(readFileSync(templatePath(name))).toEqual(original);
+ },
+);
+
+test('real bodyless template rename to an existing target keeps its previous title-only error', async () => {
+ const fromName = `classification-move-${++sequence}`;
+ const toName = `${fromName}-occupied`;
+ await seed(fromName);
+ await seed(toName);
+ const source = readFileSync(templatePath(fromName));
+ const target = readFileSync(templatePath(toName));
+ const input = { fromFolder: 'templates', fromName, toFolder: 'templates', toName };
+ const response = await post('POST', input);
+ expect(response.status, response.body).toBe(409);
+ const problem = JSON.parse(response.body) as { title: string; detail: string };
+ expect(problem.detail).toBe('TEMPLATE_EXISTS');
+ const result = await moveTemplate(input);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect.soft(result.error).toBe(problem.title);
+ expect.soft(readFileSync(templatePath(fromName))).toEqual(source);
+ expect.soft(readFileSync(templatePath(toName))).toEqual(target);
+});
+
+test.each(['markdown', 'property'] as const)(
+ 'actual form refusal qualifies full submitted body offsets for a control in %s with type and properties',
+ async (location) => {
+ const name = `classification-coordinate-${++sequence}`;
+ await seed(name);
+ const original = readFileSync(templatePath(name));
+ const initialBody =
+ location === 'markdown'
+ ? '---\ntype: note\nstatus: draft\n---\n\nx😀\u0000private-tail'
+ : '---\ntype: note\nstatus: x😀\u0000private-tail\n---\n\nSafe body.\n';
+ const errorToast = vi.spyOn(toast, 'error');
+ const committed = vi.fn();
+ const { result } = renderHook(() =>
+ useTemplateForm({
+ mode: 'edit',
+ folderPath: 'templates',
+ scope: 'local',
+ initial: { name, title: 'Existing', description: '', body: initialBody },
+ onCommitted: committed,
+ }),
+ );
+ const submittedBody = composeDocBody({
+ type: result.current.type,
+ properties: result.current.properties,
+ markdown: result.current.body,
+ });
+ expect(submittedBody).toContain('type: note');
+ expect(submittedBody).toContain('status: ');
+ const response = await post('PUT', {
+ folder: 'templates',
+ name,
+ frontmatter: { title: 'Existing' },
+ body: submittedBody,
+ });
+ expect(response.status, response.body).toBe(400);
+ const problem = JSON.parse(response.body) as { title: string; detail: string };
+ expect(problem.detail).toContain('U+0000');
+ expect(problem.detail).toMatch(
+ new RegExp(`offset\\D*${submittedBody.indexOf('\u0000')}\\b`, 'i'),
+ );
+ expect.soft(problem.detail).toMatch(/full submitted (?:body|field|text)/i);
+ expect.soft(problem.detail).toMatch(/including[^.]*frontmatter/i);
+ await act(async () => result.current.submit());
+ expect(errorToast).toHaveBeenCalledTimes(1);
+ expect.soft(errorToast.mock.calls[0]?.[0]).toContain(problem.detail);
+ expect.soft(committed).not.toHaveBeenCalled();
+ expect.soft(readFileSync(templatePath(name))).toEqual(original);
+ expect.soft(existsSync(templatePath(`${name}-renamed`))).toBe(false);
+ },
+);
+
+test('real clean template body and property composition still saves byte-exact', async () => {
+ const name = `classification-clean-${++sequence}`;
+ const body = composeDocBody({
+ type: 'note',
+ properties: [{ id: 'status', key: 'status', value: 'draft' }],
+ markdown: 'Exact\tline\r\nPrintable \\u0000 😀\u007f\u0080\u009f.\n',
+ });
+ const saved = await saveTemplate({
+ folder: 'templates',
+ name,
+ frontmatter: { title: 'Clean' },
+ body,
+ });
+ expect(saved.ok, JSON.stringify(saved)).toBe(true);
+ const response = await rawRequest(
+ server.port,
+ `/api/template?${new URLSearchParams({ folder: 'templates', name })}`,
+ );
+ expect(response.status, response.body).toBe(200);
+ expect(JSON.parse(response.body).template.body).toBe(body);
+});
diff --git a/packages/app/src/components/TemplateForm-admission-detail.dom.test.tsx b/packages/app/src/components/TemplateForm-admission-detail.dom.test.tsx
new file mode 100644
index 000000000..2ffde9879
--- /dev/null
+++ b/packages/app/src/components/TemplateForm-admission-detail.dom.test.tsx
@@ -0,0 +1,164 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { toast } from 'sonner';
+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';
+import type { BootedServer } from '../../../server/src/boot.ts';
+import { bootCompositionRig, rawRequest } from '../../../server/src/composition-rig.test-helper.ts';
+import { moveTemplate, saveTemplate } from '../lib/folder-config-api.ts';
+import { useTemplateForm } from './TemplateForm.tsx';
+
+const body = 'private-prefix x😀\u0000private-tail';
+const nativeFetch = globalThis.fetch;
+let root: string;
+let server: BootedServer;
+let sequence = 0;
+
+function templatePath(name: string) {
+ return join(root, 'templates', '.ok', 'templates', `${name}.md`);
+}
+
+async function refusal(method: 'PUT' | 'POST', name: string, toName: string) {
+ const input =
+ method === 'PUT'
+ ? { folder: 'templates', name, frontmatter: { title: 'Existing' }, body }
+ : {
+ fromFolder: 'templates',
+ fromName: name,
+ toFolder: 'templates',
+ toName,
+ frontmatter: { title: 'Existing' },
+ body,
+ };
+ const response = await rawRequest(server.port, '/api/template', {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ expect(response.status, response.body).toBe(400);
+ const problem = JSON.parse(response.body) as { title: string; detail: string };
+ expect(problem.detail).toContain('U+0000');
+ expect(problem.detail).toMatch(/body/i);
+ expect(problem.detail).toMatch(/UTF-?16/i);
+ expect(problem.detail).toMatch(new RegExp(`offset\\D*${'private-prefix x😀'.length}\\b`, 'i'));
+ expect(problem.detail).not.toContain('private-prefix');
+ expect(problem.detail).not.toContain('private-tail');
+ return problem;
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-template-renderer-detail-'));
+ mkdirSync(join(root, 'templates', '.ok', 'templates'), { recursive: true });
+ server = await bootCompositionRig(root);
+ await server.ready;
+ vi.stubGlobal('fetch', ((input: string | URL | Request, init?: RequestInit) =>
+ nativeFetch(
+ typeof input === 'string' ? new URL(input, `http://127.0.0.1:${server.port}`) : input,
+ init,
+ )) satisfies typeof fetch);
+}, 60_000);
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+afterAll(async () => {
+ vi.unstubAllGlobals();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+test.each(['PUT', 'POST'] as const)(
+ 'actual template API %s caller preserves the real HTTP admission detail',
+ async (method) => {
+ const name = `api-detail-${++sequence}`;
+ const toName = `${name}-renamed`;
+ const original = '---\ntitle: Existing\n---\nExisting body.\n';
+ writeFileSync(templatePath(name), original);
+ const problem = await refusal(method, name, toName);
+ const result =
+ method === 'PUT'
+ ? await saveTemplate({
+ folder: 'templates',
+ name,
+ frontmatter: { title: 'Existing' },
+ body,
+ })
+ : await moveTemplate({
+ fromFolder: 'templates',
+ fromName: name,
+ toFolder: 'templates',
+ toName,
+ frontmatter: { title: 'Existing' },
+ body,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect.soft(result.error).toContain(problem.detail);
+ expect.soft(readFileSync(templatePath(name), 'utf8')).toBe(original);
+ expect.soft(existsSync(templatePath(toName))).toBe(false);
+ },
+);
+
+test.each([false, true])(
+ 'actual template form submit shows the actionable real HTTP detail (rename=%s)',
+ async (rename) => {
+ const name = `form-detail-${++sequence}`;
+ const toName = `${name}-renamed`;
+ const original = `---\ntitle: Existing\n---\n${body}`;
+ writeFileSync(templatePath(name), original);
+ const problem = await refusal(rename ? 'POST' : 'PUT', name, toName);
+ const errorToast = vi.spyOn(toast, 'error');
+ const committed = vi.fn();
+ const { result } = renderHook(() =>
+ useTemplateForm({
+ mode: 'edit',
+ folderPath: 'templates',
+ scope: 'local',
+ initial: { name, title: 'Existing', description: '', body },
+ onCommitted: committed,
+ }),
+ );
+ if (rename) await act(async () => result.current.setSlug(toName));
+ await act(async () => result.current.submit());
+ expect(errorToast).toHaveBeenCalledTimes(1);
+ expect.soft(errorToast.mock.calls[0]?.[0]).toContain(problem.detail);
+ expect.soft(committed).not.toHaveBeenCalled();
+ expect.soft(result.current.isSaving).toBe(false);
+ expect.soft(result.current.canSubmit).toBe(true);
+ expect.soft(readFileSync(templatePath(name), 'utf8')).toBe(original);
+ expect.soft(existsSync(templatePath(toName))).toBe(false);
+ },
+);
+
+test('actual template callers still save and rename admitted content byte-exact', async () => {
+ const name = `safe-detail-${++sequence}`;
+ const toName = `${name}-renamed`;
+ const allowed = 'Exact\tline\r\nPrintable \\u0000 😀\u007f\u0080\u009f.\n';
+ const saved = await saveTemplate({
+ folder: 'templates',
+ name,
+ frontmatter: { title: 'Safe' },
+ body: allowed,
+ });
+ expect(saved.ok, JSON.stringify(saved)).toBe(true);
+ const moved = await moveTemplate({
+ fromFolder: 'templates',
+ fromName: name,
+ toFolder: 'templates',
+ toName,
+ frontmatter: { title: 'Moved' },
+ body: allowed,
+ });
+ expect(moved.ok, JSON.stringify(moved)).toBe(true);
+ expect(existsSync(templatePath(name))).toBe(false);
+ expect(readFileSync(templatePath(toName), 'utf8')).toContain(allowed);
+ const response = await rawRequest(
+ server.port,
+ `/api/template?${new URLSearchParams({ folder: 'templates', name: toName })}`,
+ );
+ expect(response.status, response.body).toBe(200);
+ expect(JSON.parse(response.body).template.body).toBe(allowed);
+});
diff --git a/packages/app/src/lib/folder-config-api.ts b/packages/app/src/lib/folder-config-api.ts
index 53d8bc45a..706bb6e79 100644
--- a/packages/app/src/lib/folder-config-api.ts
+++ b/packages/app/src/lib/folder-config-api.ts
@@ -8,9 +8,9 @@ interface TemplateFrontmatterFields {
description?: string;
}
-async function readErrorBody(res: Response): Promise<string> {
+async function readErrorBody(res: Response, includeDetail = false): Promise<string> {
const body = (await res.json().catch(() => null)) as unknown;
- return parseApiError(body) ?? `HTTP ${res.status}`;
+ return parseApiError(body, includeDetail) ?? `HTTP ${res.status}`;
}
export async function saveFolderConfig(
@@ -45,7 +45,7 @@ export async function saveTemplate(input: {
body: JSON.stringify(input),
});
if (!res.ok) {
- return { ok: false, error: await readErrorBody(res) };
+ return { ok: false, error: await readErrorBody(res, true) };
}
const payload = (await res.json().catch(() => null)) as {
created?: boolean;
@@ -95,7 +95,7 @@ export async function moveTemplate(input: {
body: JSON.stringify(input),
});
if (!res.ok) {
- return { ok: false, error: await readErrorBody(res) };
+ return { ok: false, error: await readErrorBody(res, true) };
}
const payload = (await res.json().catch(() => null)) as { committed?: boolean } | null;
emitTemplatesChanged();
diff --git a/packages/app/src/lib/parse-api-error.ts b/packages/app/src/lib/parse-api-error.ts
index b7ac05ee2..1690a63cd 100644
--- a/packages/app/src/lib/parse-api-error.ts
+++ b/packages/app/src/lib/parse-api-error.ts
@@ -1,12 +1,23 @@
interface RfcProblemBody {
+ type?: unknown;
+ contentControlAdmission?: unknown;
title?: unknown;
detail?: unknown;
}
-export function parseApiError(body: unknown): string | undefined {
+export function parseApiError(body: unknown, includeDetail = false): string | undefined {
if (body === null || typeof body !== 'object') return undefined;
const candidate = body as RfcProblemBody;
if (typeof candidate.title === 'string' && candidate.title.length > 0) {
+ if (
+ includeDetail &&
+ candidate.type === 'urn:ok:error:invalid-request' &&
+ candidate.contentControlAdmission === true &&
+ typeof candidate.detail === 'string' &&
+ candidate.detail.length > 0
+ ) {
+ return `${candidate.title} (${candidate.detail})`;
+ }
return candidate.title;
}
return undefined;
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 4549c74b3..a50b00123 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 4fc2c11f9..6fcdc23f2 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 9f2f6feb6..40b5cdfd6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 2a085742b..93666af70 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 878d5196b..867598d34 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 4ada3cf26..0970ac12f 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index cbe2b705f..b632185e1 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,4 +1,3 @@
-
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index 89bc9b4d9..c530ce4ba 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index a78aeb0e4..d3767adc9 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,4 +1,3 @@
-
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index e7cc69c3f..b076f955c 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 9ddcd0730..7935e35f8 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/stress/template-admission-detail.e2e.ts b/packages/app/tests/stress/template-admission-detail.e2e.ts
new file mode 100644
index 000000000..f0d73a20b
--- /dev/null
+++ b/packages/app/tests/stress/template-admission-detail.e2e.ts
@@ -0,0 +1,52 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { expect, test } from './_helpers';
+
+test('template creation shows actionable admission detail and accepts explicit printable repair', async ({
+ page,
+ workerServer,
+}, testInfo) => {
+ const name = `admission-${randomUUID()}`;
+ const path = join(workerServer.contentDir, '.ok', 'templates', `${name}.md`);
+ const unsafe = 'x😀\u0000private-tail\n';
+ const cleaned = 'x😀\\u0000private-tail\n';
+ await page.goto('/#settings');
+ await page.getByTestId('settings-sidebar-item-project-templates').click();
+ await page.getByTestId('settings-project-templates-new-button').click();
+ const dialog = page.getByRole('dialog', { name: 'New template' });
+ await dialog.getByTestId('template-name-input').fill(name);
+ await dialog.getByLabel('Starter content', { exact: true }).fill(unsafe);
+ const refused = page.waitForResponse(
+ (response) => response.url().endsWith('/api/template') && response.request().method() === 'PUT',
+ );
+ await dialog.getByRole('button', { name: 'Create template', exact: true }).click();
+ const response = await refused;
+ expect(response.status()).toBe(400);
+ const problem = await response.json();
+ expect(problem.detail).toContain('U+0000');
+ expect(problem.detail).toMatch(/offset\D*3\b/);
+ const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'U+0000' });
+ await expect(toast).toBeVisible();
+ await expect(toast).toHaveCSS('opacity', '1');
+ await expect(toast).toContainText(problem.detail);
+ await expect(toast).not.toContainText('private-tail');
+ await expect(dialog).toBeVisible();
+ expect(existsSync(path)).toBe(false);
+ await testInfo.attach('Actionable template refusal', {
+ body: await toast.screenshot({ animations: 'disabled' }),
+ contentType: 'image/png',
+ });
+ await toast.getByRole('button', { name: 'Close toast' }).click();
+ await expect(toast).not.toBeVisible();
+ await dialog.getByLabel('Starter content', { exact: true }).fill(cleaned);
+ const accepted = page.waitForResponse(
+ (candidate) =>
+ candidate.url().endsWith('/api/template') && candidate.request().method() === 'PUT',
+ );
+ await dialog.getByRole('button', { name: 'Create template', exact: true }).click();
+ expect((await accepted).status()).toBe(200);
+ await expect(dialog).not.toBeVisible();
+ expect(stripFrontmatter(readFileSync(path, 'utf8')).body).toBe(cleaned);
+});
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index ffd8fce06..e7e63f43d 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e4e1166a7..d2ed63871 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -2100,6 +2100,7 @@ export {
isValidDocName,
validateDocName,
} from './util/doc-name.ts';
+export { isMarkdownSkillFilePath, skillFilePathSegments } from './util/skill-file-path.ts';
export { applyByPrefixSuffix } from './utils/apply-by-prefix-suffix.ts';
export { toDesktopAssetHref } from './utils/asset-href.ts';
export { ChunkedInsertError, chunkedYTextInsert } from './utils/chunked-insert.ts';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fb0ba5a7c..fc267cbea 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/schemas/api/_shared.ts b/packages/core/src/schemas/api/_shared.ts
index adcefa15d..ac99ba204 100644
--- a/packages/core/src/schemas/api/_shared.ts
+++ b/packages/core/src/schemas/api/_shared.ts
@@ -1,6 +1,28 @@
import { z } from 'zod';
+import { isDisallowedContentControl } from '../../util/content-controls.ts';
import { validateDocName } from '../../util/doc-name.ts';
+export function checkAgentContent(
+ value: string,
+ context: z.RefinementCtx,
+ path: string[] = [],
+): void {
+ for (let offset = 0; offset < value.length; offset++) {
+ const codePoint = value.charCodeAt(offset);
+ if (isDisallowedContentControl(codePoint)) {
+ context.addIssue({
+ code: 'custom',
+ path,
+ params: { contentControlAdmission: true },
+ message: `Disallowed content control U+${codePoint.toString(16).toUpperCase().padStart(4, '0')} at zero-based UTF-16 offset ${offset}. C0 controls allow only TAB, LF and CR. Remove the character or replace it with a printable escape such as \\u0000.`,
+ });
+ return;
+ }
+ }
+}
+
+export const agentContentField = z.string().superRefine(checkAgentContent);
+
function checkDocName(value: string, ctx: z.RefinementCtx): void {
const result = validateDocName(value);
if (!result.ok) {
diff --git a/packages/core/src/schemas/api/agent-write-control-admission.test.ts b/packages/core/src/schemas/api/agent-write-control-admission.test.ts
new file mode 100644
index 000000000..6c8bb8952
--- /dev/null
+++ b/packages/core/src/schemas/api/agent-write-control-admission.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, test } from 'vitest';
+import {
+ AgentPatchRequestSchema,
+ AgentWriteBatchEntrySchema,
+ AgentWriteBatchRequestSchema,
+ AgentWriteMdRequestSchema,
+ AgentWriteRequestSchema,
+} from './agent-write.ts';
+
+const excludedCodePoints = Array.from({ length: 32 }, (_, code) => code).filter(
+ (code) => ![9, 10, 13].includes(code),
+);
+const fields = [
+ { label: 'AgentWriteRequestSchema', name: 'content', schema: AgentWriteRequestSchema, body: {} },
+ {
+ label: 'AgentWriteMdRequestSchema',
+ name: 'markdown',
+ schema: AgentWriteMdRequestSchema,
+ body: {},
+ },
+ {
+ label: 'AgentPatchRequestSchema',
+ name: 'replace',
+ schema: AgentPatchRequestSchema,
+ body: { find: 'old' },
+ },
+ {
+ label: 'AgentWriteBatchEntrySchema',
+ name: 'markdown',
+ schema: AgentWriteBatchEntrySchema,
+ body: { docName: 'note' },
+ },
+] as const;
+
+describe.each(fields)('$label new $name admission', ({ name, schema, body }) => {
+ test('rejects leading and sole U+0000 at UTF-16 offset 0 without echoing input', () => {
+ for (const text of ['\u0000', '\u0000sensitive-tail😀']) {
+ const result = schema.safeParse({ ...body, [name]: text });
+ expect.soft(result.success).toBe(false);
+ if (result.success) continue;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual([name]);
+ const message = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(message).toContain('U+0000');
+ expect(message).toMatch(/UTF-?16/i);
+ expect(message).toMatch(/offset\D*0\b/i);
+ expect(message).not.toContain('\u0000');
+ expect(message).not.toContain('sensitive-tail😀');
+ }
+ });
+
+ test.each(excludedCodePoints)('rejects decoded C0 code point %i', (code) => {
+ const result = schema.safeParse({ ...body, [name]: `x😀${String.fromCharCode(code)}tail` });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual([name]);
+ const message = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(message).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect(message).toMatch(/UTF-?16/i);
+ expect(message).toMatch(/offset\D*3\b/i);
+ expect(message).not.toContain('x😀');
+ expect(message).not.toContain('tail');
+ expect(message).not.toContain(String.fromCharCode(code));
+ });
+
+ test.each([
+ '',
+ 'Printable \\u0000 \\u001F \\x00',
+ '\tline\ncarriage\rreturn\r\n',
+ String.fromCharCode(...Array.from({ length: 33 }, (_, n) => 127 + n)),
+ '😀 combining é and 日本語',
+ ])('accepts allowed text without altering its bytes: %j', (text) => {
+ const result = schema.safeParse({ ...body, [name]: text });
+ expect(result.success).toBe(true);
+ if (!result.success) return;
+ expect(result.data[name as keyof typeof result.data]).toBe(text);
+ });
+
+ test('bounds diagnostics without echoing long sensitive input', () => {
+ const secret = 'sensitive-document-body-'.repeat(200);
+ const result = schema.safeParse({
+ ...body,
+ [name]: `${secret}${String.fromCharCode(0).repeat(10_000)}`,
+ });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ const diagnostics = JSON.stringify(result.error.issues);
+ expect(diagnostics.length).toBeLessThan(2048);
+ expect(diagnostics).toContain('U+0000');
+ expect(diagnostics).not.toContain('sensitive-document-body');
+ });
+});
+
+test('patch find remains able to match every excluded code point in existing source', () => {
+ for (const code of excludedCodePoints) {
+ const find = String.fromCharCode(code);
+ expect(AgentPatchRequestSchema.parse({ find, replace: '\\u0000' }).find).toBe(find);
+ }
+});
+
+test('mixed batch rejects the unsafe entry with an indexed field path', () => {
+ const result = AgentWriteBatchRequestSchema.safeParse({
+ docs: [
+ { docName: 'clean', markdown: '# Clean\n' },
+ { docName: 'unsafe', markdown: `x${String.fromCharCode(31)}` },
+ ],
+ });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual(['docs', 1, 'markdown']);
+});
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index 5d5a0214e..93fafa95e 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -10,6 +10,7 @@ import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
import { FRONTMATTER_TYPES, FrontmatterValueSchema } from '../../frontmatter/schema.ts';
import { ProblemTypeSchema } from './_envelope.ts';
import {
+ agentContentField,
agentIdentityFields,
requiredSafeDocNameField,
safeDocNameField,
@@ -20,7 +21,7 @@ export const AgentWriteRequestSchema = z
.object({
docName: safeDocNameField,
summary: summaryField,
- content: z.string().optional(),
+ content: agentContentField.optional(),
...agentIdentityFields,
})
.loose() satisfies StandardSchemaV1;
@@ -30,7 +31,7 @@ export const AgentWriteMdRequestSchema = z
.object({
docName: safeDocNameField,
summary: summaryField,
- markdown: z.string(),
+ markdown: agentContentField,
position: z.enum(['append', 'prepend', 'replace']).optional(),
extension: z.enum(SUPPORTED_DOC_EXTENSIONS).optional(),
...agentIdentityFields,
@@ -43,7 +44,7 @@ export const AgentPatchRequestSchema = z
docName: safeDocNameField,
summary: summaryField,
find: z.string().min(1),
- replace: z.string(),
+ replace: agentContentField,
offset: z.number().int().nonnegative().optional(),
...agentIdentityFields,
})
@@ -286,7 +287,7 @@ export const AGENT_WRITE_BATCH_MAX_DOCS = 100;
export const AgentWriteBatchEntrySchema = z
.object({
docName: requiredSafeDocNameField,
- markdown: z.string(),
+ markdown: agentContentField,
position: z.enum(['append', 'prepend', 'replace']).optional(),
extension: z.enum(SUPPORTED_DOC_EXTENSIONS).optional(),
summary: summaryField,
diff --git a/packages/core/src/schemas/api/artifact-body-control-admission.test.ts b/packages/core/src/schemas/api/artifact-body-control-admission.test.ts
new file mode 100644
index 000000000..819b71675
--- /dev/null
+++ b/packages/core/src/schemas/api/artifact-body-control-admission.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'vitest';
+import {
+ SkillMoveRequestSchema,
+ SkillPutRequestSchema,
+ TemplateMoveRequestSchema,
+ TemplatePutRequestSchema,
+} from './tags-search.ts';
+
+const excludedCodePoints = Array.from({ length: 32 }, (_, code) => code).filter(
+ (code) => ![9, 10, 13].includes(code),
+);
+const fields = [
+ {
+ label: 'TemplatePutRequestSchema',
+ schema: TemplatePutRequestSchema,
+ request: { folder: '', name: 'meeting' },
+ },
+ {
+ label: 'TemplateMoveRequestSchema',
+ schema: TemplateMoveRequestSchema,
+ request: { fromFolder: '', fromName: 'meeting', toFolder: '', toName: 'renamed' },
+ },
+ {
+ label: 'SkillPutRequestSchema',
+ schema: SkillPutRequestSchema,
+ request: { name: 'review', frontmatter: { name: 'review', description: 'Review code' } },
+ },
+ {
+ label: 'SkillMoveRequestSchema',
+ schema: SkillMoveRequestSchema,
+ request: { scope: 'project', fromName: 'review', toName: 'renamed' },
+ },
+] as const;
+const allowed = '\tline\ncarriage\rreturn\r\nPrintable \\u0000 \\u001F \\x00 😀\u007f\u0080\u009f';
+
+describe.each(fields)('$label incoming body admission', ({ schema, request }) => {
+ test.each(excludedCodePoints)('rejects decoded C0 code point %i', (code) => {
+ const body = `x😀${String.fromCharCode(code)}private-tail`;
+ const result = schema.safeParse({ ...request, body });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual(['body']);
+ const message = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(message).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect(message).toMatch(/UTF-?16/i);
+ expect(message).toMatch(/offset\D*3\b/i);
+ expect(message).not.toContain('x😀');
+ expect(message).not.toContain('private-tail');
+ expect(message).not.toContain(String.fromCharCode(code));
+ });
+
+ test.each(['', allowed])('preserves admitted body bytes: %j', (body) => {
+ expect(schema.parse({ ...request, body }).body).toBe(body);
+ });
+
+ test('keeps omitted body valid for metadata-only moves and writes', () => {
+ expect(schema.parse(request).body).toBeUndefined();
+ });
+
+ test('reports a sole NUL at offset zero and bounds long non-echoing diagnostics', () => {
+ for (const body of ['\u0000', `private-prefix${'x'.repeat(4096)}${'\u0000'.repeat(10_000)}`]) {
+ const result = schema.safeParse({ ...request, body });
+ expect.soft(result.success).toBe(false);
+ if (result.success) continue;
+ const messages = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(messages).toContain('U+0000');
+ expect(messages).toMatch(new RegExp(`offset\\D*${body.indexOf('\u0000')}\\b`, 'i'));
+ expect(messages.length).toBeLessThan(2048);
+ expect(messages).not.toContain('private-prefix');
+ expect(messages).not.toContain('\u0000');
+ }
+ });
+});
diff --git a/packages/core/src/schemas/api/skill-file-control-admission.test.ts b/packages/core/src/schemas/api/skill-file-control-admission.test.ts
new file mode 100644
index 000000000..fe6c5a1de
--- /dev/null
+++ b/packages/core/src/schemas/api/skill-file-control-admission.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, test } from 'vitest';
+import { SkillFilePutRequestSchema } from './tags-search.ts';
+
+const excludedCodePoints = Array.from({ length: 32 }, (_, code) => code).filter(
+ (code) => ![9, 10, 13].includes(code),
+);
+const paths = ['references/admission.md', 'references/admission.mdx'] as const;
+const allowed = '\tline\ncarriage\rreturn\r\nPrintable \\u0000 \\u001F 😀\u007f\u0080\u009f';
+const request = (path: string, content: string, scope = 'project') => ({
+ scope,
+ name: 'admission',
+ path,
+ content,
+});
+
+describe.each(paths)('%s incoming Markdown file content', (path) => {
+ test.each(excludedCodePoints)('rejects decoded C0 code point %i', (code) => {
+ const result = SkillFilePutRequestSchema.safeParse(
+ request(path, `x😀${String.fromCharCode(code)}private-tail`),
+ );
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual(['content']);
+ const message = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(message).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect(message).toMatch(/UTF-?16/i);
+ expect(message).toMatch(/offset\D*3\b/i);
+ expect(message).not.toContain('x😀');
+ expect(message).not.toContain('private-tail');
+ expect(message).not.toContain(String.fromCharCode(code));
+ });
+
+ test.each(['', allowed])('preserves admitted content bytes: %j', (content) => {
+ expect(SkillFilePutRequestSchema.parse(request(path, content)).content).toBe(content);
+ });
+
+ test('reports sole NUL at offset zero and bounds non-echoing diagnostics', () => {
+ for (const content of [
+ '\u0000',
+ `private-prefix${'x'.repeat(4096)}${'\u0000'.repeat(10_000)}`,
+ ]) {
+ const result = SkillFilePutRequestSchema.safeParse(request(path, content));
+ expect.soft(result.success).toBe(false);
+ if (result.success) continue;
+ const message = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(message).toContain('U+0000');
+ expect(message).toMatch(new RegExp(`offset\\D*${content.indexOf('\u0000')}\\b`, 'i'));
+ expect(message.length).toBeLessThan(2048);
+ expect(message).not.toContain('private-prefix');
+ expect(message).not.toContain('\u0000');
+ }
+ });
+});
+
+test.each([
+ ['project', 'references/admission.MD'],
+ ['project', 'references/admission.MDX'],
+ ['global', 'references/admission.md'],
+ ['global', 'references/admission.mdx'],
+ ['project', 'scripts/admission.md'],
+ ['project', 'assets/admission.mdx'],
+])(
+ 'rejects Markdown controls independently of scope, suffix case or file kind: %s %s',
+ (scope, path) => {
+ expect(SkillFilePutRequestSchema.safeParse(request(path, '\u0000\u001f', scope)).success).toBe(
+ false,
+ );
+ },
+);
+
+test.each([
+ 'scripts/fixture.py',
+ 'assets/data.bin',
+ 'references/data.txt',
+ 'references/admission.md.bak',
+])('keeps non-Markdown content opaque: %s', (path) => {
+ const content = String.fromCharCode(...excludedCodePoints);
+ expect(SkillFilePutRequestSchema.parse(request(path, content)).content).toBe(content);
+});
diff --git a/packages/core/src/schemas/api/skill-file-path-alias-admission.test.ts b/packages/core/src/schemas/api/skill-file-path-alias-admission.test.ts
new file mode 100644
index 000000000..98eef756b
--- /dev/null
+++ b/packages/core/src/schemas/api/skill-file-path-alias-admission.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from 'vitest';
+import { SkillFilePutRequestSchema } from './tags-search.ts';
+
+const aliases = [
+ 'references/notes.md/',
+ 'references/notes.md/.',
+ 'references\\notes.md\\',
+ 'references//./notes.MDX/./',
+] as const;
+const allowed = '\tline\ncarriage\rreturn\\u0000 😀\u007f\u0080\u009f';
+const request = (path: string, content: string) => ({
+ name: 'alias-admission',
+ path,
+ content,
+});
+
+describe.each(aliases)('%s normalized Markdown admission', (path) => {
+ test.each([0, 31])('refuses decoded C0 %i in content', (code) => {
+ const result = SkillFilePutRequestSchema.safeParse(
+ request(path, `x😀${String.fromCharCode(code)}private-tail`),
+ );
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error.issues.map((issue) => issue.path)).toContainEqual(['content']);
+ const detail = result.error.issues.map((issue) => issue.message).join('\n');
+ expect(detail).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect(detail).toMatch(/UTF-?16.*offset\D*3\b/i);
+ expect(detail).not.toContain('private-tail');
+ });
+
+ test('keeps previously accepted aliases and admitted bytes', () => {
+ expect(SkillFilePutRequestSchema.parse(request(path, allowed)).content).toBe(allowed);
+ });
+});
+
+test.each(['scripts/fixture.sh/.', 'assets/fixture.svg/', 'references/notes.md.bak/'])(
+ 'keeps normalized non-Markdown content opaque: %s',
+ (path) => {
+ const content = 'opaque\u0000\u001f';
+ expect(SkillFilePutRequestSchema.parse(request(path, content)).content).toBe(content);
+ },
+);
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 06b346fa5..1b8831397 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -6,7 +6,13 @@ import {
SkillUserTargetEditorSchema,
} from '../../skill-targets/schema.ts';
import { SkillCostTiersSchema } from '../../skills-catalog/skill-cost.ts';
-import { agentIdentityFields, summaryField } from './_shared.ts';
+import { isMarkdownSkillFilePath } from '../../util/skill-file-path.ts';
+import {
+ agentContentField,
+ agentIdentityFields,
+ checkAgentContent,
+ summaryField,
+} from './_shared.ts';
export const TagSummaryEntrySchema = z
.object({
@@ -129,7 +135,7 @@ export const TemplatePutRequestSchema = z
.object({
folder: z.string(),
name: z.string(),
- body: z.string().optional(),
+ body: agentContentField.optional(),
frontmatter: TemplateFrontmatterSchema.optional(),
...agentIdentityFields,
summary: summaryField,
@@ -182,7 +188,7 @@ export const TemplateMoveRequestSchema = z
fromName: z.string(),
toFolder: z.string(),
toName: z.string(),
- body: z.string().optional(),
+ body: agentContentField.optional(),
frontmatter: TemplateFrontmatterSchema.optional(),
...agentIdentityFields,
summary: summaryField,
@@ -347,7 +353,7 @@ export const SkillPutRequestSchema = z
.object({
scope: SkillScopeSchema.default('project'),
name: z.string().meta({ description: 'Managed skill name to create or update.' }),
- body: z.string().optional(),
+ body: agentContentField.optional(),
frontmatter: SkillFrontmatterSchema,
...agentIdentityFields,
summary: summaryField,
@@ -443,7 +449,7 @@ export const SkillMoveRequestSchema = z
scope: SkillScopeSchema.default('project'),
fromName: z.string(),
toName: z.string(),
- body: z.string().optional(),
+ body: agentContentField.optional(),
frontmatter: SkillFrontmatterSchema.optional(),
...agentIdentityFields,
summary: summaryField,
@@ -652,7 +658,12 @@ export const SkillFilePutRequestSchema = z
...agentIdentityFields,
summary: summaryField,
})
- .strict() satisfies StandardSchemaV1;
+ .strict()
+ .superRefine((value, context) => {
+ if (isMarkdownSkillFilePath(value.path)) {
+ checkAgentContent(value.content, context, ['content']);
+ }
+ }) satisfies StandardSchemaV1;
export type SkillFilePutRequest = z.infer<typeof SkillFilePutRequestSchema>;
export const SkillFilePutSuccessSchema = z
diff --git a/packages/core/src/util/content-controls.ts b/packages/core/src/util/content-controls.ts
new file mode 100644
index 000000000..68c1aad10
--- /dev/null
+++ b/packages/core/src/util/content-controls.ts
@@ -0,0 +1,5 @@
+export function isDisallowedContentControl(codePoint: number): boolean {
+ return (
+ codePoint >= 0 && codePoint <= 31 && codePoint !== 9 && codePoint !== 10 && codePoint !== 13
+ );
+}
diff --git a/packages/core/src/util/skill-file-path.ts b/packages/core/src/util/skill-file-path.ts
new file mode 100644
index 000000000..b169a15d3
--- /dev/null
+++ b/packages/core/src/util/skill-file-path.ts
@@ -0,0 +1,16 @@
+import { SUPPORTED_DOC_EXTENSIONS } from '../constants/doc-extensions.ts';
+
+export function skillFilePathSegments(path: string): string[] {
+ return path
+ .replace(/\\/g, '/')
+ .split('/')
+ .filter((segment) => segment !== '' && segment !== '.');
+}
+
+export function isMarkdownSkillFilePath(path: string): boolean {
+ const name = skillFilePathSegments(path).at(-1);
+ return (
+ name !== undefined &&
+ SUPPORTED_DOC_EXTENSIONS.some((extension) => name.toLowerCase().endsWith(extension))
+ );
+}
diff --git a/packages/server/src/api-agent-control-admission.test.ts b/packages/server/src/api-agent-control-admission.test.ts
new file mode 100644
index 000000000..751a9437d
--- /dev/null
+++ b/packages/server/src/api-agent-control-admission.test.ts
@@ -0,0 +1,273 @@
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+import { __formatContributorsForTests, dropPendingDocs } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+const unsafe = `secret-prefix😀${String.fromCharCode(0, 31)}secret-suffix`;
+const polluted = `# Historical\n\nBefore ${String.fromCharCode(0, 31)} after.\n`;
+const allowed = '# Allowed\r\n\r\nPrintable \\u0000, tab\t, DEL\u007f, C1\u0080\u009f.\r\n';
+const routes = [
+ { path: '/api/agent-write', body: (docName: string) => ({ docName, content: unsafe }) },
+ {
+ path: '/api/agent-write-md',
+ body: (docName: string) => ({ docName, markdown: unsafe, position: 'replace' }),
+ },
+ {
+ path: '/api/agent-patch',
+ body: (docName: string) => ({ docName, find: 'target', replace: unsafe }),
+ },
+ {
+ path: '/api/agent-write-batch',
+ body: (docName: string) => ({ docs: [{ docName, markdown: unsafe, position: 'replace' }] }),
+ },
+];
+let root: string;
+let server: BootedServer;
+let sequence = 0;
+const ownedNames = new Set<string>(['historical', 'historical-append']);
+
+function nextName(): string {
+ const name = `admission-${++sequence}`;
+ ownedNames.add(name);
+ return name;
+}
+
+function post(path: string, body: object) {
+ return rawRequest(server.port, path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+async function write(docName: string, markdown: string, agentId: string) {
+ const response = await post('/api/agent-write-md', {
+ docName,
+ markdown,
+ agentId,
+ position: 'replace',
+ });
+ expect(response.status, response.body).toBe(200);
+}
+
+function expectRefusal(status: number, body: string) {
+ expect.soft(status).toBe(400);
+ expect.soft(body).toContain('U+0000');
+ expect.soft(body).toMatch(/UTF-?16/i);
+ expect.soft(body).toMatch(/offset\D*15\b/i);
+ expect.soft(body.length).toBeLessThan(2048);
+ expect.soft(body).not.toContain('secret-prefix');
+ expect.soft(body).not.toContain('secret-suffix');
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-control-admission-'));
+ writeFileSync(join(root, 'historical.md'), polluted);
+ writeFileSync(join(root, 'historical-append.md'), polluted);
+ server = await bootCompositionRig(root);
+ await server.ready;
+}, 60_000);
+
+afterAll(async () => {
+ await server?.destroy();
+ dropPendingDocs(ownedNames);
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(routes)('$path decoded control admission', ({ path, body }) => {
+ test('refuses before allocating a missing document or agent session', async () => {
+ const docName = nextName();
+ const agentId = `new-${docName}`;
+ const contributors = __formatContributorsForTests();
+ const documents = [...server.serverInstance.hocuspocus.documents.keys()].sort();
+ const response = await post(path, { ...body(docName), agentId });
+ expectRefusal(response.status, response.body);
+ expect.soft(existsSync(join(root, `${docName}.md`))).toBe(false);
+ expect
+ .soft(server.serverInstance.sessionManager.hasSession(docName, `agent-${agentId}`))
+ .toBe(false);
+ expect.soft([...server.serverInstance.hocuspocus.documents.keys()].sort()).toEqual(documents);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ });
+
+ test('refuses without changing existing source, disk, attribution, or undo', async () => {
+ const docName = nextName();
+ const agentId = `existing-${docName}`;
+ const original = '# Existing\n\nA target stays unchanged.\n';
+ await write(docName, original, agentId);
+ const session = await server.serverInstance.sessionManager.getSession(
+ docName,
+ `agent-${agentId}`,
+ );
+ session.um.stopCapturing();
+ expect(session.um.undoStack.length).toBeGreaterThan(0);
+ const document = Y.encodeStateAsUpdate(session.dc.document);
+ const undo = [...session.um.undoStack];
+ const contributors = __formatContributorsForTests();
+ const response = await post(path, { ...body(docName), agentId, summary: 'Rejected write' });
+ expectRefusal(response.status, response.body);
+ expect.soft(session.dc.document.getText('source').toString()).toBe(original);
+ expect.soft(Y.encodeStateAsUpdate(session.dc.document)).toEqual(document);
+ expect.soft(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(original);
+ expect.soft(session.um.undoStack).toEqual(undo);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ });
+});
+
+test('mixed batch refuses atomically before touching its clean entries', async () => {
+ const existing = nextName();
+ const cleanNew = nextName();
+ const badNew = nextName();
+ const agentId = `batch-${existing}`;
+ const original = '# Batch target\n';
+ await write(existing, original, agentId);
+ const contributors = __formatContributorsForTests();
+ const response = await post('/api/agent-write-batch', {
+ agentId,
+ docs: [
+ { docName: existing, markdown: '# Must not replace\n', position: 'replace' },
+ { docName: cleanNew, markdown: '# Must not create\n', position: 'replace' },
+ { docName: badNew, markdown: unsafe, position: 'replace' },
+ ],
+ });
+ expectRefusal(response.status, response.body);
+ expect.soft(readFileSync(join(root, `${existing}.md`), 'utf8')).toBe(original);
+ for (const docName of [cleanNew, badNew]) {
+ expect.soft(existsSync(join(root, `${docName}.md`))).toBe(false);
+ expect
+ .soft(server.serverInstance.sessionManager.hasSession(docName, `agent-${agentId}`))
+ .toBe(false);
+ }
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+});
+
+test('allowed markdown, patch replacements and batch entries remain byte-exact on disk', async () => {
+ const docName = nextName();
+ const batchName = nextName();
+ const agentId = `allowed-${docName}`;
+ await write(docName, allowed, agentId);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(allowed);
+ const replacement = 'Printable \\u001F\t\u007f\u0080\u009f';
+ const patched = await post('/api/agent-patch', {
+ docName,
+ agentId,
+ find: 'Printable \\u0000',
+ replace: replacement,
+ });
+ expect(patched.status, patched.body).toBe(200);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(
+ allowed.replace('Printable \\u0000', replacement),
+ );
+ const batch = await post('/api/agent-write-batch', {
+ agentId,
+ docs: [{ docName: batchName, markdown: allowed, position: 'replace' }],
+ });
+ expect(batch.status, batch.body).toBe(200);
+ expect(readFileSync(join(root, `${batchName}.md`), 'utf8')).toBe(allowed);
+});
+
+test('historical pollution loads, permits clean deltas and partial repair, and survives undo and rollback', async () => {
+ const docName = 'historical';
+ const agentId = 'historical-repair';
+ const session = await server.serverInstance.sessionManager.getSession(
+ docName,
+ `agent-${agentId}`,
+ );
+ expect(session.dc.document.getText('source').toString()).toBe(polluted);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(polluted);
+ const saved = await post('/api/save-version', { agentId, summary: 'Preserve historical bytes' });
+ expect(saved.status, saved.body).toBe(200);
+ const version = (JSON.parse(saved.body) as { checkpointRef: string }).checkpointRef
+ .split('/')
+ .at(-1);
+ expect(version).toMatch(/^[a-f0-9]{40}$/);
+ const cleanDelta = await post('/api/agent-patch', {
+ docName,
+ agentId,
+ find: 'Before',
+ replace: 'Edited before',
+ });
+ expect(cleanDelta.status, cleanDelta.body).toBe(200);
+ const edited = polluted.replace('Before', 'Edited before');
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(edited);
+ session.um.stopCapturing();
+ const repaired = await post('/api/agent-patch', {
+ docName,
+ agentId,
+ find: String.fromCharCode(0),
+ replace: '\\u0000',
+ });
+ expect(repaired.status, repaired.body).toBe(200);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(
+ edited.replace(String.fromCharCode(0), '\\u0000'),
+ );
+ const undone = await post('/api/agent-undo', {
+ docName,
+ agentId,
+ connectionId: `agent-${agentId}`,
+ scope: 'last',
+ });
+ expect(undone.status, undone.body).toBe(200);
+ expect(JSON.parse(undone.body)).toMatchObject({ undone: true });
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(edited);
+ const rollback = await post('/api/rollback', {
+ docName,
+ agentId,
+ commitSha: version,
+ summary: 'Restore historical bytes',
+ });
+ expect(rollback.status, rollback.body).toBe(200);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(polluted);
+ expect(session.dc.document.getText('source').toString()).toBe(polluted);
+});
+
+test('clean append and prepend do not revalidate polluted composed source', async () => {
+ const docName = 'historical-append';
+ const session = await server.serverInstance.sessionManager.getSession(
+ docName,
+ 'agent-clean-delta',
+ );
+ expect(session.dc.document.getText('source').toString()).toBe(polluted);
+ for (const [position, markdown] of [
+ ['append', '\nClean suffix.\n'],
+ ['prepend', '# Clean prefix\n\n'],
+ ] as const) {
+ const before = session.dc.document.getText('source').toString();
+ const response = await post('/api/agent-write-md', {
+ docName,
+ agentId: 'clean-delta',
+ markdown,
+ position,
+ });
+ expect(response.status, response.body).toBe(200);
+ const expected = position === 'append' ? before + markdown : markdown + before;
+ expect(session.dc.document.getText('source').toString()).toBe(expected);
+ expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(expected);
+ }
+});
+
+test('MCP clients receive a safe actionable write refusal without a created file', async () => {
+ const client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+ const docName = nextName();
+ try {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { document: { path: docName, content: unsafe, position: 'replace' } },
+ });
+ expect.soft(result.isError).toBe(true);
+ const content = JSON.stringify(result.content);
+ expect.soft(content).toContain('U+0000');
+ expect.soft(content).toMatch(/UTF-?16/i);
+ expect.soft(content).not.toContain('secret-prefix');
+ expect.soft(content).not.toContain('secret-suffix');
+ expect.soft(content.length).toBeLessThan(2048);
+ expect.soft(existsSync(join(root, `${docName}.md`))).toBe(false);
+ } finally {
+ await client.close();
+ }
+});
diff --git a/packages/server/src/api-artifact-body-control-admission.test.ts b/packages/server/src/api-artifact-body-control-admission.test.ts
new file mode 100644
index 000000000..d2ff7ce25
--- /dev/null
+++ b/packages/server/src/api-artifact-body-control-admission.test.ts
@@ -0,0 +1,319 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { instantiateDoc, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { rawRequest } from './composition-rig.test-helper.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+type ArtifactKind = 'template' | 'skill';
+const routes = [
+ { label: 'PUT /api/template', kind: 'template', method: 'PUT' },
+ { label: 'POST /api/template', kind: 'template', method: 'POST' },
+ { label: 'PUT /api/skill', kind: 'skill', method: 'PUT' },
+ { label: 'POST /api/skill', kind: 'skill', method: 'POST' },
+] as const;
+const allowed = 'Exact \t whitespace\r\nPrintable \\u0000 \\u001F 😀\u007f\u0080\u009f.\n';
+const historical = `Historical ${String.fromCharCode(0, 31)} bytes stay.\r\n`;
+const generatedPrefix = '---\ntitle: Generated\n---\nExpanded x😀';
+let root: string;
+let server: BootedServer;
+let client: Client;
+let sequence = 0;
+const nextName = () => `body-admission-${++sequence}`;
+const unsafe = (code: number) => `private-prefix😀${String.fromCharCode(code)}private-tail`;
+
+function artifactPath(kind: ArtifactKind, name: string): string {
+ return kind === 'template'
+ ? join(root, 'templates', '.ok', 'templates', `${name}.md`)
+ : join(root, '.agents', 'skills', name, 'SKILL.md');
+}
+
+function putBody(kind: ArtifactKind, name: string, body: string): object {
+ return kind === 'template'
+ ? { folder: 'templates', name, body, frontmatter: { title: 'Admission' } }
+ : { scope: 'project', name, body, frontmatter: { name, description: 'Admission' } };
+}
+
+function moveBody(kind: ArtifactKind, fromName: string, toName: string): object {
+ return kind === 'template'
+ ? { fromFolder: 'templates', fromName, toFolder: 'templates', toName }
+ : { scope: 'project', fromName, toName };
+}
+
+function editedMoveBody(kind: ArtifactKind, fromName: string, toName: string, body: string) {
+ return {
+ ...moveBody(kind, fromName, toName),
+ body,
+ ...(kind === 'template' ? { frontmatter: { title: 'Admission' } } : {}),
+ };
+}
+
+function request(kind: ArtifactKind, method: string, body: object) {
+ return rawRequest(server.port, `/api/${kind}`, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+async function createArtifact(kind: ArtifactKind, name: string, body = 'Existing target.\n') {
+ const response = await request(kind, 'PUT', putBody(kind, name, body));
+ expect(response.status, response.body).toBe(200);
+ const result = JSON.parse(response.body) as { path: string };
+ expect(join(root, result.path)).toBe(artifactPath(kind, name));
+ expect(existsSync(artifactPath(kind, name))).toBe(true);
+}
+
+function expectControlDetail(text: string, code: number) {
+ expect.soft(text).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text.length).toBeLessThan(2048);
+ expect.soft(text).not.toContain('private-prefix');
+ expect.soft(text).not.toContain('private-tail');
+ expect.soft(text).not.toContain(String.fromCharCode(code));
+}
+
+function expectActionableRefusal(result: { isError?: boolean; content?: unknown }, code: number) {
+ expect.soft(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expectControlDetail(text, code);
+ expect.soft(text).not.toMatch(/Error:\s*undefined/i);
+ expect.soft(text).toMatch(/\bTAB\b/i);
+ expect.soft(text).toMatch(/\bLF\b/i);
+ expect.soft(text).toMatch(/\bCR\b/i);
+ expect.soft(text).toMatch(/remove|replace/i);
+ expect.soft(text).toMatch(/escap|printable/i);
+ return text;
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-artifact-body-admission-'));
+ mkdirSync(join(root, 'templates'));
+ for (const kind of ['template', 'skill'] as const) {
+ for (const metadata of [false, true]) {
+ const name = `historical-${kind}${metadata ? '-metadata' : ''}`;
+ const path = artifactPath(kind, name);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ kind === 'template'
+ ? `---\ntemplate:\n title: Historical\n---\n${historical}`
+ : `---\nname: ${name}\ndescription: Historical\n---\n${historical}`,
+ );
+ }
+ }
+ const builtin = artifactPath('skill', 'open-knowledge');
+ mkdirSync(dirname(builtin), { recursive: true });
+ writeFileSync(
+ builtin,
+ '---\nname: open-knowledge\ndescription: Project instructions\n---\nProject.\n',
+ );
+ const template = artifactPath('template', 'historical-generated');
+ writeFileSync(
+ template,
+ `---\ntitle: Generator\n---\n${generatedPrefix}${String.fromCharCode(0)}private-tail\n`,
+ );
+ writeFileSync(
+ artifactPath('template', 'legacy-edit'),
+ '---\ntitle: Legacy\n---\nExisting target.\n',
+ );
+ server = await bootArtifactAdmissionRig(root);
+ await server.ready;
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(routes)('$label incoming body over real HTTP', ({ kind, method }) => {
+ test.each([0, 31])(
+ 'rejects decoded control %i before existing-body or destination mutation',
+ async (code) => {
+ const name = nextName();
+ const destination = nextName();
+ await createArtifact(kind, name);
+ const path = artifactPath(kind, name);
+ const original = readFileSync(path);
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const payload =
+ method === 'PUT'
+ ? putBody(kind, name, unsafe(code))
+ : editedMoveBody(kind, name, destination, unsafe(code));
+ const response = await request(kind, method, {
+ ...payload,
+ agentId: nextName(),
+ summary: 'Must not land',
+ });
+ expect.soft(response.status, response.body).toBe(400);
+ expect.soft(response.headers['content-type']).toContain('application/problem+json');
+ expectControlDetail(response.body, code);
+ expect.soft(existsSync(path)).toBe(true);
+ if (existsSync(path)) expect.soft(readFileSync(path)).toEqual(original);
+ expect.soft(existsSync(artifactPath(kind, destination))).toBe(false);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ },
+ );
+
+ test('preserves admitted whitespace, printable escapes, DEL and C1 bytes', async () => {
+ const name = nextName();
+ const destination = nextName();
+ await createArtifact(kind, name);
+ const payload =
+ method === 'PUT'
+ ? putBody(kind, name, allowed)
+ : editedMoveBody(kind, name, destination, allowed);
+ const response = await request(kind, method, payload);
+ expect(response.status, response.body).toBe(200);
+ const finalName = method === 'PUT' ? name : destination;
+ const raw = readFileSync(artifactPath(kind, finalName), 'utf8');
+ expect(kind === 'template' ? instantiateDoc(raw) : stripFrontmatter(raw).body).toBe(allowed);
+ const query = kind === 'template' ? '?folder=templates&name=' : '?scope=project&name=';
+ const read = await rawRequest(server.port, `/api/${kind}${query}${finalName}`);
+ expect(read.status, read.body).toBe(200);
+ const data = JSON.parse(read.body) as { template?: { body: string }; skill?: { body: string } };
+ expect(data[kind]?.body).toBe(allowed);
+ });
+});
+
+describe.each(['template', 'skill'] as const)(
+ '%s body admission through registered MCP tools',
+ (kind) => {
+ test.each([0, 31])('refuses decoded control %i before creating an artifact', async (code) => {
+ const name = nextName();
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const response = await request(kind, 'PUT', {
+ ...putBody(kind, name, unsafe(code)),
+ agentId: name,
+ });
+ expect.soft(response.status, response.body).toBe(400);
+ expectControlDetail(response.body, code);
+ expect.soft(existsSync(artifactPath(kind, name))).toBe(false);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ });
+
+ test.each([false, true])(
+ 'body-omitted moves preserve historical raw body bytes (metadata=%s)',
+ async (metadata) => {
+ const name = `historical-${kind}${metadata ? '-metadata' : ''}`;
+ const path = artifactPath(kind, name);
+ const original = readFileSync(path, 'utf8');
+ expect(original).toContain(historical);
+ const destination = nextName();
+ const response = await request(kind, 'POST', {
+ ...moveBody(kind, name, destination),
+ ...(metadata
+ ? {
+ frontmatter:
+ kind === 'template'
+ ? { title: 'Updated' }
+ : { name: destination, description: 'Updated' },
+ }
+ : {}),
+ });
+ expect(response.status, response.body).toBe(200);
+ expect(existsSync(path)).toBe(false);
+ const raw = readFileSync(artifactPath(kind, destination), 'utf8');
+ expect(kind === 'template' ? instantiateDoc(raw) : stripFrontmatter(raw).body).toBe(
+ historical,
+ );
+ if (kind === 'template' && !metadata) expect(raw).toBe(original);
+ },
+ );
+
+ test('write returns the actionable control detail without creating an artifact', async () => {
+ const name = nextName();
+ const target =
+ kind === 'template'
+ ? {
+ template: {
+ path: `templates/${name}`,
+ content: unsafe(0),
+ frontmatter: { title: 'Admission' },
+ },
+ }
+ : { skill: { name, description: 'Admission', body: unsafe(0) } };
+ const result = await client.callTool({ name: 'write', arguments: target });
+ const text = expectActionableRefusal(result, 0);
+ expect.soft(text).toMatch(/\bbody\b|\bcontent\b/i);
+ expect.soft(text).toMatch(new RegExp(`offset\\D*${'private-prefix😀'.length}\\b`, 'i'));
+ expect.soft(existsSync(artifactPath(kind, name))).toBe(false);
+ });
+
+ test('edit returns the actionable control detail without changing the existing body', async () => {
+ const name = kind === 'template' ? 'legacy-edit' : nextName();
+ if (kind === 'skill') await createArtifact(kind, name);
+ const original = readFileSync(artifactPath(kind, name));
+ const target =
+ kind === 'template'
+ ? { template: { path: `templates/${name}`, find: 'target', replace: unsafe(31) } }
+ : { skill: { name, find: 'target', replace: unsafe(31) } };
+ const result = await client.callTool({ name: 'edit', arguments: target });
+ const text = expectActionableRefusal(result, 31);
+ const bodyCoordinate = /\bbody\b/i.test(text) && /offset\D*25\b/i.test(text);
+ const replacementCoordinate = /replace/i.test(text) && /offset\D*16\b/i.test(text);
+ expect.soft(bodyCoordinate || replacementCoordinate, text).toBe(true);
+ expect.soft(readFileSync(artifactPath(kind, name))).toEqual(original);
+ });
+ },
+);
+
+test('MCP frontmatter-composed write identifies the offset basis and remedy', async () => {
+ const name = nextName();
+ const content = `x😀${String.fromCharCode(0)}private-tail`;
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { document: { path: name, content, frontmatter: { title: 'Coordinates' } } },
+ });
+ const text = expectActionableRefusal(result, 0);
+ const sourceCoordinate =
+ /document\.content|`content`|\bcontent\s*:|\bcontent (?:argument|parameter)/i.test(text) &&
+ /offset\D*3\b/i.test(text);
+ const composedOffset = '---\ntitle: Coordinates\n---\nx😀'.length;
+ const composedCoordinate =
+ /compos|generat/i.test(text) &&
+ /frontmatter/i.test(text) &&
+ new RegExp(`offset\\D*${composedOffset}\\b`, 'i').test(text);
+ expect.soft(sourceCoordinate || composedCoordinate, text).toBe(true);
+ expect.soft(existsSync(join(root, `${name}.md`))).toBe(false);
+});
+
+test('non-Markdown skill scripts and assets retain opaque control bytes', async () => {
+ const name = nextName();
+ await createArtifact('skill', name);
+ const content = `Opaque ${String.fromCharCode(0, 31)} bytes.\n`;
+ for (const path of ['scripts/fixture.py', 'assets/data.bin']) {
+ const response = await rawRequest(server.port, '/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name, path, content }),
+ });
+ expect(response.status, response.body).toBe(200);
+ expect(readFileSync(join(dirname(artifactPath('skill', name)), path), 'utf8')).toBe(content);
+ }
+});
+
+test('MCP template-expanded write identifies generated Markdown coordinates and remedy', async () => {
+ const name = nextName();
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { document: { path: `templates/${name}`, template: 'historical-generated' } },
+ });
+ const text = expectActionableRefusal(result, 0);
+ expect.soft(text).toMatch(/compos|generat|expan|resolved template|template body/i);
+ expect.soft(text).toMatch(/template/i);
+ expect.soft(text).toMatch(new RegExp(`offset\\D*${generatedPrefix.length}\\b`, 'i'));
+ expect.soft(existsSync(join(root, 'templates', `${name}.md`))).toBe(false);
+});
diff --git a/packages/server/src/api-artifact-flush-settlement.test.ts b/packages/server/src/api-artifact-flush-settlement.test.ts
new file mode 100644
index 000000000..b517740a8
--- /dev/null
+++ b/packages/server/src/api-artifact-flush-settlement.test.ts
@@ -0,0 +1,168 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setImmediate } from 'node:timers/promises';
+import { expect, test, vi } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import * as persistence from './persistence.ts';
+import * as shadowRepo from './shadow-repo.ts';
+
+test('test flush waits for accepted artifact attribution before acknowledging settlement', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'ok-artifact-flush-settlement-'));
+ mkdirSync(join(root, 'templates'));
+ let server: BootedServer | undefined;
+ let gated = false;
+ let released = false;
+ let release!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const started = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const gitFlushes: boolean[] = [];
+ const create = persistence.createPersistenceExtension;
+ vi.spyOn(persistence, 'createPersistenceExtension').mockImplementation((...args) => {
+ const result = create(...args);
+ const flush = result.flushContributors;
+ const flushGit = result.flushPendingGitCommit;
+ result.flushContributors = async () => {
+ if (gated) {
+ entered();
+ await gate;
+ }
+ await flush();
+ };
+ result.flushPendingGitCommit = async () => {
+ if (gated) gitFlushes.push(released);
+ await flushGit();
+ };
+ return result;
+ });
+ try {
+ server = await bootCompositionRig(root, { enableTestRoutes: true });
+ await server.ready;
+ await server.generatedIndexSweepReady;
+ gated = true;
+ const write = await rawRequest(server.port, '/api/template', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ folder: 'templates',
+ name: 'example',
+ body: 'Safe.\n',
+ frontmatter: { title: 'Example' },
+ }),
+ });
+ expect(write.status, write.body).toBe(200);
+ await started;
+ expect(__formatContributorsForTests()).toContain('templates/.ok/templates/example');
+ let received!: () => void;
+ const requestReceived = new Promise<void>((resolve) => {
+ received = resolve;
+ });
+ server.httpServer.prependListener('request', (req) => {
+ if (req.url === '/api/test-flush-git') received();
+ });
+ const flushing = rawRequest(server.port, '/api/test-flush-git', { method: 'POST' });
+ await requestReceived;
+ await setImmediate();
+ const beforeRelease = [...gitFlushes];
+ released = true;
+ release();
+ const response = await flushing;
+ expect(beforeRelease).toEqual([]);
+ expect(response.status, response.body).toBe(200);
+ expect(gitFlushes).toEqual([true]);
+ expect(__formatContributorsForTests()).toBe('');
+ } finally {
+ release();
+ await server?.destroy();
+ vi.restoreAllMocks();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('shared settlement joins the separate skill-file attribution flush', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'ok-skill-file-flush-settlement-'));
+ const directory = join(root, '.agents', 'skills', 'example');
+ mkdirSync(directory, { recursive: true });
+ writeFileSync(
+ join(directory, 'SKILL.md'),
+ '---\nname: example\ndescription: Example\n---\nGuidance.\n',
+ );
+ let server: BootedServer | undefined;
+ let tracked = false;
+ let release!: () => void;
+ let commitEntered!: () => void;
+ let joinEntered!: () => void;
+ const commitGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const commitStarted = new Promise<void>((resolve) => {
+ commitEntered = resolve;
+ });
+ const joinStarted = new Promise<void>((resolve) => {
+ joinEntered = resolve;
+ });
+ let joinCompleted = false;
+ const commit = shadowRepo.commitWipFromTree;
+ vi.spyOn(shadowRepo, 'commitWipFromTree').mockImplementation(async (...args) => {
+ if (tracked) {
+ commitEntered();
+ await commitGate;
+ }
+ return commit(...args);
+ });
+ const create = persistence.createPersistenceExtension;
+ vi.spyOn(persistence, 'createPersistenceExtension').mockImplementation((...args) => {
+ const result = create(...args);
+ const flushGit = result.flushPendingGitCommit;
+ result.flushPendingGitCommit = async () => {
+ const work = flushGit();
+ if (tracked) joinEntered();
+ await work;
+ if (tracked) joinCompleted = true;
+ };
+ return result;
+ });
+ try {
+ server = await bootArtifactAdmissionRig(root);
+ await settleArtifactContributors(server);
+ tracked = true;
+ const response = await rawRequest(server.port, '/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'example',
+ scope: 'project',
+ path: 'references/example.md',
+ content: 'Safe.\n',
+ agentId: 'file-writer',
+ }),
+ });
+ expect(response.status, response.body).toBe(200);
+ await commitStarted;
+ const settling = settleArtifactContributors(server);
+ await joinStarted;
+ await setImmediate();
+ const completedBeforeRelease = joinCompleted;
+ release();
+ await settling;
+ expect(completedBeforeRelease).toBe(false);
+ expect(joinCompleted).toBe(true);
+ expect(__formatContributorsForTests()).toBe('');
+ } finally {
+ release();
+ await server?.destroy();
+ vi.restoreAllMocks();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/server/src/api-content-admission-cause.test.ts b/packages/server/src/api-content-admission-cause.test.ts
new file mode 100644
index 000000000..566ff0694
--- /dev/null
+++ b/packages/server/src/api-content-admission-cause.test.ts
@@ -0,0 +1,152 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+let root: string;
+let server: BootedServer;
+let client: Client;
+const templatePath = () => join(root, 'templates', '.ok', 'templates', 'existing.md');
+const skillPath = () => join(root, '.agents', 'skills', 'existing', 'SKILL.md');
+
+function skillFile(path: string, content: string) {
+ return rawRequest(server.port, '/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'existing', path, content }),
+ });
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-admission-cause-'));
+ for (const [path, content] of [
+ [templatePath(), '---\ntitle: Existing\n---\nExisting target.\n'],
+ [skillPath(), '---\nname: existing\ndescription: Existing\n---\nExisting target.\n'],
+ [
+ join(root, '.agents', 'skills', 'open-knowledge', 'SKILL.md'),
+ '---\nname: open-knowledge\ndescription: Project\n---\nProject.\n',
+ ],
+ [
+ join(dirname(skillPath()), 'references', 'existing.md'),
+ '---\ntitle: Existing\n---\nExisting target.\n',
+ ],
+ ]) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+ }
+ server = await bootCompositionRig(root);
+ await server.ready;
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+test.each(['template', 'skill', 'file'] as const)(
+ 'real %s edit admission leaves supplied replace open as the control source',
+ async (kind) => {
+ const path =
+ kind === 'template'
+ ? templatePath()
+ : kind === 'skill'
+ ? skillPath()
+ : join(dirname(skillPath()), 'references', 'existing.md');
+ const original = readFileSync(path);
+ const edit = { find: 'target', replace: 'x😀\u0000private-tail' };
+ const args =
+ kind === 'template'
+ ? { template: { path: 'templates/existing', ...edit } }
+ : {
+ skill: {
+ name: 'existing',
+ ...(kind === 'file' ? { file: 'references/existing.md' } : {}),
+ ...edit,
+ },
+ };
+ const result = await client.callTool({ name: 'edit', arguments: args });
+ expect(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain('U+0000');
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text).toMatch(/full[^.]*resubmit|resubmit[^.]*full/i);
+ expect
+ .soft(text)
+ .toMatch(
+ /supplied[^.]*replace|replace[^.]*supplied|replacement[^.]*submitted|submitted[^.]*replacement/i,
+ );
+ expect.soft(text).not.toContain('private-tail');
+ expect.soft(readFileSync(path)).toEqual(original);
+ },
+);
+
+test('real hidden .md bundle file is writable and its refusal has the same whole-content advice', async () => {
+ const path = 'references/.md';
+ const allowed = 'Exact\tline\r\nPrintable \\u0000 😀\u007f\u0080\u009f.\n';
+ const seeded = await skillFile(path, allowed);
+ expect(seeded.status, seeded.body).toBe(200);
+ const abs = join(dirname(skillPath()), path);
+ expect(readFileSync(abs, 'utf8')).toBe(allowed);
+ const raw = await skillFile(path, 'x😀\u0000private-tail');
+ expect(raw.status, raw.body).toBe(400);
+ expect(raw.body).toContain('U+0000');
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name: 'existing', files: [{ path, content: 'x😀\u0000private-tail' }] } },
+ });
+ expect(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain('U+0000');
+ expect.soft(text).toMatch(/offset[^.]*whole submitted file content[^.]*frontmatter/i);
+ expect.soft(readFileSync(abs, 'utf8')).toBe(allowed);
+});
+
+test('real ordinary Markdown refusal keeps actionable advice for a submitted full file', async () => {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: {
+ skill: {
+ name: 'existing',
+ files: [{ path: 'references/ordinary.md', content: 'x😀\u0000private-tail' }],
+ },
+ },
+ });
+ expect(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect(text).toContain('U+0000');
+ expect(text).toMatch(/offset[^.]*whole submitted file content[^.]*frontmatter/i);
+ expect(text).toMatch(/TAB[^.]*LF[^.]*CR/i);
+ expect(text).toMatch(/Remove[^.]*replace[^.]*printable escape/i);
+});
+
+test('real invalid skill description returns only its actual problem title and detail', async () => {
+ const description = 'x'.repeat(2048);
+ const response = await rawRequest(server.port, '/api/skill', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'existing',
+ body: 'Existing target.\n',
+ frontmatter: { name: 'existing', description },
+ }),
+ });
+ expect(response.status, response.body).toBe(400);
+ const problem = JSON.parse(response.body) as { title: string; detail: string };
+ expect(problem.detail).toBe('DESCRIPTION_TOO_LONG');
+ const original = readFileSync(skillPath());
+ const result = await client.callTool({
+ name: 'edit',
+ arguments: { skill: { name: 'existing', description } },
+ });
+ expect(result.isError).toBe(true);
+ expect
+ .soft(result.content)
+ .toEqual([{ type: 'text', text: `Error: ${problem.title} (${problem.detail})` }]);
+ expect.soft(readFileSync(skillPath())).toEqual(original);
+});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 321636edf..c9f6ef573 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -5425,7 +5425,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
contentFilter,
bumpSkillsCatalogGen,
signalChannel,
- flushGitCommit,
+ flushGitCommit: async () => {
+ await okArtifactFlushChain;
+ await flushGitCommit?.();
+ },
rescanFiles,
});
const nativeGroups = [
diff --git a/packages/server/src/api-mcp-admission-error-basis.test.ts b/packages/server/src/api-mcp-admission-error-basis.test.ts
new file mode 100644
index 000000000..4e549e23f
--- /dev/null
+++ b/packages/server/src/api-mcp-admission-error-basis.test.ts
@@ -0,0 +1,224 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { instantiateDoc, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+const historical = 'private-history x😀\u0000 middle \u001f tail.\n';
+const clean = historical.replace('\u0000', '\\u0000').replace('\u001f', '\\u001F');
+let root: string;
+let server: BootedServer;
+let client: Client;
+
+function artifactPath(kind: 'template' | 'skill', name: string) {
+ return kind === 'template'
+ ? join(root, 'templates', '.ok', 'templates', `${name}.md`)
+ : join(root, '.agents', 'skills', name, 'SKILL.md');
+}
+
+function textOf(result: Awaited<ReturnType<Client['callTool']>>) {
+ return JSON.stringify(result.content);
+}
+
+function expectAdmission(text: string, code: number, offset: number) {
+ expect.soft(text).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text).toMatch(new RegExp(`offset\\D*${offset}\\b`, 'i'));
+ expect.soft(text).not.toContain('private-history');
+ expect.soft(text).not.toContain('private-tail');
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-mcp-basis-'));
+ for (const kind of ['template', 'skill'] as const) {
+ for (const operation of ['metadata', 'partial']) {
+ const name = `basis-${kind}-${operation}`;
+ const path = artifactPath(kind, name);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ kind === 'template'
+ ? `---\ntitle: Historical\n---\n${historical}`
+ : `---\nname: ${name}\ndescription: Historical\n---\n${historical}`,
+ );
+ }
+ }
+ const builtin = artifactPath('skill', 'open-knowledge');
+ mkdirSync(dirname(builtin), { recursive: true });
+ writeFileSync(builtin, '---\nname: open-knowledge\ndescription: Project\n---\nProject.\n');
+ const bundle = artifactPath('skill', 'basis-skill-bundle');
+ mkdirSync(join(dirname(bundle), 'references'), { recursive: true });
+ writeFileSync(bundle, '---\nname: basis-skill-bundle\ndescription: Project\n---\nProject.\n');
+ writeFileSync(
+ join(dirname(bundle), 'references', 'historical.md'),
+ '---\ntitle: Historical\n---\nprivate-history x😀\u0001 middle \u001f tail.\n',
+ );
+ server = await bootArtifactAdmissionRig(root);
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(['template', 'skill'] as const)('%s real admission error basis', (kind) => {
+ test('full writes name the submitted field without claiming a replace argument', async () => {
+ const name = `basis-new-${kind}`;
+ const content = 'x😀\u0000private-tail';
+ const target =
+ kind === 'template'
+ ? { template: { path: `templates/${name}`, content, frontmatter: { title: 'Basis' } } }
+ : { skill: { name, description: 'Basis', body: content } };
+ const result = await client.callTool({ name: 'write', arguments: target });
+ expect(result.isError).toBe(true);
+ const text = textOf(result);
+ expectAdmission(text, 0, 3);
+ expect
+ .soft(text)
+ .toMatch(
+ kind === 'template'
+ ? /offset[^.]*full submitted template\.content/i
+ : /offset[^.]*full submitted skill body/i,
+ );
+ expect.soft(text).not.toMatch(/not just replace/i);
+ });
+
+ test.each(['metadata', 'partial'] as const)(
+ '%s edits identify the resubmitted stored body and cleaned full-write repair',
+ async (operation) => {
+ const name = `basis-${kind}-${operation}`;
+ const path = artifactPath(kind, name);
+ const original = readFileSync(path);
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const edit =
+ operation === 'partial'
+ ? { find: '\u0000', replace: '\\u0000' }
+ : kind === 'template'
+ ? { frontmatter: { description: 'Updated' } }
+ : { description: 'Updated' };
+ const target =
+ kind === 'template'
+ ? { template: { path: `templates/${name}`, ...edit } }
+ : { skill: { name, ...edit } };
+ const result = await client.callTool({ name: 'edit', arguments: target });
+ expect(result.isError).toBe(true);
+ const text = textOf(result);
+ const resubmitted =
+ operation === 'partial' ? historical.replace('\u0000', '\\u0000') : historical;
+ const code = operation === 'partial' ? 31 : 0;
+ expectAdmission(text, code, resubmitted.indexOf(String.fromCharCode(code)));
+ expect
+ .soft(text)
+ .toMatch(/full[^.]*stored[^.]*body[^.]*resubmit|resubmit[^.]*full[^.]*stored[^.]*body/i);
+ expect.soft(text).toMatch(/clean[^.]*full[^.]*replac/i);
+ expect.soft(text).toMatch(/write\s*\(/i);
+ expect.soft(text).toContain(kind);
+ if (operation === 'metadata') expect.soft(text).not.toMatch(/not just replace/i);
+ expect.soft(readFileSync(path)).toEqual(original);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ const cleanedTarget =
+ kind === 'template'
+ ? {
+ template: {
+ path: `templates/${name}`,
+ content: clean,
+ frontmatter: { title: 'Clean' },
+ },
+ }
+ : { skill: { name, description: 'Clean', body: clean } };
+ const repaired = await client.callTool({ name: 'write', arguments: cleanedTarget });
+ expect.soft(repaired.isError, textOf(repaired)).not.toBe(true);
+ const raw = readFileSync(path, 'utf8');
+ expect
+ .soft(kind === 'template' ? instantiateDoc(raw) : stripFrontmatter(raw).body)
+ .toBe(clean);
+ },
+ );
+});
+
+test('real Markdown bundle admission names the whole submitted content', async () => {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: {
+ skill: {
+ name: 'basis-skill-metadata',
+ files: [
+ { path: 'references/basis.md', content: '---\ntitle: Basis\n---\nx😀\u0000private-tail' },
+ ],
+ },
+ },
+ });
+ expect(result.isError).toBe(true);
+ const text = textOf(result);
+ expectAdmission(text, 0, '---\ntitle: Basis\n---\nx😀'.length);
+ expect.soft(text).toMatch(/offset[^.]*whole submitted file content[^.]*frontmatter/i);
+});
+
+test.each(['references/absent.md', 'scripts/absent.sh', 'assets/absent.svg'])(
+ 'real missing-skill failure has no admission offset advice for %s',
+ async (path) => {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name: 'basis-does-not-exist', files: [{ path, content: 'Safe.' }] } },
+ });
+ expect(result.isError).toBe(true);
+ const text = textOf(result);
+ expect.soft(text).toMatch(/not found/i);
+ expect.soft(text).not.toMatch(/(?:body|content) offset|full submitted|whole submitted/i);
+ },
+);
+
+test('real Markdown bundle edit identifies the resubmitted stored file and clean full-write repair', async () => {
+ const path = join(
+ dirname(artifactPath('skill', 'basis-skill-bundle')),
+ 'references',
+ 'historical.md',
+ );
+ const original = readFileSync(path, 'utf8');
+ const result = await client.callTool({
+ name: 'edit',
+ arguments: {
+ skill: {
+ name: 'basis-skill-bundle',
+ file: 'references/historical.md',
+ find: '\u0001',
+ replace: '\\u0001',
+ },
+ },
+ });
+ expect(result.isError).toBe(true);
+ const text = textOf(result);
+ const resubmitted = original.replace('\u0001', '\\u0001');
+ expectAdmission(text, 31, resubmitted.indexOf('\u001f'));
+ expect
+ .soft(text)
+ .toMatch(
+ /full[^.]*stored[^.]*(?:file|content)[^.]*resubmit|resubmit[^.]*full[^.]*stored[^.]*(?:file|content)/i,
+ );
+ expect.soft(text).toMatch(/clean[^.]*full[^.]*replac/i);
+ expect.soft(text).toMatch(/write\s*\(/i);
+ expect.soft(readFileSync(path, 'utf8')).toBe(original);
+ const cleaned = resubmitted.replace('\u001f', '\\u001F');
+ const repaired = await client.callTool({
+ name: 'write',
+ arguments: {
+ skill: {
+ name: 'basis-skill-bundle',
+ files: [{ path: 'references/historical.md', content: cleaned }],
+ },
+ },
+ });
+ expect.soft(repaired.isError, textOf(repaired)).not.toBe(true);
+ expect.soft(readFileSync(path, 'utf8')).toBe(cleaned);
+});
diff --git a/packages/server/src/api-mcp-full-put-qualification.test.ts b/packages/server/src/api-mcp-full-put-qualification.test.ts
new file mode 100644
index 000000000..945d48d98
--- /dev/null
+++ b/packages/server/src/api-mcp-full-put-qualification.test.ts
@@ -0,0 +1,172 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { instantiateDoc, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+type Kind = 'template' | 'skill';
+const historical = `private-history x😀${String.fromCharCode(0)} middle ${String.fromCharCode(31)} end.\n`;
+const fullyClean = historical.replace('\u0000', '\\u0000').replace('\u001f', '\\u001F');
+let root: string;
+let server: BootedServer;
+let client: Client;
+
+function nameFor(kind: Kind, operation: string): string {
+ return `qualification-${operation}-${kind}`;
+}
+
+function pathFor(kind: Kind, name: string): string {
+ return kind === 'template'
+ ? join(root, 'templates', '.ok', 'templates', `${name}.md`)
+ : join(root, '.agents', 'skills', name, 'SKILL.md');
+}
+
+function expectFullFieldRefusal(
+ result: { isError?: boolean; content?: unknown },
+ code: number,
+ offset: number,
+) {
+ expect.soft(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text).toMatch(new RegExp(`offset\\D*${offset}\\b`, 'i'));
+ expect.soft(text).toMatch(/body|markdown|content|compos|generat/i);
+ expect.soft(text).toMatch(/\bTAB\b/i);
+ expect.soft(text).toMatch(/\bLF\b/i);
+ expect.soft(text).toMatch(/\bCR\b/i);
+ expect.soft(text).toMatch(/remove|replace/i);
+ expect.soft(text).toMatch(/escap|printable/i);
+ expect.soft(text).not.toContain('private-history');
+ expect.soft(text).not.toContain('private-batch');
+ expect.soft(text).not.toContain('private-tail');
+ expect.soft(text).not.toMatch(/Error:\s*undefined/i);
+ expect.soft(text.length).toBeLessThan(2048);
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-full-put-qualification-'));
+ for (const kind of ['template', 'skill'] as const) {
+ for (const operation of ['metadata', 'repair', 'clean']) {
+ const name = nameFor(kind, operation);
+ const path = pathFor(kind, name);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ kind === 'template'
+ ? `---\ntitle: Legacy\n---\n${historical}`
+ : `---\nname: ${name}\ndescription: Historical\n---\n${historical}`,
+ );
+ }
+ }
+ const builtin = pathFor('skill', 'open-knowledge');
+ mkdirSync(dirname(builtin), { recursive: true });
+ writeFileSync(builtin, '---\nname: open-knowledge\ndescription: Project\n---\nProject.\n');
+ server = await bootArtifactAdmissionRig(root);
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(['template', 'skill'] as const)(
+ '%s new full-PUT input-domain qualification',
+ (kind) => {
+ test('metadata-only and partial-repair MCP edits refuse resubmitted historical controls without mutation', async () => {
+ for (const operation of ['metadata', 'repair']) {
+ const name = nameFor(kind, operation);
+ const path = pathFor(kind, name);
+ const original = readFileSync(path);
+ expect(original.toString('utf8')).toContain(historical);
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const edit =
+ operation === 'metadata'
+ ? kind === 'template'
+ ? { frontmatter: { description: 'Updated' } }
+ : { description: 'Updated' }
+ : { find: '\u0000', replace: '\\u0000' };
+ const target =
+ kind === 'template'
+ ? { template: { path: `templates/${name}`, ...edit } }
+ : { skill: { name, ...edit } };
+ const result = await client.callTool({ name: 'edit', arguments: target });
+ const fullBody =
+ operation === 'metadata' ? historical : historical.replace('\u0000', '\\u0000');
+ const code = operation === 'metadata' ? 0 : 31;
+ expectFullFieldRefusal(result, code, fullBody.indexOf(String.fromCharCode(code)));
+ expect.soft(readFileSync(path)).toEqual(original);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ }
+ });
+
+ test('fully clean full replacement of historical content succeeds byte-exact', async () => {
+ const name = nameFor(kind, 'clean');
+ const path = pathFor(kind, name);
+ expect(readFileSync(path, 'utf8')).toContain(historical);
+ const cleanTarget =
+ kind === 'template'
+ ? {
+ template: {
+ path: `templates/${name}`,
+ content: fullyClean,
+ frontmatter: { title: 'Clean' },
+ },
+ }
+ : { skill: { name, description: 'Clean', body: fullyClean } };
+ const clean = await client.callTool({ name: 'write', arguments: cleanTarget });
+ expect(clean.isError, JSON.stringify(clean.content)).not.toBe(true);
+ const raw = readFileSync(path, 'utf8');
+ expect(kind === 'template' ? instantiateDoc(raw) : stripFrontmatter(raw).body).toBe(
+ fullyClean,
+ );
+ });
+ },
+);
+
+test('mixed MCP documents batch persists safe siblings before and after refusal without atomic rollback', async () => {
+ const first = 'qualification-batch-safe-first';
+ const unsafe = 'qualification-batch-unsafe';
+ const last = 'qualification-batch-safe-last';
+ const content = `private-batch x😀${String.fromCharCode(0)} private-tail`;
+ const result = await client.callTool({
+ name: 'write',
+ arguments: {
+ documents: [
+ { path: first, content: '# First safe\n', position: 'replace' },
+ { path: unsafe, content, position: 'replace' },
+ { path: last, content: '# Last safe\n', position: 'replace' },
+ ],
+ },
+ });
+ expect(result.isError).toBe(true);
+ const structured = result.structuredContent as
+ | { documents?: Array<{ docName: string; ok: boolean; error?: string }> }
+ | undefined;
+ expect(structured?.documents?.map(({ docName, ok }) => ({ docName, ok }))).toEqual([
+ { docName: first, ok: true },
+ { docName: unsafe, ok: false },
+ { docName: last, ok: true },
+ ]);
+ expect(readFileSync(join(root, `${first}.md`), 'utf8')).toBe('# First safe\n');
+ expect(readFileSync(join(root, `${last}.md`), 'utf8')).toBe('# Last safe\n');
+ expect(existsSync(join(root, `${unsafe}.md`))).toBe(false);
+ const refusal = structured?.documents?.find((doc) => doc.docName === unsafe)?.error;
+ expect(refusal).toBeDefined();
+ expectFullFieldRefusal(
+ { isError: result.isError, content: refusal },
+ 0,
+ content.indexOf('\u0000'),
+ );
+});
diff --git a/packages/server/src/api-skill-file-control-admission.test.ts b/packages/server/src/api-skill-file-control-admission.test.ts
new file mode 100644
index 000000000..c9be12bee
--- /dev/null
+++ b/packages/server/src/api-skill-file-control-admission.test.ts
@@ -0,0 +1,161 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { rawRequest } from './composition-rig.test-helper.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+const name = 'reference-admission';
+const original = '---\ntitle: Existing\n---\nExisting target.\n';
+const allowed = 'Exact \t whitespace\r\nPrintable \\u0000 \\u001F 😀\u007f\u0080\u009f.\n';
+const unsafe = (code: number) => `x😀${String.fromCharCode(code)}private-tail`;
+let root: string;
+let server: BootedServer;
+let client: Client;
+let sequence = 0;
+const nextPath = (extension: string) => `references/admission-${++sequence}${extension}`;
+const diskPath = (path: string) => join(root, '.agents', 'skills', name, path);
+
+function put(path: string, content: string, agentId = 'reference-writer') {
+ return rawRequest(server.port, '/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name, path, content, agentId }),
+ });
+}
+
+async function seed(path: string, content = original) {
+ const response = await put(path, content);
+ expect(response.status, response.body).toBe(200);
+ expect(readFileSync(diskPath(path), 'utf8')).toBe(content);
+}
+
+function expectDetail(text: string, code: number, offset: number) {
+ expect.soft(text).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text).toMatch(new RegExp(`offset\\D*${offset}\\b`, 'i'));
+ expect.soft(text.length).toBeLessThan(2048);
+ expect.soft(text).not.toContain('private-tail');
+}
+
+function toolError(result: { isError?: boolean; content?: unknown }, code: number) {
+ expect.soft(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain(`U+${code.toString(16).toUpperCase().padStart(4, '0')}`);
+ expect.soft(text).toMatch(/UTF-?16/i);
+ expect.soft(text).toMatch(/\bTAB\b/i);
+ expect.soft(text).toMatch(/\bLF\b/i);
+ expect.soft(text).toMatch(/\bCR\b/i);
+ expect.soft(text).toMatch(/remove|replace/i);
+ expect.soft(text).toMatch(/escap|printable/i);
+ expect.soft(text).not.toMatch(/Error:\s*undefined/i);
+ expect.soft(text).not.toContain('private-tail');
+ expect.soft(text.length).toBeLessThan(2048);
+ return text;
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-reference-admission-'));
+ for (const skill of [name, 'open-knowledge']) {
+ const directory = join(root, '.agents', 'skills', skill);
+ mkdirSync(directory, { recursive: true });
+ writeFileSync(
+ join(directory, 'SKILL.md'),
+ `---\nname: ${skill}\ndescription: Admission\n---\nGuidance.\n`,
+ );
+ }
+ server = await bootArtifactAdmissionRig(root);
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(['.md', '.mdx'])(
+ '%s reference content over real HTTP and registered MCP',
+ (extension) => {
+ test.each([0, 31])(
+ 'refuses decoded control %i before creating or overwriting a reference',
+ async (code) => {
+ for (const existing of [false, true]) {
+ const path = nextPath(extension);
+ if (existing) await seed(path);
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const response = await put(path, unsafe(code), `rejected-reference-${++sequence}`);
+ expect.soft(response.status, response.body).toBe(400);
+ expect.soft(response.headers['content-type']).toContain('application/problem+json');
+ expectDetail(response.body, code, 3);
+ expect.soft(existsSync(diskPath(path))).toBe(existing);
+ if (existing) expect.soft(readFileSync(diskPath(path), 'utf8')).toBe(original);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ }
+ },
+ );
+
+ test('preserves admitted bytes on disk and through the public file read', async () => {
+ const path = nextPath(extension);
+ await seed(path, allowed);
+ const response = await rawRequest(
+ server.port,
+ `/api/skill-file?${new URLSearchParams({ scope: 'project', name, path })}`,
+ );
+ expect(response.status, response.body).toBe(200);
+ expect(JSON.parse(response.body)).toMatchObject({ path, kind: 'reference', text: allowed });
+ });
+
+ test('MCP file write returns an actionable content-coordinate refusal without creation', async () => {
+ const path = nextPath(extension);
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name, files: [{ path, content: unsafe(0) }] } },
+ });
+ const text = toolError(result, 0);
+ expectDetail(text, 0, 3);
+ expect.soft(text).toMatch(/\bcontent\b/i);
+ expect.soft(existsSync(diskPath(path))).toBe(false);
+ });
+
+ test('MCP file edit names whole-file content or replacement coordinates without mutation', async () => {
+ const path = nextPath(extension);
+ await seed(path);
+ const result = await client.callTool({
+ name: 'edit',
+ arguments: { skill: { name, file: path, find: 'target', replace: unsafe(31) } },
+ });
+ const text = toolError(result, 31);
+ const fullOffset = original.indexOf('target') + 3;
+ const contentCoordinate =
+ /\bcontent\b/i.test(text) && new RegExp(`offset\\D*${fullOffset}\\b`, 'i').test(text);
+ const replacementCoordinate = /replace/i.test(text) && /offset\D*3\b/i.test(text);
+ expect.soft(contentCoordinate || replacementCoordinate, text).toBe(true);
+ expect.soft(readFileSync(diskPath(path), 'utf8')).toBe(original);
+ });
+
+ test('MCP file write and edit preserve admitted Markdown bytes', async () => {
+ const path = nextPath(extension);
+ const written = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name, files: [{ path, content: allowed }] } },
+ });
+ expect(written.isError, JSON.stringify(written.content)).not.toBe(true);
+ expect(readFileSync(diskPath(path), 'utf8')).toBe(allowed);
+ const edited = await client.callTool({
+ name: 'edit',
+ arguments: { skill: { name, file: path, find: 'Exact', replace: 'Updated' } },
+ });
+ expect(edited.isError, JSON.stringify(edited.content)).not.toBe(true);
+ expect(readFileSync(diskPath(path), 'utf8')).toBe(allowed.replace('Exact', 'Updated'));
+ });
+ },
+);
diff --git a/packages/server/src/api-skill-file-path-alias-admission.test.ts b/packages/server/src/api-skill-file-path-alias-admission.test.ts
new file mode 100644
index 000000000..9c327c0c1
--- /dev/null
+++ b/packages/server/src/api-skill-file-path-alias-admission.test.ts
@@ -0,0 +1,149 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ bootArtifactAdmissionRig,
+ settleArtifactContributors,
+} from './artifact-admission-rig.test-helper.ts';
+import type { BootedServer } from './boot.ts';
+import { rawRequest } from './composition-rig.test-helper.ts';
+import { __formatContributorsForTests } from './contributor-tracker.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+
+const aliases = [
+ ['references/notes.md/', 'references/notes.md'],
+ ['references/notes.md/.', 'references/notes.md'],
+ ['references\\notes.md\\', 'references/notes.md'],
+ ['references//./notes.MDX/./', 'references/notes.MDX'],
+] as const;
+const allowed = 'Exact\tline\r\nPrintable \\u0000 😀\u007f\u0080\u009f.\n';
+let root: string;
+let server: BootedServer;
+let client: Client;
+let sequence = 0;
+
+function put(name: string, path: string, content: string) {
+ return rawRequest(server.port, '/api/skill-file', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ scope: 'project', name, path, content }),
+ });
+}
+
+async function seedSkill() {
+ const name = `alias-admission-${++sequence}`;
+ const response = await rawRequest(server.port, '/api/skill', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name,
+ body: 'Project instructions.\n',
+ frontmatter: { name, description: 'Path admission' },
+ }),
+ });
+ expect(response.status, response.body).toBe(200);
+ return name;
+}
+
+async function read(name: string, path: string) {
+ return rawRequest(
+ server.port,
+ `/api/skill-file?${new URLSearchParams({ name, scope: 'project', path })}`,
+ );
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-skill-path-alias-'));
+ const builtin = join(root, '.agents', 'skills', 'open-knowledge');
+ mkdirSync(builtin, { recursive: true });
+ writeFileSync(
+ join(builtin, 'SKILL.md'),
+ '---\nname: open-knowledge\ndescription: Project\n---\nProject.\n',
+ );
+ server = await bootArtifactAdmissionRig(root);
+ client = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await server?.destroy();
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(['HTTP', 'MCP'] as const)('%s normalized skill file admission', (transport) => {
+ test.each(aliases)(
+ 'refuses controls through %s without changing the canonical file %s',
+ async (alias, canonical) => {
+ const name = await seedSkill();
+ const seeded = await put(name, canonical, allowed);
+ expect(seeded.status, seeded.body).toBe(200);
+ const path = join(root, '.agents', 'skills', name, canonical);
+ const original = readFileSync(path);
+ await settleArtifactContributors(server);
+ const contributors = __formatContributorsForTests();
+ const content = 'x😀\u0000private-tail';
+ let detail: string;
+ if (transport === 'HTTP') {
+ const response = await put(name, alias, content);
+ expect.soft(response.status, response.body).toBe(400);
+ detail = response.body;
+ } else {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name, files: [{ path: alias, content }] } },
+ });
+ expect.soft(result.isError, JSON.stringify(result.content)).toBe(true);
+ detail = JSON.stringify(result.content);
+ }
+ expect.soft(detail).toContain('U+0000');
+ expect.soft(detail).toMatch(/UTF-?16/i);
+ expect.soft(detail).toMatch(/offset\D*3\b/i);
+ expect.soft(detail).not.toContain('private-tail');
+ expect.soft(readFileSync(path)).toEqual(original);
+ expect.soft(__formatContributorsForTests()).toBe(contributors);
+ const loaded = await read(name, canonical);
+ expect.soft(loaded.status, loaded.body).toBe(200);
+ expect.soft(JSON.parse(loaded.body).text).toBe(allowed);
+ },
+ );
+
+ test.each(aliases)('accepts admitted bytes through %s at %s', async (alias, canonical) => {
+ const name = await seedSkill();
+ if (transport === 'HTTP') {
+ const response = await put(name, alias, allowed);
+ expect(response.status, response.body).toBe(200);
+ } else {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name, files: [{ path: alias, content: allowed }] } },
+ });
+ expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
+ }
+ expect(readFileSync(join(root, '.agents', 'skills', name, canonical), 'utf8')).toBe(allowed);
+ const loaded = await read(name, canonical);
+ expect(loaded.status, loaded.body).toBe(200);
+ expect(JSON.parse(loaded.body).text).toBe(allowed);
+ });
+
+ test.each([
+ ['scripts/fixture.sh/.', 'scripts/fixture.sh'],
+ ['assets/fixture.svg/', 'assets/fixture.svg'],
+ ['references/notes.md.bak/', 'references/notes.md.bak'],
+ ])('preserves opaque control bytes through %s at %s', async (alias, canonical) => {
+ const name = await seedSkill();
+ const content = 'opaque\u0000\u001f\n';
+ if (transport === 'HTTP') {
+ const response = await put(name, alias, content);
+ expect(response.status, response.body).toBe(200);
+ } else {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name, files: [{ path: alias, content }] } },
+ });
+ expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
+ }
+ expect(readFileSync(join(root, '.agents', 'skills', name, canonical), 'utf8')).toBe(content);
+ });
+});
diff --git a/packages/server/src/artifact-admission-rig.test-helper.ts b/packages/server/src/artifact-admission-rig.test-helper.ts
new file mode 100644
index 000000000..37aef8437
--- /dev/null
+++ b/packages/server/src/artifact-admission-rig.test-helper.ts
@@ -0,0 +1,15 @@
+import { expect } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
+
+export async function bootArtifactAdmissionRig(root: string): Promise<BootedServer> {
+ const server = await bootCompositionRig(root, { enableTestRoutes: true });
+ await server.ready;
+ await server.generatedIndexSweepReady;
+ return server;
+}
+
+export async function settleArtifactContributors(server: BootedServer): Promise<void> {
+ const response = await rawRequest(server.port, '/api/test-flush-git', { method: 'POST' });
+ expect(response.status, response.body).toBe(200);
+}
diff --git a/packages/server/src/content/skills-write.ts b/packages/server/src/content/skills-write.ts
index 1be4cc548..88f9a23fa 100644
--- a/packages/server/src/content/skills-write.ts
+++ b/packages/server/src/content/skills-write.ts
@@ -8,6 +8,7 @@ import {
SKILL_NAME_REGEX,
type SkillAuthoringWarningCode,
type SkillFrontmatter,
+ skillFilePathSegments,
} from '@inkeep/open-knowledge-core';
import { ATOMIC_TEMP_INFIX, atomicTempPath } from '@inkeep/open-knowledge-core/server';
import { stringify as stringifyYaml } from 'yaml';
@@ -244,10 +245,7 @@ function resolveBundleFileAbs(
if (typeof relPath !== 'string' || relPath.length === 0 || relPath.includes('\x00')) {
return { ok: false, error: { code: 'BAD_FILE_PATH', message: 'Invalid skill file path.' } };
}
- const segments = relPath
- .replace(/\\/g, '/')
- .split('/')
- .filter((s) => s !== '' && s !== '.');
+ const segments = skillFilePathSegments(relPath);
if (segments.length === 0 || segments.some((s) => s === '..')) {
return {
ok: false,
diff --git a/packages/server/src/http/request-validation.ts b/packages/server/src/http/request-validation.ts
index 8c2e3e0bc..ea61963dd 100644
--- a/packages/server/src/http/request-validation.ts
+++ b/packages/server/src/http/request-validation.ts
@@ -123,12 +123,19 @@ export function validateBody<T>(
if (parseResult.success) {
return { ok: true, value: parseResult.data };
}
- const detail = parseResult.error.issues
+ const contentControlAdmission = parseResult.error.issues.some(
+ (issue) => issue.code === 'custom' && issue.params?.contentControlAdmission === true,
+ );
+ const issues = parseResult.error.issues
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
.join('; ');
+ const detail = contentControlAdmission
+ ? `${issues} Offsets count the full submitted field after caller composition, including any frontmatter.`
+ : issues;
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Request body is invalid.', {
handler: options.handler,
detail,
+ ...(contentControlAdmission ? { extensions: { contentControlAdmission: true } } : {}),
});
return { ok: false };
}
diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.ts
index b6b516f62..709372042 100644
--- a/packages/server/src/http/skills-file-routes.ts
+++ b/packages/server/src/http/skills-file-routes.ts
@@ -12,6 +12,7 @@ import {
SkillFilePutSuccessSchema,
SkillFileRenameRequestSchema,
SkillFileRenameSuccessSchema,
+ skillFilePathSegments,
} from '@inkeep/open-knowledge-core';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { composeAndWriteRawBody } from '../bridge-intake.ts';
@@ -208,10 +209,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup
} = deps;
function classifySkillFilePath(rel: string): 'reference' | 'script' | 'file' | null {
if (rel.includes('\x00')) return null;
- const segments = rel
- .replace(/\\/g, '/')
- .split('/')
- .filter((s) => s !== '' && s !== '.');
+ const segments = skillFilePathSegments(rel);
if (segments.length < 1 || segments.some((s) => s === '..')) return null;
if (segments.length === 1 && (segments[0] as string).toLowerCase() === 'skill.md') return null;
if (segments[0] === 'references' && segments.length >= 2) return 'reference';
diff --git a/packages/server/src/mcp/tools/admission-failure-formatter-wiring.test.ts b/packages/server/src/mcp/tools/admission-failure-formatter-wiring.test.ts
new file mode 100644
index 000000000..ba2ed2e25
--- /dev/null
+++ b/packages/server/src/mcp/tools/admission-failure-formatter-wiring.test.ts
@@ -0,0 +1,188 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { ConfigSchema } from '../../config/schema.ts';
+import { installJsonSchemaDialect } from '../json-schema-dialect.ts';
+import { register as registerEdit } from './edit.ts';
+import { register as registerWrite } from './write.ts';
+
+const failures = [
+ {
+ status: 409,
+ type: 'urn:ok:error:doc-in-conflict',
+ title: 'Conflict',
+ detail: 'Resolve the conflict first.',
+ },
+ {
+ status: 503,
+ type: 'urn:ok:error:too-many-agent-sessions',
+ title: 'Session limit',
+ detail: 'Retry after a session closes.',
+ },
+ {
+ status: 404,
+ type: 'urn:ok:error:not-found',
+ title: 'Missing target',
+ detail: 'The target was removed.',
+ },
+] as const;
+const cases = [
+ {
+ label: 'template write',
+ tool: 'write',
+ args: {
+ template: {
+ path: 'templates/existing',
+ content: 'Safe.',
+ frontmatter: { title: 'Existing' },
+ },
+ },
+ },
+ {
+ label: 'template body edit',
+ tool: 'edit',
+ args: { template: { path: 'templates/existing', find: 'target', replace: 'replacement' } },
+ },
+ {
+ label: 'template frontmatter edit',
+ tool: 'edit',
+ args: { template: { path: 'templates/existing', frontmatter: { description: 'Updated' } } },
+ },
+ {
+ label: 'skill write',
+ tool: 'write',
+ args: { skill: { name: 'existing', description: 'Existing', body: 'Safe.' } },
+ },
+ {
+ label: 'skill description edit',
+ tool: 'edit',
+ args: { skill: { name: 'existing', description: 'Updated' } },
+ },
+ {
+ label: 'skill body edit',
+ tool: 'edit',
+ args: { skill: { name: 'existing', find: 'target', replace: 'replacement' } },
+ },
+ ...['references/example.md', 'scripts/example.sh', 'assets/example.svg'].map((path) => ({
+ label: `skill file write ${path}`,
+ tool: 'write',
+ args: { skill: { name: 'existing', files: [{ path, content: 'Safe.' }] } },
+ })),
+ ...['references/example.md', 'scripts/example.sh', 'assets/example.svg'].map((file) => ({
+ label: `skill file edit ${file}`,
+ tool: 'edit',
+ args: { skill: { name: 'existing', file, find: 'target', replace: 'replacement' } },
+ })),
+] as const;
+let root: string;
+let listener: Server;
+let mcp: McpServer;
+let client: Client;
+let failure: { status: number; type: string; title: string; detail: string } = failures[0];
+let putCount = 0;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-error-formatter-wiring-'));
+ const templates = join(root, 'templates', '.ok', 'templates');
+ mkdirSync(templates, { recursive: true });
+ writeFileSync(join(templates, 'existing.md'), '---\ntitle: Existing\n---\nExisting target.\n');
+ listener = createServer((req, res) => {
+ req.resume();
+ if (req.method === 'GET') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ if (req.url?.startsWith('/api/skill-file')) {
+ res.end(
+ JSON.stringify({
+ path: 'references/example.md',
+ kind: 'reference',
+ text: 'Existing target.\n',
+ }),
+ );
+ return;
+ }
+ res.end(
+ JSON.stringify({
+ skill: {
+ frontmatter: { description: 'Existing' },
+ body: 'Existing target.\n',
+ files: [],
+ },
+ }),
+ );
+ return;
+ }
+ putCount++;
+ res.writeHead(failure.status, { 'Content-Type': 'application/problem+json' });
+ res.end(JSON.stringify(failure));
+ });
+ await new Promise<void>((resolve) => listener.listen(0, '127.0.0.1', resolve));
+ const address = listener.address();
+ if (address === null || typeof address === 'string') throw new Error('HTTP listener has no port');
+ mcp = new McpServer({ name: 'formatter-wiring', version: '1' });
+ const deps = {
+ config: ConfigSchema.parse({ content: { dir: '.' } }),
+ resolveCwd: async () => root,
+ serverUrl: `http://127.0.0.1:${address.port}`,
+ };
+ registerWrite(mcp, deps);
+ registerEdit(mcp, deps);
+ installJsonSchemaDialect(mcp);
+ client = new Client({ name: 'formatter-wiring', version: '1' });
+ const [ct, st] = InMemoryTransport.createLinkedPair();
+ await Promise.all([mcp.connect(st), client.connect(ct)]);
+});
+
+afterAll(async () => {
+ await client?.close();
+ await mcp?.close();
+ if (listener)
+ await new Promise<void>((resolve, reject) =>
+ listener.close((error) => (error ? reject(error) : resolve())),
+ );
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each(failures)(
+ 'controlled HTTP $status formatter wiring, not persistence fidelity',
+ (problem) => {
+ test.each(cases)(
+ '$label preserves failure detail without content-offset advice',
+ async ({ tool, args }) => {
+ failure = problem;
+ const count = putCount;
+ const result = await client.callTool({ name: tool, arguments: args });
+ expect(putCount).toBe(count + 1);
+ expect(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain(problem.title);
+ expect.soft(text).toContain(problem.detail);
+ expect.soft(text).not.toMatch(/(?:body|content) offset|full submitted|whole submitted/i);
+ },
+ );
+ },
+);
+
+test.each(['scripts/example.sh', 'assets/example.svg'])(
+ 'controlled invalid-request formatter excludes opaque %s from admission advice',
+ async (path) => {
+ failure = {
+ status: 400,
+ type: 'urn:ok:error:invalid-request',
+ title: 'Invalid path',
+ detail: 'The destination path is invalid.',
+ };
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { skill: { name: 'existing', files: [{ path, content: 'Safe.' }] } },
+ });
+ expect(result.isError).toBe(true);
+ const text = JSON.stringify(result.content);
+ expect.soft(text).toContain(failure.detail);
+ expect.soft(text).not.toMatch(/(?:body|content) offset|full submitted|whole submitted/i);
+ },
+);
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index 300f5ae35..a162e30a3 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -64,6 +64,8 @@ import {
SKILL_FILE_DESCRIBE,
SKILL_NAME_DESCRIBE,
SkillScopeArg,
+ TEMPLATE_EDIT_CONTROL_ADVICE,
+ TEMPLATE_METADATA_CONTROL_ADVICE,
TEMPLATE_PATH_DESCRIBE,
} from './verb-schemas.ts';
@@ -365,7 +367,8 @@ async function handleTemplate(
...(summary !== undefined ? { summary } : {}),
...agentIdentityFields(deps.identityRef?.current),
});
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ if (!result.ok)
+ return textResult(errorTextWithDetail(result, TEMPLATE_METADATA_CONTROL_ADVICE), true);
const path = typeof result.path === 'string' ? result.path : undefined;
return textPlusStructured(
`Patched template "${name}" frontmatter${path ? ` (${path})` : ''}.`,
@@ -395,7 +398,8 @@ async function handleTemplate(
...(summary !== undefined ? { summary } : {}),
...agentIdentityFields(deps.identityRef?.current),
});
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ if (!result.ok)
+ return textResult(errorTextWithDetail(result, TEMPLATE_EDIT_CONTROL_ADVICE), true);
const path = typeof result.path === 'string' ? result.path : undefined;
return textPlusStructured(`Edited template "${name}"${path ? ` (${path})` : ''}.`, {
template: { ok: true, path },
@@ -457,6 +461,7 @@ async function handleSkillFileEdit(
scope,
path: pathCheck.path,
content: newText,
+ resubmitted: true,
summary,
identity,
});
@@ -544,6 +549,7 @@ async function handleSkill(
name: skill.name,
description: newDescription,
body: newBody,
+ resubmitted: hasDesc ? 'metadata-edit' : 'body-edit',
summary,
identity: deps.identityRef?.current,
lockDir,
@@ -581,7 +587,12 @@ export function register(server: ServerInstance, deps: EditDeps): void {
.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.'),
+ replace: z
+ .string()
+ .optional()
+ .describe(
+ 'Replacement for the `find` match. Markdown C0 controls allow only TAB, LF and CR; remove others or use printable escapes.',
+ ),
occurrence: z
.number()
.int()
@@ -626,21 +637,30 @@ export function register(server: ServerInstance, deps: EditDeps): void {
.object({
path: z.string().describe(TEMPLATE_PATH_DESCRIBE),
...bodyFields,
- frontmatter: FrontmatterArg.optional().describe('Template metadata merge-patch.'),
+ frontmatter: FrontmatterArg.optional().describe(
+ 'Template metadata merge-patch. Resubmits the full existing body; unsupported C0 controls anywhere in that body refuse the edit.',
+ ),
})
.optional()
- .describe('Edit a TEMPLATE: body (find+replace) or frontmatter (patch).'),
+ .describe(
+ 'Edit a TEMPLATE: body (find+replace) or frontmatter (patch). Edits resubmit the full stored template body, including any supplied replace; unsupported C0 controls anywhere in that body refuse the edit. Remove controls from replace or clean the full body through write({ template: ... }).',
+ ),
skill: z
.object({
name: z.string().describe(SKILL_NAME_DESCRIBE),
file: z.string().optional().describe(SKILL_FILE_DESCRIBE),
...bodyFields,
- description: z.string().optional().describe(SKILL_DESCRIPTION_DESCRIBE),
+ description: z
+ .string()
+ .optional()
+ .describe(
+ `${SKILL_DESCRIPTION_DESCRIBE} Resubmits the full existing body; unsupported C0 controls anywhere in that body refuse the edit.`,
+ ),
scope: SkillScopeArg.optional(),
})
.optional()
.describe(
- 'Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE bundle file.',
+ 'Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE bundle file. Without file, edits resubmit the full stored skill body, including any supplied replace; unsupported C0 controls anywhere in that body refuse the edit. With file, edits resubmit the full file content, including frontmatter and replace; Markdown files must be wholly clean. Remove controls from replace or clean the full body/file through write({ skill: ... }).',
),
summary: summaryArgSchema,
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
diff --git a/packages/server/src/mcp/tools/metadata-control-advice.test.ts b/packages/server/src/mcp/tools/metadata-control-advice.test.ts
new file mode 100644
index 000000000..9dda5b416
--- /dev/null
+++ b/packages/server/src/mcp/tools/metadata-control-advice.test.ts
@@ -0,0 +1,121 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { afterAll, beforeAll, expect, test } from 'vitest';
+import { ConfigSchema } from '../../config/schema.ts';
+import { installJsonSchemaDialect } from '../json-schema-dialect.ts';
+import { register } from './edit.ts';
+
+let root: string;
+let listener: Server;
+let mcp: McpServer;
+let client: Client;
+let writes = 0;
+const detail = 'body: Disallowed content control U+001F at zero-based UTF-16 offset 9.';
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-metadata-control-advice-'));
+ const templates = join(root, 'templates', '.ok', 'templates');
+ mkdirSync(templates, { recursive: true });
+ writeFileSync(
+ join(templates, 'existing.md'),
+ '---\ntitle: Existing\n---\nHistorical\u001f body.\n',
+ );
+ listener = createServer((req, res) => {
+ req.resume();
+ if (req.method === 'GET') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ skill: {
+ frontmatter: { description: 'Existing' },
+ body: 'Historical\u001f body.\n',
+ files: [],
+ },
+ }),
+ );
+ return;
+ }
+ writes++;
+ res.writeHead(400, { 'Content-Type': 'application/problem+json' });
+ res.end(
+ JSON.stringify({
+ type: 'urn:ok:error:invalid-request',
+ title: 'Request body is invalid.',
+ status: 400,
+ contentControlAdmission: true,
+ detail,
+ }),
+ );
+ });
+ await new Promise<void>((resolve) => listener.listen(0, '127.0.0.1', resolve));
+ const address = listener.address();
+ if (address === null || typeof address === 'string') throw new Error('Missing listener port');
+ mcp = new McpServer({ name: 'metadata-control-advice', version: '1' });
+ register(mcp, {
+ config: ConfigSchema.parse({ content: { dir: '.' } }),
+ resolveCwd: async () => root,
+ serverUrl: `http://127.0.0.1:${address.port}`,
+ });
+ installJsonSchemaDialect(mcp);
+ client = new Client({ name: 'metadata-control-advice', version: '1' });
+ const [ct, st] = InMemoryTransport.createLinkedPair();
+ await Promise.all([mcp.connect(st), client.connect(ct)]);
+});
+
+afterAll(async () => {
+ await client?.close();
+ await mcp?.close();
+ if (listener)
+ await new Promise<void>((resolve, reject) =>
+ listener.close((error) => (error ? reject(error) : resolve())),
+ );
+ rmSync(root, { recursive: true, force: true });
+});
+
+test.each([
+ {
+ label: 'template frontmatter',
+ args: { template: { path: 'templates/existing', frontmatter: { description: 'Updated' } } },
+ kind: 'template',
+ },
+ {
+ label: 'skill description',
+ args: { skill: { name: 'existing', description: 'Updated' } },
+ kind: 'skill',
+ },
+])('$label refusal repairs stored body without naming absent replace', async ({ args, kind }) => {
+ const count = writes;
+ const result = await client.callTool({ name: 'edit', arguments: args });
+ expect(writes).toBe(count + 1);
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual([
+ {
+ type: 'text',
+ text: `Error: Request body is invalid. (${detail}) Any body offset refers to the full stored ${kind} body resubmitted by this edit. Remove stored controls through a clean full replacement using write({ ${kind}: ... }).`,
+ },
+ ]);
+});
+
+test('template edit description states full-body precondition before a call', async () => {
+ const tools = await client.listTools();
+ const schema = tools.tools.find((tool) => tool.name === 'edit')?.inputSchema;
+ expect(schema?.properties?.template).toMatchObject({
+ description: expect.stringContaining('Edits resubmit the full stored template body'),
+ });
+});
+
+test('skill edit description distinguishes body and bundle-file preconditions', async () => {
+ const tools = await client.listTools();
+ const schema = tools.tools.find((tool) => tool.name === 'edit')?.inputSchema;
+ expect(schema?.properties?.skill).toMatchObject({
+ description: expect.stringContaining('Without file, edits resubmit the full stored skill body'),
+ });
+ expect(schema?.properties?.skill).toMatchObject({
+ description: expect.stringContaining('With file, edits resubmit the full file content'),
+ });
+});
diff --git a/packages/server/src/mcp/tools/non-admission-invalid-request-wiring.test.ts b/packages/server/src/mcp/tools/non-admission-invalid-request-wiring.test.ts
new file mode 100644
index 000000000..49458e19f
--- /dev/null
+++ b/packages/server/src/mcp/tools/non-admission-invalid-request-wiring.test.ts
@@ -0,0 +1,176 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { ConfigSchema } from '../../config/schema.ts';
+import { installJsonSchemaDialect } from '../json-schema-dialect.ts';
+import { register as registerEdit } from './edit.ts';
+import { register as registerWrite } from './write.ts';
+
+const cases = [
+ {
+ label: 'template write name',
+ tool: 'write',
+ args: {
+ template: {
+ path: 'templates/existing',
+ content: 'Safe.',
+ frontmatter: { title: 'Existing' },
+ },
+ },
+ detail: 'BAD_NAME',
+ },
+ {
+ label: 'template body edit compose',
+ tool: 'edit',
+ args: { template: { path: 'templates/existing', find: 'target', replace: 'replacement' } },
+ detail: 'INVALID_SUBSTITUTION',
+ },
+ {
+ label: 'template frontmatter edit',
+ tool: 'edit',
+ args: { template: { path: 'templates/existing', frontmatter: { description: 'Updated' } } },
+ detail: 'BAD_TITLE',
+ },
+ {
+ label: 'skill write description',
+ tool: 'write',
+ args: { skill: { name: 'existing', description: 'Existing', body: 'Safe.' } },
+ detail: 'DESCRIPTION_TOO_LONG',
+ },
+ {
+ label: 'skill description edit',
+ tool: 'edit',
+ args: { skill: { name: 'existing', description: 'Updated' } },
+ detail: 'DESCRIPTION_HAS_XML',
+ },
+ {
+ label: 'skill body edit summary',
+ tool: 'edit',
+ args: { skill: { name: 'existing', find: 'target', replace: 'replacement' } },
+ detail: 'INVALID_SUMMARY',
+ },
+ {
+ label: 'Markdown bundle write',
+ tool: 'write',
+ args: {
+ skill: { name: 'existing', files: [{ path: 'references/example.md', content: 'Safe.' }] },
+ },
+ detail: 'BAD_PATH',
+ batch: true,
+ },
+ {
+ label: 'Markdown bundle edit',
+ tool: 'edit',
+ args: {
+ skill: {
+ name: 'existing',
+ file: 'references/example.md',
+ find: 'target',
+ replace: 'replacement',
+ },
+ },
+ detail: 'INVALID_SUMMARY',
+ },
+] as const;
+let root: string;
+let listener: Server;
+let mcp: McpServer;
+let client: Client;
+let problem = {
+ type: 'urn:ok:error:invalid-request',
+ status: 400,
+ title: 'Invalid artifact request.',
+ detail: 'BAD_NAME',
+};
+let writes = 0;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-non-admission-wiring-'));
+ const templates = join(root, 'templates', '.ok', 'templates');
+ mkdirSync(templates, { recursive: true });
+ writeFileSync(join(templates, 'existing.md'), '---\ntitle: Existing\n---\nExisting target.\n');
+ listener = createServer((req, res) => {
+ req.resume();
+ if (req.method === 'GET') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(
+ JSON.stringify(
+ req.url?.startsWith('/api/skill-file')
+ ? { path: 'references/example.md', kind: 'reference', text: 'Existing target.\n' }
+ : {
+ skill: {
+ frontmatter: { description: 'Existing' },
+ body: 'Existing target.\n',
+ files: [],
+ },
+ },
+ ),
+ );
+ return;
+ }
+ writes++;
+ res.writeHead(problem.status, { 'Content-Type': 'application/problem+json' });
+ res.end(JSON.stringify(problem));
+ });
+ await new Promise<void>((resolve) => listener.listen(0, '127.0.0.1', resolve));
+ const address = listener.address();
+ if (address === null || typeof address === 'string')
+ throw new Error('Missing HTTP listener port');
+ mcp = new McpServer({ name: 'non-admission-wiring', version: '1' });
+ const deps = {
+ config: ConfigSchema.parse({ content: { dir: '.' } }),
+ resolveCwd: async () => root,
+ serverUrl: `http://127.0.0.1:${address.port}`,
+ };
+ registerWrite(mcp, deps);
+ registerEdit(mcp, deps);
+ installJsonSchemaDialect(mcp);
+ client = new Client({ name: 'non-admission-wiring', version: '1' });
+ const [ct, st] = InMemoryTransport.createLinkedPair();
+ await Promise.all([mcp.connect(st), client.connect(ct)]);
+});
+
+afterAll(async () => {
+ await client?.close();
+ await mcp?.close();
+ if (listener)
+ await new Promise<void>((resolve, reject) =>
+ listener.close((error) => (error ? reject(error) : resolve())),
+ );
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe.each([false, true])(
+ 'controlled non-admission 400 formatter wiring (C0-like echoed text=%s)',
+ (spoof) => {
+ test.each(cases)('$label returns exactly its problem title and detail', async (item) => {
+ problem = {
+ type: 'urn:ok:error:invalid-request',
+ status: 400,
+ title: spoof ? 'Request body is invalid.' : 'Invalid artifact request.',
+ detail: spoof
+ ? 'body: Disallowed content control U+0000 at zero-based UTF-16 offset 3. C0 controls allow only TAB, LF and CR. Remove the character or replace it with a printable escape such as \\u0000.'
+ : item.detail,
+ };
+ const count = writes;
+ const result = await client.callTool({ name: item.tool, arguments: item.args });
+ expect(writes).toBe(count + 1);
+ expect(result.isError).toBe(true);
+ const expected = `Error: ${problem.title} (${problem.detail})`;
+ expect(result.content).toEqual([
+ {
+ type: 'text',
+ text:
+ 'batch' in item
+ ? `0/1 bundle file(s) written.\n Failed references/example.md: ${expected}`
+ : expected,
+ },
+ ]);
+ });
+ },
+);
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 04a83b737..3cbb45307 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -158,8 +158,17 @@ export function requestFailureText(result: { [key: string]: unknown }): string {
return `${title}${detail}${retryAfter}`;
}
-export function errorTextWithDetail(result: { [key: string]: unknown }): string {
- return `Error: ${requestFailureText(result)}`;
+export function errorTextWithDetail(
+ result: { [key: string]: unknown },
+ invalidRequestAdvice?: string,
+): string {
+ const advice =
+ result.type === 'urn:ok:error:invalid-request' &&
+ result.contentControlAdmission === true &&
+ invalidRequestAdvice
+ ? ` ${invalidRequestAdvice}`
+ : '';
+ return `Error: ${requestFailureText(result)}${advice}`;
}
export function textResult(text: string, isError?: boolean) {
diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.ts
index 6969c95fc..20bc28b8a 100644
--- a/packages/server/src/mcp/tools/skill-target.ts
+++ b/packages/server/src/mcp/tools/skill-target.ts
@@ -5,6 +5,7 @@ import {
type EditorId,
HUB_READER_EDITORS,
interpretSkillMoveFailure,
+ isMarkdownSkillFilePath,
normalizeApiWarnings,
SKILL_AUTHORING_WARNING_CODES,
type SkillMoveFailureOutcome,
@@ -24,7 +25,12 @@ import {
textPlusStructured,
textResult,
} from './shared.ts';
-import { resolveSkillName } from './verb-schemas.ts';
+import {
+ resolveSkillName,
+ SKILL_EDIT_CONTROL_ADVICE,
+ SKILL_FILE_EDIT_CONTROL_ADVICE,
+ SKILL_METADATA_CONTROL_ADVICE,
+} from './verb-schemas.ts';
export type { SkillScope };
@@ -48,6 +54,7 @@ export async function writeSkill(
name: string;
description: string;
body?: string;
+ resubmitted?: 'body-edit' | 'metadata-edit';
lockDir?: string;
} & SkillIdentity,
) {
@@ -62,7 +69,18 @@ export async function writeSkill(
...(input.summary !== undefined ? { summary: input.summary } : {}),
...agentIdentityFields(input.identity),
});
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ if (!result.ok)
+ return textResult(
+ errorTextWithDetail(
+ result,
+ input.resubmitted
+ ? input.resubmitted === 'metadata-edit'
+ ? SKILL_METADATA_CONTROL_ADVICE
+ : SKILL_EDIT_CONTROL_ADVICE
+ : 'Any body offset refers to the full submitted skill body.',
+ ),
+ true,
+ );
const created = result.created === true;
const path = typeof result.path === 'string' ? result.path : undefined;
const aligned = alignWarningCodes(
@@ -118,7 +136,13 @@ export async function fetchSkill(
export async function writeSkillFile(
url: string | undefined,
- input: { scope?: SkillScope; name: string; path: string; content: string } & SkillIdentity,
+ input: {
+ scope?: SkillScope;
+ name: string;
+ path: string;
+ content: string;
+ resubmitted?: true;
+ } & SkillIdentity,
) {
const resolved = resolveSkillName(input.name);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
@@ -131,7 +155,18 @@ export async function writeSkillFile(
...(input.summary !== undefined ? { summary: input.summary } : {}),
...agentIdentityFields(input.identity),
});
- if (!result.ok) return textResult(`Error: ${result.error}`, true);
+ if (!result.ok)
+ return textResult(
+ errorTextWithDetail(
+ result,
+ isMarkdownSkillFilePath(input.path)
+ ? input.resubmitted
+ ? SKILL_FILE_EDIT_CONTROL_ADVICE
+ : 'Any content offset refers to the whole submitted file content, including frontmatter.'
+ : undefined,
+ ),
+ true,
+ );
const created = result.created === true;
const path = typeof result.path === 'string' ? result.path : input.path;
const kind = result.kind === 'script' ? 'script' : 'reference';
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index 1231789c3..33b822c65 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -3,6 +3,7 @@ import {
FrontmatterValueSchema,
MANAGED_ARTIFACT_SCOPES,
SKILL_NAME_REGEX,
+ skillFilePathSegments,
TEMPLATE_NAME_REGEX,
} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
@@ -90,6 +91,16 @@ export const SKILL_DESCRIPTION_DESCRIBE =
'One-line description (≤1024 chars) — the PRIMARY triggering surface telling an agent WHEN to use this skill. No XML tags (`<...>`), which break the skill loader.';
export const SKILL_BODY_DESCRIBE =
'SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`.';
+export const TEMPLATE_EDIT_CONTROL_ADVICE =
+ 'Any body offset refers to the full stored template body resubmitted by this edit, including any supplied replace. Clean controls in replace, or, if stored controls remain, use a clean full replacement through write({ template: ... }).';
+export const TEMPLATE_METADATA_CONTROL_ADVICE =
+ 'Any body offset refers to the full stored template body resubmitted by this edit. Remove stored controls through a clean full replacement using write({ template: ... }).';
+export const SKILL_EDIT_CONTROL_ADVICE =
+ 'Any body offset refers to the full stored skill body resubmitted by this edit, including any supplied replace. Clean controls in replace, or, if stored controls remain, use a clean full replacement through write({ skill: ... }).';
+export const SKILL_METADATA_CONTROL_ADVICE =
+ 'Any body offset refers to the full stored skill body resubmitted by this edit. Remove stored controls through a clean full replacement using write({ skill: ... }).';
+export const SKILL_FILE_EDIT_CONTROL_ADVICE =
+ 'Any content offset refers to the full stored file content resubmitted by this edit, including frontmatter and any supplied replace. Clean controls in replace, or, if stored controls remain, use a clean full replacement through write({ skill: { files: ... } }).';
const SKILL_SCOPE_DESCRIBE =
'Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.';
@@ -138,10 +149,7 @@ export function resolveSkillFilePath(
error: `a skill file \`path\` must be skill-relative, not absolute — "${path}" is rejected. e.g. { path: "references/tiers.md" }.`,
};
}
- const segments = path
- .replace(/\\/g, '/')
- .split('/')
- .filter((s) => s !== '' && s !== '.');
+ const segments = skillFilePathSegments(path);
if (segments.some((s) => s === '..')) {
return {
ok: false,
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 60bebe8c7..11525012f 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -46,6 +46,7 @@ import {
CANONICAL_COMPONENT_GUIDANCE,
docExtensionOnDisk,
documentResultBaseShape,
+ errorTextWithDetail,
HOCUSPOCUS_NOT_RUNNING_ERROR,
httpPost,
httpPut,
@@ -321,11 +322,23 @@ async function writeOneDoc(
...agentIdentityFields(identity),
});
if (!result.ok) {
+ const offsetBasis =
+ result.type === 'urn:ok:error:invalid-request' && result.contentControlAdmission === true
+ ? spec.template !== undefined
+ ? ' Any markdown offset refers to generated template Markdown after substitution.'
+ : hasFrontmatter
+ ? ' Any markdown offset refers to composed Markdown including frontmatter.'
+ : ' Any markdown offset refers to document.content as forwarded.'
+ : '';
const recovery =
result.type === CONCURRENT_OVERWRITE_REFUSED_TYPE
? ' Wait and retry, or use edit for a targeted change.'
: '';
- return { docName, ok: false, error: `${requestFailureText(result)}${recovery}` };
+ return {
+ docName,
+ ok: false,
+ error: `${requestFailureText(result)}${offsetBasis}${recovery}`,
+ };
}
if (spec.template !== undefined && hasFrontmatter) {
@@ -436,7 +449,10 @@ async function handleTemplate(
...agentIdentityFields(deps.identityRef?.current),
});
if (!result.ok) {
- return textResult(`Error: ${result.error}`, true);
+ return textResult(
+ errorTextWithDetail(result, 'Any body offset refers to the full submitted template.content.'),
+ true,
+ );
}
const created = result.created === true;
const path = typeof result.path === 'string' ? result.path : undefined;
@@ -588,9 +604,11 @@ async function handleSkillWrite(
true,
);
}
+ const normalizedFiles: typeof files = [];
for (const f of files) {
const resolved = resolveSkillFilePath(f.path);
if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);
+ normalizedFiles.push({ ...f, path: resolved.path });
}
const fileResults: Array<{
@@ -615,7 +633,7 @@ async function handleSkillWrite(
if (skillMdResult.isError) return skillMdResult;
}
- for (const f of files) {
+ for (const f of normalizedFiles) {
const r = await writeSkillFile(url, {
name: skill.name,
scope: skill.scope,
@@ -813,7 +831,9 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
content: z
.string()
.optional()
- .describe('The full Markdown body. Mutually exclusive with `template`.'),
+ .describe(
+ 'The full Markdown body. C0 controls allow only TAB, LF and CR; remove others or use printable escapes. Mutually exclusive with `template`.',
+ ),
extension: DocExtensionArg.optional(),
template: z
.string()
@@ -853,7 +873,11 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
template: z
.object({
path: z.string().describe(TEMPLATE_PATH_DESCRIBE),
- content: z.string().describe(TEMPLATE_CONTENT_DESCRIBE),
+ content: z
+ .string()
+ .describe(
+ `${TEMPLATE_CONTENT_DESCRIBE} C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`,
+ ),
frontmatter: z
.object({
title: z
@@ -883,7 +907,12 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
.describe(
`${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`,
),
- body: z.string().optional().describe(SKILL_BODY_DESCRIBE),
+ body: z
+ .string()
+ .optional()
+ .describe(
+ `${SKILL_BODY_DESCRIBE} C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`,
+ ),
files: z
.array(
z.object({
@@ -892,7 +921,11 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
.describe(
'Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.',
),
- content: z.string().describe('Full text of the bundle file.'),
+ content: z
+ .string()
+ .describe(
+ 'Full text of the bundle file, including any frontmatter. For .md/.mdx paths, C0 controls allow only TAB, LF and CR; remove others or use printable escapes.',
+ ),
}),
)
.optional()