Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Refuse agent edits to a path with no document (PRD-7532) (#6000)
Andrew Mikofalvy97dd51046ec3
diff --git a/.changeset/edit-refuses-missing-document.md b/.changeset/edit-refuses-missing-document.mdnew file mode 100644index 000000000..c1409a5cc--- /dev/null+++ b/.changeset/edit-refuses-missing-document.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agent edits to a path with no document now fail with "No document at" and suggest the likely path, instead of "Text not found" or silently creating a file. Appending or prepending to a missing path now says it created a new document.diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex b0452b0fb..6d599f77e 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -27,8 +27,8 @@ 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 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) |+| `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`. An `append` or `prepend` to a path with no document creates it, and the response opens with `Created new document`. 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). A document `edit` changes only an existing document; a path with no document is refused and nothing is created || `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 || `install` | Manage **where** a skill is available. A skill is one real folder (its source, which itself loads) plus managed copies/symlinks at other locations — there is no draft state and no "uninstall everywhere". `add` / `remove` change the other locations (editor ids, `agents`, or custom root paths); `mode` flips an editor copy↔symlink; `source` relocates the real folder. To make a skill stop existing, use `delete` |@@ -130,6 +130,8 @@ A write refused because the document's duplication baseline could not be read atA 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 body or frontmatter edit addressed to a path with no document returns `urn:ok:error:doc-not-found` (404) from `POST /api/agent-patch` and `POST /api/frontmatter-patch`: nothing was written or created, and the body carries `committed: false`. Paths are relative to the content root. The problem body lists up to three likely targets in `candidates` (a folder's hub document, or documents whose trailing path segments match), and the title names them. A find that misses inside an existing document is a different error, `urn:ok:error:target-not-found`.+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.### Resolving a conflictdiff --git a/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts b/packages/app/tests/integration/api-error-envelope/agent-patch.test.tsindex 07bb8171e..7c9a93327 100644--- a/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts+++ b/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts@@ -1,3 +1,5 @@+import { existsSync } from 'node:fs';+import { join } from 'node:path';import { AgentPatchSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';@@ -61,6 +63,30 @@ describe('agent-patch envelope (RFC 9457)', () => {}});+ test('a path with no document emits 404 urn:ok:error:doc-not-found naming the near match', async () => {+ const bundle = `bundle-${crypto.randomUUID().slice(0, 8)}`;+ await agentWriteMd(server.port, '# Ops\n\nthe text that is here\n', {+ docName: `${bundle}/system/ops`,+ position: 'replace',+ });++ const res = await postPatch({+ docName: 'system/ops',+ find: 'the text that is here',+ replace: 'x',+ });+ expect(res.status).toBe(404);+ const body = await res.json();+ const parsed = ProblemDetailsSchema.safeParse(body);+ expect(parsed.success).toBe(true);+ if (parsed.success) {+ expect(parsed.data.type).toBe('urn:ok:error:doc-not-found');+ expect(parsed.data.title).toContain('No document at "system/ops"');+ expect(parsed.data.title).toContain(`"${bundle}/system/ops"`);+ }+ expect(existsSync(join(server.contentDir, 'system/ops.md'))).toBe(false);+ });+test('stale-target emits 409 urn:ok:error:stale-target when explicit offset misses', async () => {const docName = `agent-patch-stale-${crypto.randomUUID().slice(0, 8)}`;await agentWriteMd(server.port, '# Hello world\n', { docName, position: 'replace' });diff --git a/packages/server/assets/skills/project/references/doc-editing.md b/packages/server/assets/skills/project/references/doc-editing.mdindex 8fac059df..60dbe244d 100644--- a/packages/server/assets/skills/project/references/doc-editing.md+++ b/packages/server/assets/skills/project/references/doc-editing.md@@ -2,7 +2,9 @@`edit({ document: { path, find, replace } })` does NOT change frontmatter (body-only; frontmatter-intersecting find/replace returns HTTP 400). For metadata, use `edit({ document: { path, frontmatter: { key: value } } })` — JSON Merge Patch (RFC 7396), `null` deletes, field-level CRDT merge, atomic per-call. For a full rewrite (body + frontmatter together), call `write({ document: { path, content, frontmatter, position: "replace" } })`.-**Stale-session symptom.** If `edit` returns "Text not found" on text you can verify exists on disk (via `exec("cat …")`), the MCP session is likely stale (e.g., after a folder rename or server restart). Treat this as the escape-hatch trigger from the STOP block: prefix your next user-visible sentence with `OpenKnowledge MCP unavailable:` and report the inconsistency. Don't loop on retries — the symptom is structural, not transient.+**Wrong path.** `edit` only changes a document that already exists. When nothing exists at `path` it returns `No document at "<path>"` and changes nothing, naming any near match it found (a folder's hub doc, or a document whose trailing path segments match). Paths are relative to the content root, so a document in a subfolder needs every folder segment from that root. Retry at a suggested path or the corrected one; don't retry the same one. `write` with `position: "append"` or `"prepend"` on a missing path creates the document, and its response opens with `Created new document`. If you meant an existing document, the path is wrong: `delete` the new one and retry at the intended path.++**Stale-session symptom.** If `edit` returns "Text not found" on text you can verify exists on disk (via `exec("cat …")`), or `No document at` a path you can `cat` from the content root, the MCP session is likely stale (e.g., after a folder rename or server restart). Treat this as the escape-hatch trigger from the STOP block: prefix your next user-visible sentence with `OpenKnowledge MCP unavailable:` and report the inconsistency. Don't loop on retries — the symptom is structural, not transient.**Delete / move.** To delete a doc, call `delete({ document })` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible — call `checkpoint()` first if you may need to roll back (it snapshots the whole project; afterwards restore the doc via `restore_version({ document, version })`, finding the `version` in `history`), and `links({ kind: "backlinks", document })` first if you want to fix referrers that will become redlinks. To move or rename a doc instead of delete + rewrite, use `move({ from, to })` — it auto-detects document vs folder vs asset and rewrites incoming references atomically.diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex c9f6ef573..e1e7444c9 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -142,7 +142,7 @@ import { createSkillsInstallRoutes } from './http/skills-install-routes.ts';import { createSkillsListRoutes } from './http/skills-list-routes.ts';import { createSkillsRecoveryRoutes } from './http/skills-recovery-routes.ts';import { createSkillsTrackingRoutes } from './http/skills-tracking-routes.ts';-import { findHubCandidates } from './hub-candidates.ts';+import { findHubCandidates, findMissingDocCandidates } from './hub-candidates.ts';import { recordSkillInstall, removeSkillInstall } from './installed-skills-marker.ts';import { collectDocFiles } from './lint/audit.ts';import { composeAuditGeneration } from './lint/audit-generation.ts';@@ -1810,6 +1810,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {const writeAdvisoryGate = createWriteAdvisoryGate();+ function findMissingDocCandidatesInIndex(docName: string): string[] {+ return findMissingDocCandidates(docName, getFileIndex());+ }+async function computeOrphanHints(docName: string,): Promise<Array<{ type: 'orphan'; parentCandidates: string[]; message: string }> | undefined> {@@ -5377,6 +5381,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {resolveAlias,extractAgentIdentity,docNameExistsWithAnySupportedExtension,+ findMissingDocCandidates: findMissingDocCandidatesInIndex,contentDir,summaryResponseFields,sessionManager,diff --git a/packages/server/src/http/agent-write-routes.test.ts b/packages/server/src/http/agent-write-routes.test.tsindex 2941b4d79..a2bb6537e 100644--- a/packages/server/src/http/agent-write-routes.test.ts+++ b/packages/server/src/http/agent-write-routes.test.ts@@ -32,6 +32,7 @@ function buildGroup(overrides: Partial<Deps> = {}) {label: undefined,}),docNameExistsWithAnySupportedExtension: notDispatched,+ findMissingDocCandidates: notDispatched,contentDir: '/nonexistent-content',summaryResponseFields: () => ({ stored: undefined }),sessionManager: {} as AgentSessionManager,@@ -116,7 +117,11 @@ describe('agent-write session capacity responses', () => {});try {await sessionManager.getSession('occupied', 'agent-occupant');- const group = buildGroup({ hocuspocus, sessionManager });+ const group = buildGroup({+ hocuspocus,+ sessionManager,+ docNameExistsWithAnySupportedExtension: () => true,+ });const route = group.table.resolve(path);if (!route?.dispatch) throw new Error(`${path} did not resolve to a dispatch handler`);const { res, captured } = makeCaptureRes();@@ -137,3 +142,72 @@ describe('agent-write session capacity responses', () => {},);});++describe('edit routes refuse a document path that has nothing behind it', () => {+ test.each([+ ['/api/agent-patch', { docName: 'system/ops', find: 'present elsewhere', replace: 'x' }],+ ['/api/frontmatter-patch', { docName: 'system/ops', patch: { title: 'probe' } }],+ ])('%s answers doc-not-found with near matches and creates nothing', async (path, body) => {+ const hocuspocus = new Hocuspocus({ quiet: true });+ const sessionManager = new AgentSessionManager(hocuspocus);+ try {+ const group = buildGroup({+ hocuspocus,+ sessionManager,+ docNameExistsWithAnySupportedExtension: () => false,+ findMissingDocCandidates: (docName) => (docName === 'system/ops' ? ['kb/system/ops'] : []),+ });+ const route = group.table.resolve(path);+ if (!route?.dispatch) throw new Error(`${path} did not resolve to a dispatch handler`);+ const { res, captured } = makeCaptureRes();+ await route.dispatch(makeReq(path, body), res);+ expect(captured.status).toBe(404);+ const problem = JSON.parse(captured.body);+ expect(problem).toMatchObject({+ type: 'urn:ok:error:doc-not-found',+ candidates: ['kb/system/ops'],+ committed: false,+ });+ expect(problem.title).toContain('No document at "system/ops"');+ expect(problem.title).toContain('Did you mean "kb/system/ops"?');+ expect(problem.title).not.toContain('Text not found');+ expect(problem.title).not.toContain('to create one');+ expect(hocuspocus.documents.has('system/ops')).toBe(false);+ } finally {+ await sessionManager.closeAll();+ }+ });++ test('a path with no near match points to write instead of a suggestion', async () => {+ const hocuspocus = new Hocuspocus({ quiet: true });+ const sessionManager = new AgentSessionManager(hocuspocus);+ try {+ const group = buildGroup({+ hocuspocus,+ sessionManager,+ docNameExistsWithAnySupportedExtension: () => false,+ findMissingDocCandidates: () => [],+ });+ const route = group.table.resolve('/api/agent-patch');+ if (!route?.dispatch)+ throw new Error('/api/agent-patch did not resolve to a dispatch handler');+ const { res, captured } = makeCaptureRes();+ await route.dispatch(+ makeReq('/api/agent-patch', { docName: 'wiki/new', find: 'x', replace: 'y' }),+ res,+ );+ expect(captured.status).toBe(404);+ const problem = JSON.parse(captured.body);+ expect(problem).toMatchObject({+ type: 'urn:ok:error:doc-not-found',+ candidates: [],+ committed: false,+ });+ expect(problem.title).toContain('No document at "wiki/new"');+ expect(problem.title).toContain('use write(');+ expect(problem.title).not.toContain('Did you mean');+ } finally {+ await sessionManager.closeAll();+ }+ });+});diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.tsindex 8012a85b0..045ca48ae 100644--- a/packages/server/src/http/agent-write-routes.ts+++ b/packages/server/src/http/agent-write-routes.ts@@ -154,6 +154,7 @@ export interface AgentWriteRouteDeps {label: string | undefined;};docNameExistsWithAnySupportedExtension: (contentDir: string, docName: string) => boolean;+ findMissingDocCandidates: (docName: string) => string[];contentDir: string;summaryResponseFields: (normalized: NormalizedSummary) => {response?: SummaryResponse;@@ -232,6 +233,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupresolveAlias,extractAgentIdentity,docNameExistsWithAnySupportedExtension,+ findMissingDocCandidates,contentDir,summaryResponseFields,sessionManager,@@ -279,6 +281,28 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup}}+ function respondIfDocumentMissing(+ res: ServerResponse,+ docName: string,+ handler: 'agent-patch' | 'frontmatter-patch',+ ): boolean {+ if (docNameExistsWithAnySupportedExtension(contentDir, docName)) return false;+ if ((hocuspocus.documents.get(docName)?.getText('source').length ?? 0) > 0) return false;+ const candidates = findMissingDocCandidates(docName);+ const nextStep =+ candidates.length === 0+ ? 'edit only changes an existing document; use write({ document: { path, content } }) to create one.'+ : `Did you mean ${candidates.map((c) => `"${c}"`).join(' or ')}? Retry the edit at that path.`;+ errorResponse(+ res,+ 404,+ 'urn:ok:error:doc-not-found',+ `No document at "${docName}" (paths are relative to the content root). ${nextStep}`,+ { handler, extensions: { candidates, committed: false } },+ );+ return true;+ }+function getSystemSubscriberCount(): number {try {const doc = hocuspocus.documents.get(SYSTEM_DOC_NAME);@@ -543,6 +567,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup);return;}+ if (respondIfDocumentMissing(res, resolvedDocName, 'frontmatter-patch')) return;const patch = body.patch ?? {};const patchKeys = Object.keys(patch);const normalizedSummary = normalizeSummary(body.summary);@@ -792,6 +817,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup);return;}+ if (respondIfDocumentMissing(res, docName, 'agent-patch')) return;const normalizedSummary = normalizeSummary(body.summary);await sessionManager.withSessions(async (getSession) => {const session = await getSession(docName, agentId, {diff --git a/packages/server/src/hub-candidates.test.ts b/packages/server/src/hub-candidates.test.tsindex d746d1cb6..39f83757d 100644--- a/packages/server/src/hub-candidates.test.ts+++ b/packages/server/src/hub-candidates.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { findHubCandidates } from './hub-candidates.ts';+import { findHubCandidates, findMissingDocCandidates } from './hub-candidates.ts';function makeIndex(docNames: string[]): ReadonlyMap<string, unknown> {return new Map(docNames.map((name) => [name, { mtime: 0 }]));@@ -76,3 +76,46 @@ describe('findHubCandidates', () => {expect(findHubCandidates('foo', index)).toEqual([]);});});++describe('findMissingDocCandidates', () => {+ test('suggests the hub doc when the missing name is a folder', () => {+ const index = makeIndex(['reports/foo/REPORT', 'reports/foo/evidence']);+ expect(findMissingDocCandidates('reports/foo', index)).toEqual(['reports/foo/REPORT']);+ });++ test('suggests a folder-name-match hub', () => {+ const index = makeIndex(['guides/setup/setup', 'guides/setup/extra']);+ expect(findMissingDocCandidates('guides/setup', index)).toEqual(['guides/setup/setup']);+ });++ test('suggests documents whose trailing segments match a bundle-relative path', () => {+ const index = makeIndex([+ 'kb/system/ways-of-working/operations',+ 'archive/kb/system/ways-of-working/operations',+ 'kb/system/ways-of-working/other',+ ]);+ expect(findMissingDocCandidates('system/ways-of-working/operations', index)).toEqual([+ 'kb/system/ways-of-working/operations',+ 'archive/kb/system/ways-of-working/operations',+ ]);+ });++ test('matches trailing segments whole, not as a substring of a segment', () => {+ const index = makeIndex(['wiki/my-operations', 'wiki/operations']);+ expect(findMissingDocCandidates('operations', index)).toEqual(['wiki/operations']);+ });++ test('lists hubs before trailing-segment matches and caps at 3', () => {+ const index = makeIndex(['notes/INDEX', 'notes/README', 'a/notes', 'b/notes']);+ expect(findMissingDocCandidates('notes', index)).toEqual([+ 'notes/INDEX',+ 'notes/README',+ 'a/notes',+ ]);+ });++ test('returns empty when nothing resembles the missing name', () => {+ const index = makeIndex(['wiki/real']);+ expect(findMissingDocCandidates('wiki/zz-probe', index)).toEqual([]);+ });+});diff --git a/packages/server/src/hub-candidates.ts b/packages/server/src/hub-candidates.tsindex 1f44d3a50..3f0bdcdcf 100644--- a/packages/server/src/hub-candidates.ts+++ b/packages/server/src/hub-candidates.ts@@ -35,6 +35,29 @@ export function findHubCandidates(return candidates;}+export function findMissingDocCandidates(+ missingDocName: string,+ fileIndex: ReadonlyMap<string, unknown>,+): string[] {+ const candidates: string[] = [];+ const lowerIndex = buildLowerDocNameIndex(fileIndex);+ const folderBase = basename(missingDocName);+ for (const base of [...FIXED_HUB_BASENAMES, folderBase]) {+ const hub = lookup(fileIndex, lowerIndex, joinDocName(missingDocName, base));+ if (hub && !candidates.includes(hub)) candidates.push(hub);+ if (candidates.length >= MAX_CANDIDATES) return candidates;+ }+ const suffix = `/${missingDocName.toLowerCase()}`;+ const suffixMatches = [...fileIndex.keys()]+ .filter((docName) => docName.toLowerCase().endsWith(suffix))+ .sort((a, b) => a.length - b.length || a.localeCompare(b));+ for (const docName of suffixMatches) {+ if (!candidates.includes(docName)) candidates.push(docName);+ if (candidates.length >= MAX_CANDIDATES) break;+ }+ return candidates;+}+function lookup(fileIndex: ReadonlyMap<string, unknown>,lowerIndex: ReadonlyMap<string, string>,diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.tsindex a162e30a3..4ae1bafd9 100644--- a/packages/server/src/mcp/tools/edit.ts+++ b/packages/server/src/mcp/tools/edit.ts@@ -166,7 +166,7 @@ async function handleDocBody(}if (full === null) {return textResult(- `Error: cannot resolve occurrence ${occurrence} — "${normalized.docName}" is not on disk yet. Retry with the first match (omit \`occurrence\`).`,+ `Error: No document at "${normalized.docName}" on disk (paths are relative to the content root), so occurrence ${occurrence} cannot be resolved. If the path is wrong, fix it; edit only changes an existing document. If the document was just created and is not saved yet, retry with the first match (omit \`occurrence\`).`,true,);}diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.tsindex b905b534c..265d370fa 100644--- a/packages/server/src/mcp/tools/verb-tools.test.ts+++ b/packages/server/src/mcp/tools/verb-tools.test.ts@@ -89,6 +89,44 @@ describe('edit — body-XOR-frontmatter + exactly-one-target teaching errors', (});});+describe('edit — occurrence on a path with no document', () => {+ test('names the missing document instead of implying it is pending', async () => {+ let requests = 0;+ const server = await startFetchTestServer({+ fetch() {+ requests += 1;+ return Response.json({ error: 'unexpected request' }, { status: 500 });+ },+ });+ try {+ const cwd = newProject();+ let handler: Handler | undefined;+ registerEdit(+ {+ registerTool(_name: string, _cfg: unknown, h: Handler) {+ handler = h;+ },+ } as unknown as ServerInstance,+ {+ serverUrl: `http://127.0.0.1:${server.port}`,+ config: BASE_CONFIG,+ resolveCwd: async () => cwd,+ } as unknown as Parameters<typeof registerEdit>[1],+ );+ if (!handler) throw new Error('tool did not register');+ const r = await handler({+ document: { path: 'system/ops', find: 'x', replace: 'y', occurrence: 2 },+ });+ expect(r.isError).toBe(true);+ expect(textOf(r)).toContain('No document at "system/ops" on disk');+ expect(textOf(r)).not.toContain('not on disk yet');+ expect(requests).toBe(0);+ } finally {+ server.stop();+ }+ });+});+describe('delete — exactly-one-target teaching error', () => {test('two targets rejected', async () => {const del = capture(registerDelete, newProject());diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.tsindex 745fb504e..b12d16840 100644--- a/packages/server/src/mcp/tools/write.test.ts+++ b/packages/server/src/mcp/tools/write.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { stripFrontmatter } from '@inkeep/open-knowledge-core';@@ -303,6 +303,87 @@ describe('write({ document }) relaying a concurrent-overwrite refusal', () => {expect(result.content[0]?.text).toContain('or use edit');});});+describe('write({ document }) appending or prepending to a path with no document', () => {+ interface ToolResult {+ content: Array<{ type: 'text'; text: string }>;+ isError?: true;+ }+ type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;++ let testServer: FetchTestServer;+ let cwd: string;+ let handler: Handler;++ beforeAll(async () => {+ testServer = await startFetchTestServer({+ hostname: '127.0.0.1',+ fetch(request) {+ const { pathname } = new URL(request.url);+ if (pathname === '/api/agent-write-md') {+ return Response.json({ timestamp: new Date().toISOString(), subscriberCount: 0 });+ }+ return Response.json({ error: `unexpected route ${pathname}` }, { status: 500 });+ },+ });+ cwd = mkdtempSync(join(tmpdir(), 'ok-write-created-by-position-'));+ mkdirSync(join(cwd, '.ok'), { recursive: true });+ mkdirSync(join(cwd, 'notes'), { recursive: true });+ writeFileSync(join(cwd, 'notes', 'existing.md'), '# Existing\n');++ let captured: Handler | null = null;+ const server = {+ registerTool(_name: string, _cfg: unknown, toolHandler: Handler) {+ captured = toolHandler;+ },+ } as unknown as ServerInstance;+ registerWrite(server, {+ serverUrl: `http://127.0.0.1:${testServer.port}`,+ config: ConfigSchema.parse({}),+ resolveCwd: async () => cwd,+ });+ if (captured === null) throw new Error('write tool did not register');+ handler = captured;+ });++ afterAll(() => {+ testServer.stop();+ rmSync(cwd, { recursive: true, force: true });+ });++ it('says the append created a new document instead of reporting a plain success', async () => {+ const result = await handler({+ document: { path: 'system/ops', content: 'appended line\n', position: 'append' },+ });++ expect(result.isError).toBeUndefined();+ const text = result.content[0]?.text ?? '';+ expect(text.split('\n')[0]).toContain('Created new document "system/ops"');+ expect(text).not.toContain('Written successfully');+ });++ it('keeps the plain success line when the appended-to document exists', async () => {+ const result = await handler({+ document: { path: 'notes/existing', content: 'more\n', position: 'append' },+ });++ expect(result.content[0]?.text.split('\n')[0]).toBe('Written successfully (append).');+ });++ it('names the created document in a batch entry', async () => {+ const result = await handler({+ documents: [+ { path: 'notes/existing', content: 'more\n', position: 'prepend' },+ { path: 'system/ops', content: 'prepended line\n', position: 'prepend' },+ ],+ });++ const text = result.content[0]?.text ?? '';+ expect(text).toContain('Wrote notes/existing (prepend).');+ expect(text).toContain('Created new document "system/ops"');+ expect(text).not.toContain('Wrote system/ops');+ });+});+describe('write — an asset upload whose request to the server fails', () => {type AssetHandler = (args: Record<string, unknown>) => Promise<{isError?: boolean;diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 11525012f..87c5e1c02 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -125,6 +125,7 @@ type WriteOneResult =position: string;fromTemplate?: string;extensionNote?: string;+ createdByPosition?: 'append' | 'prepend';templateHint?: readonly { name: string; description?: string }[];raw: WriteApiResult;}@@ -143,6 +144,10 @@ export function frontmatterIgnoredNote(return `Note: this \`${position}\` payload opens with a \`---\` fence pair, but what is between the fences is not a YAML mapping, so it was written as BODY text (fence lines included) rather than treated as frontmatter. If you meant a thematic break, that is the correct outcome — \`***\` or \`___\` avoids the ambiguity. If you meant to set frontmatter, the YAML did not parse: use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`;}+function createdByPositionNote(docName: string, position: 'append' | 'prepend'): string {+ return `Created new document "${docName}" — no document existed at this path, so \`${position}\` started a new one. If you meant to add to an existing document, the path is wrong (paths are relative to the content root): remove this one with \`delete({ document: "${docName}" })\` and retry at the intended path.`;+}+function emptyAppendNoOpNote(position: string, markdown: string | undefined): string | null {if ((position !== 'prepend' && position !== 'append') || markdown === undefined) return null;if (splitPayloadFrontmatter(markdown).body !== '') return null;@@ -359,10 +364,15 @@ async function writeOneDoc(}const extensionNote = extensionIgnoredNote(requestedExt, existingExt, docName);+ const createdByPosition =+ !docExists && (effectivePosition === 'append' || effectivePosition === 'prepend')+ ? effectivePosition+ : undefined;return {docName,ok: true,position: effectivePosition,+ ...(createdByPosition ? { createdByPosition } : {}),...(spec.template !== undefined ? { fromTemplate: spec.template } : {}),...(extensionNote ? { extensionNote } : {}),...(templateHint ? { templateHint } : {}),@@ -720,7 +730,11 @@ async function handleBatch(return `No change to ${spec.path} — empty ${r.position}, document unchanged.`;}const d = docOut[i];- const baseParts = [`Wrote ${spec.path} (${r.position}).`];+ const baseParts = [+ r.createdByPosition+ ? createdByPositionNote(r.docName, r.createdByPosition)+ : `Wrote ${spec.path} (${r.position}).`,+ ];if (d?.ok && d.warnings) {baseParts.push(...formatAdvisoryBriefs(d.warnings));}@@ -784,7 +798,8 @@ async function handleSingleDoc(const noOpNote = emptyAppendNoOpNote(w.position, spec.content);const lines: string[] = [- noOpNote ??+ (w.createdByPosition ? createdByPositionNote(w.docName, w.createdByPosition) : null) ??+ noOpNote ??(w.fromTemplate !== undefined? `Written successfully (instantiated from template "${w.fromTemplate}").`: `Written successfully (${w.position}).`),