Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-9772 Report ACP, engine-less and skill write outcomes (#7233)
mike-inkeepdd759dcc7d1f
diff --git a/.changeset/agent-write-outcome.md b/.changeset/agent-write-outcome.mdindex 817181a20..13f651328 100644--- a/.changeset/agent-write-outcome.md+++ b/.changeset/agent-write-outcome.md@@ -2,4 +2,4 @@'@inkeep/open-knowledge': minor----Agent writes to Markdown documents, templates and project skills report `outcome`, `saved` and `nextStep`. `agent-write`, `agent-write-md`, `agent-patch` and `frontmatter-patch` answer 409 `both-kept` or 503 `save-held` where they answered 200: those writes landed, so do not retry. `retryWhen` and warning-level `nextStep` are deprecated.+Agent writes, the in-app agent's file writes included, report `outcome`, `saved` and `nextStep`. Writes that answered 200 can answer 409 `both-kept` or 503 `save-held` (landed; do not retry) or 409 `write-dropped`; in-app file writes return error `-32010` unless applied or merged first. `retryWhen` and warning-level `nextStep` are deprecated.diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex f45db7551..a8088732a 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -102,7 +102,7 @@ MCP `write({ documents: [...] })` writes entries sequentially and returns ordere## Write outcomes-A write the server answers says what happened to it, in three fields: `outcome`, `saved` and `nextStep`. They come back, success or not, on the document, template and skill results of `write` and `edit`, on a document `restore_version` and on a `lint` fix that changed the document, in the structured content and as an `Outcome: …` line in the text; and on the responses of the HTTP agent write routes (`POST /api/agent-write`, `/api/agent-write-md`, `/api/agent-patch`, `/api/frontmatter-patch`, `/api/agent-undo`, `/api/rollback`, `/api/lint/fix`, the template and skill writes, and each entry of `POST /api/agent-write-batch`, on the entry rather than inside its `error`). A request turned away by input validation, a folder or asset write, a skill install and a skill `restore_version` carry none. Writes to Mermaid, Excalidraw, plain-text and settings documents and to global and external skills carry none yet either, because their save does not report its result back to the write. `saved` says whether the write's bytes were in the document's file when the server answered; it is a different field from the `committed` a `move` result carries, which is about git history.+A write the server answers says what happened to it, in three fields: `outcome`, `saved` and `nextStep`. They come back, success or not, on the document, template and skill results of `write` and `edit`, on a document `restore_version` and on a `lint` fix that changed the document, in the structured content and as an `Outcome: …` line in the text; and on the responses of the HTTP agent write routes (`POST /api/agent-write`, `/api/agent-write-md`, `/api/agent-patch`, `/api/frontmatter-patch`, `/api/agent-undo`, `/api/rollback`, `/api/lint/fix`, the template and skill writes, and each entry of `POST /api/agent-write-batch`, on the entry rather than inside its `error`). The in-app agent's file write over ACP (`fs/write_text_file`) answers the same way when the file is a document the project shows: Markdown, including skills and folder templates under dot folders, and Mermaid, Excalidraw and text files. It is written through the document and saved with the same check against the file on disk; as a whole-file write it skips the merge before the write, and its save merges any outside change instead. `applied` and `merged-first` return the three fields under `_meta.openknowledge`. A replace refused by a recent edit keeps error code `-32009`, whose `data` carries `type`, `file`, `retryable` and `retryAfterSeconds` and now the three fields too. Every other outcome is error code `-32010`, whose message is the result's title and detail and whose `data` carries `type` and `file`, plus the three fields whenever the server sent them; a server error (500) sends none. A request turned away by input validation, a folder or asset write, a successful skill install, an ACP write of a file that is not a document (written to disk as is, with an empty result), and a skill `restore_version` carry none. `saved` says whether the write's bytes were in the document's file when the server answered; it is a different field from the `committed` a `move` result carries, which is about git history.| Outcome | What happened | `saved` | What to do || --- | --- | --- | --- |@@ -114,9 +114,9 @@ A write the server answers says what happened to it, in three fields: `outcome`,`nextStep` is `retry` (the write did not land; send it again, corrected the way the result's detail says, such as a fixed path, quoted YAML or a different name, or after the wait it names), `re-read` (re-read the document before doing anything further with it) or `none` (nothing more to do on this document: with `applied` carry on; with `refused` nothing the agent sends changes it, so tell the user what the result says). No outcome asks the agent to wait for a person. Both sets only ever grow. A tool that meets an outcome it does not know reports it as `merged-first` when `saved` is true and `refused` otherwise, with `nextStep: re-read`, and says so in its text. A response with no `outcome` reports none, whatever else it carries, and a `saved` or `nextStep` the server left out stays out. A tool never opens a `refused` result with its success line, whatever the HTTP status.-Two older fields stay for clients written against earlier beta releases and are deprecated: `retryWhen` on `urn:ok:error:save-held`, and `nextStep` inside a `disk-edit-reconciled` warning. Read the top-level `nextStep` instead. On `save-held` the top-level `nextStep` was always `re-read` in those betas; it is now `none` for the two holds that only the user can end (see below).+Two older fields stay for clients written against earlier beta releases and are deprecated: `retryWhen` on `urn:ok:error:save-held`, and `nextStep` inside a `disk-edit-reconciled` warning. Read the top-level `nextStep` instead. On `save-held` the top-level `nextStep` was always `re-read` in those betas; it is now `none` for the holds that only a person can end (see below). The `pending-not-utf8` hold, which those betas never returned, carries no `retryWhen`.-`both-kept`, `projection-held` and `refused` are not plain success. Over MCP they come back as error results; the text of a `both-kept` or `projection-held` result starts by saying the write landed and is not to be repeated. Over HTTP a `both-kept` write to `POST /api/agent-write`, `/api/agent-write-md`, `/api/agent-patch` or `/api/frontmatter-patch` answers `urn:ok:error:both-kept` (409), carrying the same fields a success would (`warnings`, `brokenLinks`, `summary`). The undo, restore, lint fix, template and skill routes, which the app also calls, keep their `200` for a both-kept write, for a save still running when the write stops waiting (`projection-held`) and for a write the file on disk replaced (`refused`), and say which in the fields; a batch entry stays `written` for both-kept. Skill install keeps its `200` in the same cases and carries no fields, because the save it waits for holds pending edits to the skill, not the install itself.+`both-kept`, `projection-held` and `refused` are not plain success. Over MCP they come back as error results; the text of a `both-kept` or `projection-held` result starts by saying the write landed and is not to be repeated. Over HTTP a `both-kept` write to `POST /api/agent-write`, `/api/agent-write-md`, `/api/agent-patch` or `/api/frontmatter-patch` answers `urn:ok:error:both-kept` (409), carrying the same fields a success would (`warnings`, `brokenLinks`, `summary`). The undo, restore, lint fix, template and skill routes, which the app also calls, keep their `200` for a both-kept write, for a save still running when the write stops waiting (`projection-held`) and for a write the file on disk replaced (`refused`), and say which in the fields; a batch entry stays `written` for both-kept. Skill install keeps its `200` in the same cases, and its success carries no fields, because the save it waits for holds pending edits to the skill, not the install itself. When that save fails in any other way, the install is refused with that save's problem, which still carries the fields; they describe the pending edits, not the install.## Refusals and held saves@@ -139,6 +139,7 @@ Every result an agent write can come back with, its fields, and the move they as| `stale-external-write` (409) | `refused` | `false` | `none` | Tell the user which file it is. Your edit is kept in the document and the recovery snapshot; do not repeat it. || `save-held` (503) with `pending-conflict` | `refused` | `false` | `none` | Tell the user which file it is. The save runs once they deal with the file in the app; do not repeat the write. || `save-held` (503) on a file with no agreed version | `refused` | `false` | `none` | Tell the user its file changed outside OpenKnowledge, and do not write to that document again: any write replaces it with the file on disk and moves your edit to its history. |+| `save-held` (503) with `pending-not-utf8` | `refused` | `false` | `none` | Tell the user which file it is: it now holds bytes that are not text, so it is not written over, and no save runs until someone saves it as text again. Do not repeat the write. || `save-held` (503) with any other `reason` | `projection-held` | `false` | `re-read` | Do not repeat the write. Re-read before the next edit; with `pending-rename`, re-read at the new name the detail gives. || `doc-moved` (409) | `projection-held` | `false` | `re-read` | Do not repeat the edit. Re-read the document at the new name the detail gives. || `branch-switched` (409) | `projection-held` | `false` | `re-read` | Do not repeat the edit. Re-read the document before the next edit. |@@ -149,6 +150,9 @@ Every result an agent write can come back with, its fields, and the move they as| `path-escape` (400) | `refused` | `false` | `none` | Tell the user the document's path could not be resolved. || `store-refused` (503) | `refused` | `false` | `re-read` | Do not repeat it now. Once the user has fixed the filesystem fault, re-read and re-apply only what is missing. || `write-replaced` (409) | `refused` | `false` | `re-read` | Re-read: the document now holds the file as it is on disk, and your edit is in its history. Re-apply it if it is still needed. |+| `write-dropped` (409) for a name with no file of its own | `refused` | `false` | `retry` | Send the write again by the skill's or template's file path. |+| `write-dropped` (409) while an outside change was being taken in | `refused` | `false` | `re-read` | Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing. |+| `write-dropped` (409) for a skill folder that is gone or a path that does not resolve | `refused` | `false` | `none` | Tell the user which skill it is: its folder was deleted or moved, or its path no longer resolves. || `storage-full` (507), `storage-readonly` or `storage-error` (500) | `refused` | `false` | `re-read` | Once the user has fixed the storage, re-read and re-apply only what is missing. |A write to a document in a conflict state returns `urn:ok:error:doc-in-conflict` (409, `refused`, `nextStep: none`). Most come from Git: a merge that left the file unmerged, or a pull that collided with local edits. A few come from disk: the file holds conflict markers, or OpenKnowledge could not save an outside version to the document's history. `conflict.kind` says which: `merge-native` for a git merge, `working-tree` for a pull, and a third kind for the disk cases. Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses such a document:@@ -173,11 +177,11 @@ A write that finds another app has put back an older copy of the file, one an eaWhen OpenKnowledge saves a Markdown document, it first compares the file with the version it last agreed with the disk. If another tool changed the file, that change is merged into the document before the save, so the write lands and the file holds both edits, and the result says `merged-first` or `both-kept`. This covers saves of edits made in the app, idle saves, the save at quit, the in-app agent's whole-document write and the agent write routes. Rename, delete and the other writers do not run this comparison yet.-If the save cannot finish safely, the write returns `urn:ok:error:save-held` (503) with `reason` (what holds the save) and, for a file that could not be read, the errno in `causeCode`; in a batch response that entry's `error` carries the same fields. When the file cannot be read (`pending-unreadable`), keeps changing (`pending-exhausted`, `pending-base-moved`) or the outside change could not be merged (`pending-intake-failed`), the outcome is `projection-held`: the edit is in the document, and the next edit or the idle save within a few minutes saves it. The same answer, with `pending-unsettled`, means the save was still running when the write stopped waiting for it, and with `pending-rename` that the document was being moved to a new name outside the app. Do not repeat the write; re-read the document before editing it further.+If the save cannot finish safely, the write returns `urn:ok:error:save-held` (503) with `reason` (what holds the save) and, for a file that could not be read, the errno in `causeCode`; in a batch response that entry's `error` carries the same fields. When the file cannot be read (`pending-unreadable`), keeps changing (`pending-exhausted`, `pending-base-moved`), or the outside change could not be merged (`pending-intake-failed`) or saved to the document's history or the backup folder (`pending-no-history-or-backup`), the outcome is `projection-held`: the edit is in the document, and the next edit or the idle save within a few minutes saves it. The same answer, with `pending-unsettled`, means the save was still running when the write stopped waiting for it, and with `pending-rename` that the document was being moved to a new name outside the app. Do not repeat the write; re-read the document before editing it further.-Two holds are `refused` with `nextStep: none`. One waits for the user to deal with the file in the app (`pending-conflict`). The other is a file OpenKnowledge has no agreed version of: the edit is in the document but is not saved, no save runs on its own, and any further write to the document, the agent's own included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history. Do not write to that document again; tell the user its file changed outside OpenKnowledge. A new document with no file yet is not that case: its held save is `projection-held` like the others. A write whose own save found such a file and took it in instead returns `urn:ok:error:write-replaced` (409, `refused`, `nextStep: re-read`): the document now holds the file as it is on disk and the edit is in its history; re-read and re-apply the edit if it is still needed.+The holds that only a person can end are `refused` with `nextStep: none`. One waits for the user to deal with the file in the app (`pending-conflict`). One is a Mermaid, Excalidraw or plain-text file, or a global or external skill, whose file changed outside to bytes that are not UTF-8 text (`pending-not-utf8`): it is not written over, and no save runs until someone saves the file as text again; tell the user which file it is. Another is a file OpenKnowledge has no agreed version of: the edit is in the document but is not saved, no save runs on its own, and any further write to the document, the agent's own included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history. Do not write to that document again; tell the user its file changed outside OpenKnowledge. A new document with no file yet is not that case: its held save is `projection-held` like the others. A write whose own save found such a file and took it in instead returns `urn:ok:error:write-replaced` (409, `refused`, `nextStep: re-read`): the document now holds the file as it is on disk and the edit is in its history; re-read and re-apply the edit if it is still needed. A write whose save wrote no file returns `urn:ok:error:write-dropped` (409, `refused`): a global skill whose folder was deleted or moved, or a path that no longer resolves (`nextStep: none`); a name with no file of its own, such as `__template__/…` (`nextStep: retry`: write it by its file path); or a skill whose outside change was being taken in when the save ran (`nextStep: re-read`).-A write to a Mermaid, Excalidraw or plain-text document or to a global or external skill returns its ordinary success response whatever its save does; these writes never return `save-held`. The save compares the file the same way, and what happens shows only in the document, its history and the user's notice. A Mermaid, Excalidraw or plain-text file has no merge: when it changed outside OpenKnowledge, the version being written is kept and the outside version is saved to the document's history. A skill merges an outside change like a Markdown document, and when the merge is refused the version being written is kept and the outside version is saved the same way. When history cannot take a version, it is saved under `~/.ok/edit-backups/discarded/` instead. When neither can take it, or the file keeps changing, cannot be read, or changed to text that is not UTF-8, nothing is written: the save is held and retried, and only the user's notice says so. So after a write to one of these files, re-read it before editing it further, and if it is not what you wrote, look for the other version with `history`. A typed outcome for these writes is planned. Settings files, which the `config` tool reads, follow the same rules when they change outside OpenKnowledge: a valid outside version replaces the user's unsaved settings edits, which are saved first, as soon as OpenKnowledge sees it; an invalid one is only rejected until the next settings save, which saves it to history, or the backup folder, and then writes over it.+A write to a Mermaid, Excalidraw or plain-text document or to a global or external skill reports what its save did, like a Markdown write. A Mermaid, Excalidraw or plain-text file has no merge: when it changed outside OpenKnowledge, the version being written is kept, the outside version is saved to the document's history, and the result says `merged-first`. A skill merges an outside change like a Markdown document and answers `merged-first` or `both-kept`; when the merge is refused, the version being written is kept, the outside version is saved the same way, and the result says `merged-first`. When history cannot take a version, it is saved under `~/.ok/edit-backups/discarded/` instead. When neither can take it, or the file keeps changing or cannot be read, nothing is written and the write returns `save-held` as described above. Settings files, which the `config` tool reads, follow the same rules when they change outside OpenKnowledge: a valid outside version replaces the user's unsaved settings edits, which are saved first, as soon as OpenKnowledge sees it; an invalid one is only rejected until the next settings save, which saves it to history, or the backup folder, and then writes over it.A write to a document whose file was deleted, renamed or moved on disk returns `urn:ok:error:doc-removed` (409, `refused`): the edit reached collaborative state, but the disk write was refused. Retrying the same write does not help, and the `detail` says which case applies. If the file was deleted, the edit is in the document's history; tell the user (`nextStep: none`), and do not re-create the document on your own. If it was renamed or moved and the edit did not move with it, because it reached the document after the move or OpenKnowledge could not carry it, the `detail` names the new path: re-read the document there and re-apply your change (`nextStep: re-read`). If a different file now sits at the old path and has not been loaded into the document, only a reload of that document from disk clears the refusal, so tell the user instead of retrying.diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex 533ab1255..f36c29399 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -242,7 +242,7 @@ async function attachOkServer(permissions: currentSrv.acpPermissions,sessionManager,agentPresenceBroadcaster,- resolveEmbed: currentSrv.resolveEmbed,+ localApi: currentSrv.localApi,isExcludedPath: (rel) => currentSrv.contentFilter.isExcluded(rel),isIgnoredPath: (rel) => currentSrv.contentFilter.isPathIgnored(rel),getLoadedDocText: (docName) =>diff --git a/packages/app/tests/integration/acp-write-outcome.test.ts b/packages/app/tests/integration/acp-write-outcome.test.tsnew file mode 100644index 000000000..af8f2e13e--- /dev/null+++ b/packages/app/tests/integration/acp-write-outcome.test.ts@@ -0,0 +1,349 @@+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ AcpPermissionStore,+ AcpRegistry,+ AcpThreadManager,+ getLogger,+} from '@inkeep/open-knowledge-server';+import { afterEach, describe, expect, test } from 'vitest';+import { createWatcherDouble } from '../../../server/src/watcher-double.test-helper';+import {+ agentWriteMd,+ createTestClient,+ createTestServer,+ pollUntil,+ type TestServer,+} from './test-harness';++const SEED = '# Doc\n\nAlpha paragraph.\n\nBeta paragraph.\n';++const cleanups: Array<() => Promise<void> | void> = [];++afterEach(async () => {+ delete process.env.OK_TEST_COMPARE_READ_FAULT;+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();+});++interface AgentAnswer {+ result?: unknown;+ error?: { code: number; message: string; data?: Record<string, unknown> };+}++interface FileWrite {+ path: string;+ content: string;+}++function applied(outcome = 'applied', nextStep = 'none') {+ return { result: { _meta: { openknowledge: { outcome, saved: true, nextStep } } } };+}++async function boot(contentDir?: string): Promise<TestServer> {+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 600_000,+ ...(contentDir === undefined ? {} : { contentDir, keepContentDir: true }),+ });+ cleanups.push(() => server.cleanup());+ return server;+}++function liveText(server: TestServer, docName: string): string {+ return server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';+}++async function seedAndOpen(server: TestServer, docName: string) {+ const file = join(server.contentDir, `${docName}.md`);+ await agentWriteMd(server.port, SEED, { docName, position: 'replace' });+ await pollUntil(() => existsSync(file) && readFileSync(file, 'utf-8') === SEED, 10_000, 25);+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });+ cleanups.push(() => client.cleanup());+ await pollUntil(() => client.ytext.toString() === SEED, 10_000, 25, 'the client to load');+ return { client, file };+}++function writingAgent(localDir: string, writes: readonly FileWrite[], answerFile: string) {+ const agentPath = join(localDir, 'writer.mjs');+ writeFileSync(+ agentPath,+ `import { writeFileSync } from 'node:fs';+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+let nextId = 1000;+const pending = new Map();+const request = (method, params) =>+ new Promise((resolve) => {+ const id = nextId++;+ pending.set(id, resolve);+ write({ jsonrpc: '2.0', id, method, params: { sessionId: 'sess-1', ...params } });+ });+async function handlePrompt(msg) {+ const answers = [];+ for (const file of ${JSON.stringify(writes)}) {+ answers.push(await request('fs/write_text_file', file));+ }+ writeFileSync(${JSON.stringify(answerFile)}, JSON.stringify(answers));+ write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });+}+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ if (msg.method === undefined && msg.id !== undefined && pending.has(msg.id)) {+ const resolve = pending.get(msg.id);+ pending.delete(msg.id);+ resolve(msg.error ? { error: msg.error } : { result: msg.result });+ continue;+ }+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });+ if (msg.method === 'initialize') reply({ protocolVersion: 1, agentCapabilities: {} });+ else if (msg.method === 'session/new') reply({ sessionId: 'sess-1' });+ else if (msg.method === 'session/prompt') handlePrompt(msg);+ else if (msg.id !== undefined) reply({});+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id: 'writer', name: 'Writer', command: 'node', args: [agentPath] }]),+ );+}++async function writeThroughAcp(+ server: TestServer,+ writes: readonly FileWrite[],+ beforeClose: (threadId: string) => void = () => {},+): Promise<AgentAnswer[]> {+ const localDir = mkdtempSync(join(tmpdir(), 'acp-write-outcome-'));+ cleanups.push(() => rmSync(localDir, { recursive: true, force: true }));+ const answerFile = join(localDir, 'answers.json');+ writingAgent(localDir, writes, answerFile);+ const log = getLogger('acp-write-outcome-test');+ const manager = new AcpThreadManager({+ contentDir: server.contentDir,+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () => {+ throw new Error('offline test');+ }) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager: server.instance.sessionManager,+ localApi: server.instance.localApi,+ isExcludedPath: (rel) => server.instance.contentFilter.isExcluded(rel),+ isIgnoredPath: (rel) => server.instance.contentFilter.isPathIgnored(rel),+ log,+ resolveLoginShellPath: async () => null,+ });+ cleanups.push(() => manager.destroy());+ const info = await manager.createThread({ agent: { source: 'custom', id: 'writer' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await pollUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 25, 'ready');+ manager.sendPrompt(info.threadId, 'write the files');+ await pollUntil(() => existsSync(answerFile), 60_000, 25, 'the agent to record its answers');+ beforeClose(info.threadId);+ await manager.closeThread(info.threadId);+ return JSON.parse(readFileSync(answerFile, 'utf-8')) as AgentAnswer[];+}++describe('an in-app agent Markdown write answers with its outcome', () => {+ test('a saved write returns the outcome under _meta, and closing the thread ends its session', async () => {+ const server = await boot();+ const docName = `acp-applied-${randomUUID()}`;+ const file = join(server.contentDir, `${docName}.md`);+ let writer = '';+ let sessionWhileOpen = false;++ const [answer] = await writeThroughAcp(+ server,+ [{ path: file, content: '# Alpha\n\nAlpha paragraph.\n' }],+ (id) => {+ writer = `agent-acp-${id}`;+ sessionWhileOpen = server.instance.sessionManager.hasSession(docName, writer);+ },+ );++ expect(answer).toEqual(applied());+ expect(readFileSync(file, 'utf-8')).toBe('# Alpha\n\nAlpha paragraph.\n');+ expect(sessionWhileOpen).toBe(true);+ expect(server.instance.sessionManager.hasSession(docName, writer)).toBe(false);+ }, 90_000);++ test('a replace refused by a recent edit keeps code -32009 and names the outcome', async () => {+ const server = await boot();+ const docName = `acp-refused-${randomUUID()}`;+ const { client, file } = await seedAndOpen(server, docName);+ client.doc.transact(() => {+ client.ytext.insert(client.ytext.length, '\ntyped by a person\n');+ });+ await pollUntil(() => liveText(server, docName).includes('typed by a person'));++ const [answer] = await writeThroughAcp(server, [{ path: file, content: '# Replacement\n' }]);++ expect(answer?.error?.code).toBe(-32009);+ expect(answer?.error?.data).toMatchObject({+ type: 'urn:ok:error:concurrent-overwrite-refused',+ retryable: true,+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ });+ expect(readFileSync(file, 'utf-8')).not.toContain('Replacement');+ }, 90_000);++ test('a write whose save is held returns code -32010 with projection-held, not success', async () => {+ const server = await boot();+ const docName = `acp-held-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ process.env.OK_TEST_COMPARE_READ_FAULT = `${docName}:EBUSY:1000`;++ const [answer] = await writeThroughAcp(server, [+ { path: file, content: `${SEED}\nAgent line.\n` },+ ]);++ expect(answer?.error?.code).toBe(-32010);+ expect(answer?.error?.message).toContain('Do not repeat this write');+ expect(answer?.error?.data).toEqual({+ type: 'urn:ok:error:save-held',+ file: `${docName}.md`,+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ expect(readFileSync(file, 'utf-8')).toBe(SEED);+ }, 90_000);++ test('a whole-file write over unsaved edits and an outside change keeps all three and answers merged-first', async () => {+ const server = await boot();+ const docName = `acp-merge-${randomUUID()}`;+ const { client, file } = await seedAndOpen(server, docName);+ client.doc.transact(() => {+ const at = client.ytext.toString().indexOf('Alpha paragraph.');+ client.ytext.insert(at + 'Alpha paragraph.'.length, ' Typed here.');+ });+ await pollUntil(() => liveText(server, docName).includes('Typed here.'));+ await new Promise((resolve) => setTimeout(resolve, 2_100));+ writeFileSync(file, '# Doc\n\nAlpha paragraph.\n\nBeta paragraph. Changed outside.\n');++ const [answer] = await writeThroughAcp(server, [+ { path: file, content: `${liveText(server, docName)}\nAgent line.\n` },+ ]);++ expect(answer).toEqual(applied('merged-first', 're-read'));+ const saved = readFileSync(file, 'utf-8');+ expect(saved).toContain('Alpha paragraph. Typed here.');+ expect(saved).toContain('Beta paragraph. Changed outside.');+ expect(saved).toContain('Agent line.');+ expect(liveText(server, docName)).toBe(saved);+ }, 90_000);++ test('a document that already holds a control character can still be edited', async () => {+ const server = await boot();+ const docName = `acp-control-${randomUUID()}`;+ const file = join(server.contentDir, `${docName}.md`);+ const pasted = '# Log\n\n\u001b[31mred\u001b[0m output\n';+ writeFileSync(file, pasted);++ const [answer] = await writeThroughAcp(server, [+ { path: file, content: `${pasted}\nAgent line.\n` },+ ]);++ expect(answer).toEqual(applied());+ expect(readFileSync(file, 'utf-8')).toBe(`${pasted}\nAgent line.\n`);+ }, 90_000);+});++describe('an in-app agent write to a document under a dot folder', () => {+ test('writes and edits a project skill under .claude/skills', async () => {+ const contentDir = mkdtempSync(join(tmpdir(), 'acp-skill-content-'));+ cleanups.push(() => rmSync(contentDir, { recursive: true, force: true }));+ const skillDir = join(contentDir, '.claude', 'skills', 'acp-skill');+ mkdirSync(skillDir, { recursive: true });+ const file = join(skillDir, 'SKILL.md');+ const original = '---\nname: acp-skill\ndescription: Use when testing.\n---\n\n# Skill\n';+ writeFileSync(file, original);+ const server = await boot(contentDir);++ const written = `${original}\nFirst step.\n`;+ const edited = `${original}\nFirst step, edited.\n`;+ const answers = await writeThroughAcp(server, [+ { path: file, content: written },+ { path: file, content: edited },+ ]);++ expect(answers).toEqual([applied(), applied()]);+ expect(readFileSync(file, 'utf-8')).toBe(edited);+ }, 90_000);++ test('writes and edits a folder template', async () => {+ const server = await boot();+ const file = join(server.contentDir, 'meetings', '.ok', 'templates', 'weekly.md');++ const answers = await writeThroughAcp(server, [+ { path: file, content: '# Weekly\n\nAgenda.\n' },+ { path: file, content: '# Weekly\n\nAgenda and notes.\n' },+ ]);++ expect(answers).toEqual([applied(), applied()]);+ expect(readFileSync(file, 'utf-8')).toBe('# Weekly\n\nAgenda and notes.\n');+ }, 90_000);+});++describe('an in-app agent write that is not Markdown', () => {+ test('saves a Mermaid file through its document, and is merged first after an outside change', async () => {+ const server = await boot();+ const file = join(server.contentDir, `flow-${randomUUID()}.mmd`);+ const [first] = await writeThroughAcp(server, [{ path: file, content: 'graph TD\n A-->B\n' }]);+ expect(first).toEqual(applied());+ writeFileSync(file, 'graph TD\n A-->Outside\n');+ await new Promise((resolve) => setTimeout(resolve, 2_100));++ const [second] = await writeThroughAcp(server, [+ { path: file, content: 'graph TD\n A-->Agent\n' },+ ]);++ expect(second).toEqual(applied('merged-first', 're-read'));+ expect(readFileSync(file, 'utf-8')).toBe('graph TD\n A-->Agent\n');+ }, 90_000);++ test('saves an Excalidraw file and a text file through their documents', async () => {+ const server = await boot();+ const board = join(server.contentDir, `board-${randomUUID()}.excalidraw`);+ const notes = join(server.contentDir, `notes-${randomUUID()}.txt`);+ const boardJson = '{"type":"excalidraw","version":2,"elements":[]}\n';++ const answers = await writeThroughAcp(server, [+ { path: board, content: boardJson },+ { path: notes, content: 'plain notes\n' },+ ]);++ expect(answers).toEqual([applied(), applied()]);+ expect(readFileSync(board, 'utf-8')).toBe(boardJson);+ expect(readFileSync(notes, 'utf-8')).toBe('plain notes\n');+ }, 90_000);++ test('writes a file that is not a document as is, with an empty result', async () => {+ const server = await boot();+ const file = join(server.contentDir, 'assets', `logo-${randomUUID()}.png`);++ const [answer] = await writeThroughAcp(server, [{ path: file, content: 'not really a png' }]);++ expect(answer).toEqual({ result: {} });+ expect(readFileSync(file, 'utf-8')).toBe('not really a png');+ }, 90_000);+});diff --git a/packages/app/tests/integration/agent-write-outcome.test.ts b/packages/app/tests/integration/agent-write-outcome.test.tsindex 25d604728..33c58105e 100644--- a/packages/app/tests/integration/agent-write-outcome.test.ts+++ b/packages/app/tests/integration/agent-write-outcome.test.ts@@ -1,5 +1,15 @@import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';import { AGENT_WRITE_NEXT_STEPS, AGENT_WRITE_OUTCOMES } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test, vi } from 'vitest';@@ -212,31 +222,238 @@ describe('what each refusal and each kind of document reports', () => {});}, 60_000);- test('a write to a Mermaid document, and its undo, carry no outcome until the save reports back', async () => {+ test('a Mermaid write is applied, then merged first when its file changed outside, and its undo reports too', async () => {const server = await boot();const docName = `diagrams/outcome-${randomUUID()}.mmd`;const file = join(server.contentDir, docName);mkdirSync(join(server.contentDir, 'diagrams'), { recursive: true });writeFileSync(file, 'graph TD\n A-->B\n');- const answer = await post(server, '/api/agent-write-md', {+ const write = (markdown: string) =>+ post(server, '/api/agent-write-md', {+ docName,+ markdown,+ position: 'replace',+ agentId: 'outcome-agent',+ });++ const first = await write('graph TD\n A-->C\n');+ expect(first.status).toBe(200);+ expect(first.body).toMatchObject({ outcome: 'applied', saved: true, nextStep: 'none' });+ writeFileSync(file, 'graph TD\n A-->Outside\n');++ const second = await write('graph TD\n A-->Agent\n');+ expect(second.status).toBe(200);+ expect(second.body).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ expectInClosedSets(second);+ expect(disk(file)).toBe('graph TD\n A-->Agent\n');++ const undo = await post(server, '/api/agent-undo', {+ docName,+ connectionId: 'agent-outcome-agent',+ agentId: 'outcome-agent',+ });+ expect(undo.status).toBe(200);+ expectInClosedSets(undo);+ }, 60_000);++ test('a Mermaid write over a file that no longer holds text is not saved, and says to tell the user', async () => {+ const server = await boot();+ const docName = `diagrams/outcome-${randomUUID()}.mmd`;+ const file = join(server.contentDir, docName);+ mkdirSync(join(server.contentDir, 'diagrams'), { recursive: true });+ writeFileSync(file, 'graph TD\n A-->B\n');+ const write = (markdown: string) =>+ post(server, '/api/agent-write-md', {+ docName,+ markdown,+ position: 'replace',+ agentId: 'outcome-agent',+ });+ expect((await write('graph TD\n A-->C\n')).status).toBe(200);+ const notText = Buffer.from([0x67, 0x72, 0xff, 0xfe, 0x0a]);+ writeFileSync(file, notText);++ const answer = await write('graph TD\n A-->Agent\n');+ expect(answer.status).toBe(503);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:save-held',+ reason: 'pending-not-utf8',+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+ });+ expect(String(answer.body.detail)).toContain(+ 'no save runs until someone saves the file as text again. Tell the user which file it is.',+ );+ expect(answer.body).not.toHaveProperty('retryWhen');+ expectInClosedSets(answer);+ expect(readFileSync(file).equals(notText)).toBe(true);+ expect(liveText(server, docName)).toBe('graph TD\n A-->Agent\n');+ }, 60_000);++ test.skipIf(process.getuid?.() === 0)(+ 'a Mermaid write whose save runs at once reports that save: merged first, then held',+ async () => {+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 0,+ });+ cleanups.push(() => server.cleanup());+ const docName = `diagrams/outcome-${randomUUID()}.mmd`;+ const file = join(server.contentDir, docName);+ mkdirSync(join(server.contentDir, 'diagrams'), { recursive: true });+ writeFileSync(file, 'graph TD\n A-->B\n');+ const write = (markdown: string) =>+ post(server, '/api/agent-write-md', {+ docName,+ markdown,+ position: 'replace',+ agentId: 'outcome-agent',+ });+ expect((await write('graph TD\n A-->C\n')).body).toMatchObject({ outcome: 'applied' });++ writeFileSync(file, 'graph TD\n A-->Outside\n');+ const merged = await write('graph TD\n A-->Agent\n');+ expect(merged.status).toBe(200);+ expect(merged.body).toMatchObject({ outcome: 'merged-first', saved: true });++ chmodSync(file, 0o000);+ cleanups.push(() => chmodSync(file, 0o644));+ const held = await write('graph TD\n A-->Held\n');+ expect(held.status).toBe(503);+ expect(held.body).toMatchObject({+ type: 'urn:ok:error:save-held',+ reason: 'pending-unreadable',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ },+ 60_000,+ );++ test('a Mermaid undo whose save runs at once reports that save, never applied', async () => {+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 0,+ });+ cleanups.push(() => server.cleanup());+ const docName = `diagrams/outcome-${randomUUID()}.mmd`;+ const file = join(server.contentDir, docName);+ mkdirSync(join(server.contentDir, 'diagrams'), { recursive: true });+ writeFileSync(file, 'graph TD\n A-->B\n');+ const written = await post(server, '/api/agent-write-md', {docName,markdown: 'graph TD\n A-->C\n',position: 'replace',agentId: 'outcome-agent',});- expect(answer.status).toBe(200);- expect(answer.body).not.toHaveProperty('outcome');- expect(answer.body).not.toHaveProperty('saved');- expect(answer.body).not.toHaveProperty('nextStep');+ expect(written.body).toMatchObject({ outcome: 'applied' });+ const notText = Buffer.from([0x67, 0x72, 0xff, 0xfe, 0x0a]);+ writeFileSync(file, notText);const undo = await post(server, '/api/agent-undo', {docName,connectionId: 'agent-outcome-agent',agentId: 'outcome-agent',});- expect(undo.status).toBe(200);- expect(undo.body).not.toHaveProperty('outcome');- expect(undo.body).not.toHaveProperty('saved');+ expect(undo.status).toBe(503);+ expect(undo.body).toMatchObject({+ type: 'urn:ok:error:save-held',+ reason: 'pending-not-utf8',+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+ });+ expect(undo.body).not.toHaveProperty('retryWhen');+ expect(readFileSync(file).equals(notText)).toBe(true);+ }, 60_000);++ test('a write under a template name that has no file is refused, with the file path to use instead', async () => {+ const server = await boot();+ const answer = await post(server, '/api/agent-write-md', {+ docName: `__template__/notes/daily-${randomUUID()}`,+ markdown: '# Daily\n',+ position: 'replace',+ agentId: 'outcome-agent',+ });+ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:write-dropped',+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ });+ expect(String(answer.body.detail)).toContain('Write the skill or template by its file path');+ }, 60_000);++ test('a global skill write is merged first, or keeps both, when its file changed outside', async () => {+ const home = mkdtempSync(join(tmpdir(), 'outcome-skill-home-'));+ cleanups.push(() => rmSync(home, { recursive: true, force: true }));+ mkdirSync(join(home, '.agents', 'skills'), { recursive: true });+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 600_000,+ configHomedirOverride: home,+ });+ cleanups.push(() => server.cleanup());+ const name = `outcome-skill-${randomUUID().slice(0, 8)}`;+ const file = join(home, '.agents', 'skills', name, 'SKILL.md');+ const put = async (body: string): Promise<Answer> => {+ const response = await fetch(`${server.baseUrl}/api/skill`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ scope: 'global',+ name,+ body,+ frontmatter: { name, description: 'Use when checking write outcomes.' },+ agentId: 'outcome-agent',+ }),+ });+ return { status: response.status, body: (await response.json()) as Record<string, unknown> };+ };+ const outside = (find: string, replace: string) =>+ writeFileSync(file, readFileSync(file, 'utf-8').replace(find, replace));++ const created = await put('## Alpha\n\nAlpha paragraph.\n\n## Beta\n\nBeta paragraph.\n');+ expect(created.body).toMatchObject({ created: true, outcome: 'applied', saved: true });+ const edited = await put(+ '## Alpha\n\nAlpha paragraph.\n\n## Beta\n\nBeta paragraph.\n\n## Gamma\n\nGamma paragraph.\n',+ );+ expect(edited.body).toMatchObject({ created: false, outcome: 'applied', saved: true });++ outside('Beta paragraph.', 'Beta paragraph, edited outside.');+ const merged = await put(+ '## Alpha\n\nAlpha paragraph, edited by the agent.\n\n## Beta\n\nBeta paragraph.\n\n## Gamma\n\nGamma paragraph.\n',+ );+ expect(merged.status).toBe(200);+ expect(merged.body).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ expect(disk(file)).toContain('Alpha paragraph, edited by the agent.');+ expect(disk(file)).toContain('Beta paragraph, edited outside.');++ outside('Gamma paragraph.', 'Gamma paragraph, edited outside.');+ const bothKept = await put(+ '## Alpha\n\nAlpha paragraph, edited by the agent.\n\n## Beta\n\nBeta paragraph, edited outside.\n\n## Gamma\n\nGamma paragraph, edited by the agent.\n',+ );+ expect(bothKept.status).toBe(200);+ expect(bothKept.body).toMatchObject({ outcome: 'both-kept', saved: true, nextStep: 're-read' });+ expect(disk(file)).toContain('Gamma paragraph, edited by the agent.');+ expect(disk(file)).toContain('Gamma paragraph, edited outside.');}, 60_000);});diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.tsindex 02a45b39d..97f359b6d 100644--- a/packages/core/src/handoff/urn-ipc-registry.ts+++ b/packages/core/src/handoff/urn-ipc-registry.ts@@ -67,6 +67,7 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>(['urn:ok:error:server-stopped','urn:ok:error:both-kept','urn:ok:error:write-replaced',+ 'urn:ok:error:write-dropped','urn:ok:error:doc-in-conflict','urn:ok:error:no-conflict-tracked','urn:ok:error:unresolved-conflict-markers',diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 9c625647d..aed3c59df 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -91,6 +91,7 @@ export const ProblemTypeSchema = z.enum(['urn:ok:error:server-stopped','urn:ok:error:both-kept','urn:ok:error:write-replaced',+ 'urn:ok:error:write-dropped','urn:ok:error:doc-not-found','urn:ok:error:doc-already-exists','urn:ok:error:doc-not-open',diff --git a/packages/core/src/schemas/api/agent-write-outcome.test.ts b/packages/core/src/schemas/api/agent-write-outcome.test.tsindex 81e9dce4c..11d1da26f 100644--- a/packages/core/src/schemas/api/agent-write-outcome.test.ts+++ b/packages/core/src/schemas/api/agent-write-outcome.test.ts@@ -65,9 +65,10 @@ describe('the agent write outcome contract', () => {).toBe(true);});- test('the both-kept and write-replaced problem types are registered', () => {+ test('the both-kept, write-replaced and write-dropped problem types are registered', () => {expect(ProblemTypeSchema.safeParse('urn:ok:error:both-kept').success).toBe(true);expect(ProblemTypeSchema.safeParse('urn:ok:error:write-replaced').success).toBe(true);+ expect(ProblemTypeSchema.safeParse('urn:ok:error:write-dropped').success).toBe(true);});});diff --git a/packages/server/assets/skills/project/references/conflict-resolution.md b/packages/server/assets/skills/project/references/conflict-resolution.mdindex e07ed5270..8f2837b96 100644--- a/packages/server/assets/skills/project/references/conflict-resolution.md+++ b/packages/server/assets/skills/project/references/conflict-resolution.md@@ -10,7 +10,7 @@ A document, template or skill write through `write` or `edit`, a document `resto| `refused` | Not saved. OpenKnowledge saves it only after someone acts: you, as `nextStep` says, or the user. | `false` | Follow `nextStep`: `retry` means send it again, corrected the way the detail says (a fixed path, quoted YAML, a different name) or after the wait it names; `re-read` means re-read, then re-apply only what is missing; `none` means nothing you send changes it, so tell the user (below). || `projection-held` | Your write is in the doc but not yet in its file; OpenKnowledge saves it on its own. On OpenKnowledge Cloud the same outcome means the doc's file projection is held. | `false` | Never repeat the write. Re-read before the next edit. |-A `both-kept` or `projection-held` result comes back as an error result because it is not plain success, but its text starts by saying the write landed: do not repeat it. A batch reports these per entry in `documents[]`, and a skill write per file in `skill.files[]`. If `outcome` holds a value you do not know, treat it as `merged-first` when `saved` is true and `refused` otherwise, and re-read; treat an unknown `nextStep` as `re-read`. If there is no `outcome`, the server predates the fields, or the doc is a Mermaid, Excalidraw, text, settings or global skill file whose save does not report back yet: read the result text. `retryWhen` and a warning's own `nextStep` are older fields; ignore them.+A `both-kept` or `projection-held` result comes back as an error result because it is not plain success, but its text starts by saying the write landed: do not repeat it. A batch reports these per entry in `documents[]`, and a skill write per file in `skill.files[]`. If `outcome` holds a value you do not know, treat it as `merged-first` when `saved` is true and `refused` otherwise, and re-read; treat an unknown `nextStep` as `re-read`. If there is no `outcome`, the server predates the fields: read the result text. `retryWhen` and a warning's own `nextStep` are older fields; ignore them.## What each result asks of you@@ -33,6 +33,7 @@ The fields come from one table on the server, and this one repeats it: for every| `stale-external-write` (409) | `refused` | `false` | `none` | Tell the user which file it is. Your edit is kept in the document and the recovery snapshot; do not repeat it. || `save-held` (503) with `pending-conflict` | `refused` | `false` | `none` | Tell the user which file it is. The save runs once they deal with the file in the app; do not repeat the write. || `save-held` (503) on a file with no agreed version | `refused` | `false` | `none` | Tell the user its file changed outside OpenKnowledge, and do not write to that document again: any write replaces it with the file on disk and moves your edit to its history. |+| `save-held` (503) with `pending-not-utf8` | `refused` | `false` | `none` | Tell the user which file it is: it now holds bytes that are not text, so it is not written over, and no save runs until someone saves it as text again. Do not repeat the write. || `save-held` (503) with any other `reason` | `projection-held` | `false` | `re-read` | Do not repeat the write. Re-read before the next edit; with `pending-rename`, re-read at the new name the detail gives. || `doc-moved` (409) | `projection-held` | `false` | `re-read` | Do not repeat the edit. Re-read the document at the new name the detail gives. || `branch-switched` (409) | `projection-held` | `false` | `re-read` | Do not repeat the edit. Re-read the document before the next edit. |@@ -43,6 +44,9 @@ The fields come from one table on the server, and this one repeats it: for every| `path-escape` (400) | `refused` | `false` | `none` | Tell the user the document's path could not be resolved. || `store-refused` (503) | `refused` | `false` | `re-read` | Do not repeat it now. Once the user has fixed the filesystem fault, re-read and re-apply only what is missing. || `write-replaced` (409) | `refused` | `false` | `re-read` | Re-read: the document now holds the file as it is on disk, and your edit is in its history. Re-apply it if it is still needed. |+| `write-dropped` (409) for a name with no file of its own | `refused` | `false` | `retry` | Send the write again by the skill's or template's file path. |+| `write-dropped` (409) while an outside change was being taken in | `refused` | `false` | `re-read` | Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing. |+| `write-dropped` (409) for a skill folder that is gone or a path that does not resolve | `refused` | `false` | `none` | Tell the user which skill it is: its folder was deleted or moved, or its path no longer resolves. || `storage-full` (507), `storage-readonly` or `storage-error` (500) | `refused` | `false` | `re-read` | Once the user has fixed the storage, re-read and re-apply only what is missing. |If you come back to that file later, re-read it first. For a refusal before anything was written (`doc-in-conflict`), write again only if the write is still needed; otherwise compare the doc with the intended result and make only the edit that is still missing.diff --git a/packages/server/src/acp/document-write.ts b/packages/server/src/acp/document-write.tsnew file mode 100644index 000000000..e737a0b4a--- /dev/null+++ b/packages/server/src/acp/document-write.ts@@ -0,0 +1,99 @@+import { RequestError, type WriteTextFileResponse } from '@agentclientprotocol/sdk';+import {+ type AgentWriteOutcomeFields,+ normalizeAgentWriteOutcome,+} from '@inkeep/open-knowledge-core';+import { asRecord } from '@inkeep/open-knowledge-core/acp/tool-call-input';+import {+ CONCURRENT_OVERWRITE_REFUSED_DETAIL,+ CONCURRENT_OVERWRITE_REFUSED_TYPE,+ CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,+} from '../concurrent-overwrite-refused-error.ts';+import type { LocalApiDispatch } from '../http/local-api-dispatch.ts';++export const ACP_DOCUMENT_WRITE_PATH = '/internal/acp/document-write';++const CONCURRENT_OVERWRITE_REFUSED_CODE = -32009;++const WRITE_NOT_PLAIN_SUCCESS_CODE = -32010;++export interface AcpDocumentWrite {+ readonly docName: string;+ readonly file: string;+ readonly markdown: string;+ readonly agentId: string;+ readonly agentName: string;+ readonly clientName: string;+}++export async function writeDocumentThroughRoute(+ localApi: LocalApiDispatch,+ write: AcpDocumentWrite,+): Promise<WriteTextFileResponse> {+ const answer = await localApi('POST', ACP_DOCUMENT_WRITE_PATH, {+ body: JSON.stringify({+ docName: write.docName,+ file: write.file,+ markdown: write.markdown,+ ...markdownExtensionOf(write.file),+ agentId: write.agentId,+ agentName: write.agentName,+ clientName: write.clientName,+ }),+ contentType: 'application/json',+ });+ if (answer === null) {+ throw new Error(`${ACP_DOCUMENT_WRITE_PATH} is not dispatchable in process`);+ }+ return acpWriteResult(answer.status, asRecord(JSON.parse(answer.bodyText)), write.file);+}++function markdownExtensionOf(file: string): { extension?: '.md' | '.mdx' } {+ if (file.endsWith('.mdx')) return { extension: '.mdx' };+ if (file.endsWith('.md')) return { extension: '.md' };+ return {};+}++function outcomeFieldsOf(+ body: Record<string, unknown>,+): (Pick<AgentWriteOutcomeFields, 'outcome'> & Partial<AgentWriteOutcomeFields>) | undefined {+ const normalized = normalizeAgentWriteOutcome(body);+ if (normalized === undefined) return undefined;+ return {+ outcome: normalized.outcome,+ ...(normalized.saved === undefined ? {} : { saved: normalized.saved }),+ ...(normalized.nextStep === undefined ? {} : { nextStep: normalized.nextStep }),+ };+}++function problemMessage(status: number, body: Record<string, unknown>): string {+ const title = typeof body.title === 'string' ? body.title : `The write answered ${status}.`;+ return typeof body.detail === 'string' ? `${title} ${body.detail}` : title;+}++function acpWriteResult(+ status: number,+ body: Record<string, unknown>,+ file: string,+): WriteTextFileResponse {+ const fields = outcomeFieldsOf(body);+ const plainSuccess =+ status >= 200 &&+ status < 300 &&+ (fields === undefined || fields.outcome === 'applied' || fields.outcome === 'merged-first');+ if (plainSuccess) return fields === undefined ? {} : { _meta: { openknowledge: { ...fields } } };+ if (body.type === CONCURRENT_OVERWRITE_REFUSED_TYPE) {+ throw new RequestError(CONCURRENT_OVERWRITE_REFUSED_CODE, CONCURRENT_OVERWRITE_REFUSED_DETAIL, {+ type: CONCURRENT_OVERWRITE_REFUSED_TYPE,+ file,+ retryable: true,+ retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,+ ...fields,+ });+ }+ throw new RequestError(WRITE_NOT_PLAIN_SUCCESS_CODE, problemMessage(status, body), {+ type: typeof body.type === 'string' ? body.type : 'urn:ok:error:internal-server-error',+ file,+ ...fields,+ });+}diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex 607109e33..a3eac2ab5 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -32,6 +32,7 @@ import codexFixture from '../../../../test-support/fixtures/codex-legacy-warningimport type { AgentPresenceBroadcaster } from '../agent-presence.ts';import type { AgentSessionManager } from '../agent-sessions.ts';import { resolveBundledSkillDir } from '../build-skill-zip.ts';+import type { LocalApiDispatch } from '../http/local-api-dispatch.ts';import { getLogger, type PinoLogger } from '../logger.ts';import { RUNTIME_VERSION } from '../version-constants.ts';import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';@@ -60,6 +61,7 @@ import {AcpThreadManager,type AcpThreadManagerOptions,buildEnvironmentNote,+ confineToContentDir,MAX_QUEUED_PROMPTS,} from './thread-manager.ts';@@ -105,11 +107,13 @@ function makeManager(unwatchedTurnKillMs?: number;turnStallMs?: number;isIgnoredPath?: (relPosix: string) => boolean;+ isExcludedPath?: (relPosix: string) => boolean;registry?: AcpRegistry;runtimeInstall?: AcpThreadManagerOptions['runtimeInstall'];resolveLoginShellPath?: () => Promise<string | null>;agentPresenceBroadcaster?: AgentPresenceBroadcaster;sessionManager?: AgentSessionManager;+ localApi?: LocalApiDispatch;log?: PinoLogger;projectSkillSourceDir?: string | null;autoApproveOkTools?: () => boolean;@@ -1845,14 +1849,16 @@ describe('AcpThreadManager persistence + resume', () => {});describe('handleFsWrite exclusion gate', () => {- test('non-markdown writes into ignored namespaces are rejected; plain asset writes land', async () => {+ test('writes into ignored namespaces are rejected; a file that is not a document is written as is', async () => {const contentDir = tmp();const localDir = tmp();+ const ignored = (rel: string) => rel.startsWith('.ok/') || rel.startsWith('.git/');const manager = makeManager(contentDir, localDir, {- isIgnoredPath: (rel) => rel.startsWith('.ok/') || rel.startsWith('.git/'),+ isIgnoredPath: ignored,+ isExcludedPath: ignored,});const m = manager as unknown as {- handleFsWrite: (record: unknown, path: string, content: string) => Promise<void>;+ handleFsWrite: (record: unknown, path: string, content: string) => Promise<unknown>;};const record = { info: { lastActivityAt: 0 } };@@ -1863,57 +1869,182 @@ describe('handleFsWrite exclusion gate', () => {m.handleFsWrite(record, join(contentDir, '.git', 'hooks', 'pre-commit'), '#!/bin/sh'),).rejects.toThrow(/excluded from the project content scope/);- await m.handleFsWrite(record, join(contentDir, 'assets', 'note.txt'), 'hi');- expect(readFileSync(join(contentDir, 'assets', 'note.txt'), 'utf8')).toBe('hi');+ const answer = await m.handleFsWrite(record, join(contentDir, 'assets', 'logo.png'), 'png');+ expect(answer).toEqual({});+ expect(readFileSync(join(contentDir, 'assets', 'logo.png'), 'utf8')).toBe('png');});});-describe('handleFsWrite concurrent replace guard', () => {- test('returns one small ACP error and keeps the peer content', async () => {+describe('confineToContentDir', () => {+ test('names a document for Markdown, Mermaid, Excalidraw and text files, and none for other files', async () => {const contentDir = tmp();- const docs = new Map<string, Y.Doc>();- const sessionManager = {- getSession: async (docName: string, agentId: string) => {- let document = docs.get(docName);- if (document === undefined) {- document = new Y.Doc();- Object.assign(document, { name: docName });- docs.set(docName, document);- }- return { dc: { document }, origin: { agentId }, agentId, docName };- },- closeAllForAgent: async () => {},- } as unknown as AgentSessionManager;- const manager = makeManager(contentDir, tmp(), { sessionManager });- const fsWrite = (+ const docNameOf = async (rel: string) =>+ (await confineToContentDir(contentDir, join(contentDir, rel), () => false)).docName;++ expect(await docNameOf('notes/a.md')).toBe('notes/a');+ expect(await docNameOf('notes/b.mdx')).toBe('notes/b');+ expect(await docNameOf('diagrams/flow.mmd')).toBe('diagrams/flow.mmd');+ expect(await docNameOf('boards/plan.excalidraw')).toBe('boards/plan.excalidraw');+ expect(await docNameOf('notes/todo.txt')).toBe('notes/todo.txt');+ expect(await docNameOf('assets/logo.png')).toBeNull();+ });++ test('names no document for a path the content filter excludes', async () => {+ const contentDir = tmp();+ const confined = await confineToContentDir(+ contentDir,+ join(contentDir, '.github', 'notes.md'),+ (rel) => rel.startsWith('.github/'),+ );+ expect(confined.docName).toBeNull();+ });+});++describe('handleFsWrite through the agent write route', () => {+ interface RouteCall {+ method: string;+ path: string;+ body: Record<string, unknown>;+ }++ function routeAnswering(+ status: number,+ body: Record<string, unknown>,+ calls: RouteCall[] = [],+ ): LocalApiDispatch {+ return async (method, path, options) => {+ calls.push({ method, path, body: JSON.parse(String(options?.body)) });+ return { status, bodyText: JSON.stringify(body) };+ };+ }++ function fsWriteOf(+ manager: AcpThreadManager,+ ): (record: unknown, path: string, content: string) => Promise<unknown> {+ return (manager as unknown as {- handleFsWrite: (record: unknown, path: string, content: string) => Promise<void>;+ handleFsWrite: (record: unknown, path: string, content: string) => Promise<unknown>;}).handleFsWrite.bind(manager);- const path = join(contentDir, 'notes', 'shared.md');- const record = (agentSessionId: string) => ({- agentSessionId,- info: { lastActivityAt: 0, agent: { id: 'codex', name: agentSessionId } },- });+ }++ const record = {+ agentSessionId: 'acp-thread-1',+ info: { lastActivityAt: 0, agent: { id: 'codex-acp', name: 'Codex' } },+ };- await fsWrite(record('agent-a'), path, '# From A\n');- const before = docs.get('notes/shared')?.getText('source').toString();- const error = await fsWrite(record('agent-b'), path, '# From B\n').then(- () => undefined,+ async function refusal(+ pending: Promise<unknown>,+ ): Promise<{ code?: number; message?: string; data?: unknown }> {+ return pending.then(+ () => ({}),(reason: unknown) => reason as { code?: number; message?: string; data?: unknown },);+ }++ test('a saved write returns its outcome under _meta, sent as a whole-document replace', async () => {+ const contentDir = tmp();+ const calls: RouteCall[] = [];+ const localApi = routeAnswering(+ 200,+ { outcome: 'merged-first', saved: true, nextStep: 're-read' },+ calls,+ );+ const manager = makeManager(contentDir, tmp(), { localApi });++ const result = await fsWriteOf(manager)(+ record,+ join(contentDir, 'notes', 'shared.mdx'),+ '# Shared\n',+ );++ expect(result).toEqual({+ _meta: { openknowledge: { outcome: 'merged-first', saved: true, nextStep: 're-read' } },+ });+ expect(calls).toEqual([+ {+ method: 'POST',+ path: '/internal/acp/document-write',+ body: {+ docName: 'notes/shared',+ file: 'notes/shared.mdx',+ markdown: '# Shared\n',+ extension: '.mdx',+ agentId: 'acp-thread-1',+ agentName: 'Codex',+ clientName: 'codex-acp',+ },+ },+ ]);+ });++ test('a concurrent replace keeps code -32009 and its data, with the outcome added', async () => {+ const contentDir = tmp();+ const localApi = routeAnswering(409, {+ type: 'urn:ok:error:concurrent-overwrite-refused',+ title: 'Concurrent overwrite refused.',+ file: 'notes/shared.md',+ retryAfterSeconds: 3,+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ });+ const manager = makeManager(contentDir, tmp(), { localApi });++ const error = await refusal(+ fsWriteOf(manager)(record, join(contentDir, 'notes', 'shared.md'), '# From B\n'),+ );- expect(error?.code).toBe(-32009);- expect(error?.message).toBe(+ expect(error.code).toBe(-32009);+ expect(error.message).toBe('Another writer changed this document recently. Wait a few seconds and retry.',);- expect(error?.data).toEqual({+ expect(error.data).toEqual({type: 'urn:ok:error:concurrent-overwrite-refused',file: 'notes/shared.md',retryable: true,retryAfterSeconds: 3,+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',});- expect(docs.get('notes/shared')?.getText('source').toString()).toBe(before);+ });++ test.each([+ [409, 'urn:ok:error:both-kept', 'both-kept', true, 're-read'],+ [503, 'urn:ok:error:save-held', 'projection-held', false, 're-read'],+ [409, 'urn:ok:error:doc-in-conflict', 'refused', false, 'none'],+ ] as const)(+ 'a %i %s returns code -32010 naming the outcome',+ async (status, type, outcome, saved, nextStep) => {+ const contentDir = tmp();+ const localApi = routeAnswering(status, {+ type,+ title: 'Edit title.',+ detail: 'What happened and what to do.',+ outcome,+ saved,+ nextStep,+ });+ const manager = makeManager(contentDir, tmp(), { localApi });++ const error = await refusal(+ fsWriteOf(manager)(record, join(contentDir, 'notes', 'shared.md'), '# Shared\n'),+ );++ expect(error.code).toBe(-32010);+ expect(error.message).toBe('Edit title. What happened and what to do.');+ expect(error.data).toEqual({ type, file: 'notes/shared.md', outcome, saved, nextStep });+ },+ );++ test('a document write with no route to send it to fails instead of answering success', async () => {+ const contentDir = tmp();+ const manager = makeManager(contentDir, tmp());++ await expect(+ fsWriteOf(manager)(record, join(contentDir, 'notes', 'shared.md'), '# Shared\n'),+ ).rejects.toThrow(/document writes are not available/);});});@@ -2719,7 +2850,9 @@ describe('AcpThreadManager terminals + permission effects', () => {const contentDir = tmp();const localDir = tmp();writePlantingAgentEntry(localDir);- const manager = makeManager(contentDir, localDir);+ const manager = makeManager(contentDir, localDir, {+ isExcludedPath: (rel) => !/\.mdx?$/.test(rel),+ });const info = await manager.createThread({ agent: { source: 'custom', id: 'planting-agent' } });const events: Collected = [];await manager.subscribe(info.threadId, 0, collect(events));@@ -6109,6 +6242,10 @@ process.stdin.on('data', (chunk) => {const manager = makeManager(contentDir, localDir, {agentPresenceBroadcaster: recordingBroadcaster(published),sessionManager: stubSessionManager(new Map()),+ localApi: async () => ({+ status: 200,+ bodyText: JSON.stringify({ outcome: 'applied', saved: true, nextStep: 'none' }),+ }),});const info = await manager.createThread({ agent: { source: 'custom', id: 'codex-acp' } });diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex ca6c36070..a43c76aba 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -21,7 +21,6 @@ import {type PermissionOption,PROTOCOL_VERSION,type PromptCapabilities,- RequestError,type RequestPermissionResponse,type SessionConfigOption,type SessionNotification,@@ -30,11 +29,11 @@ import {type SetSessionConfigOptionResponse,type StopReason,type ToolCallUpdate,+ type WriteTextFileResponse,} from '@agentclientprotocol/sdk';import {AGENT_ICON_COLORS,agentIdForAcpAgent,- changedBlockRange,colorFromSeed,currentMcpServerName,type EditorId,@@ -62,26 +61,21 @@ import type {} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { THREAD_REOPEN_OP_TIMEOUT_MS } from '@inkeep/open-knowledge-core/acp/thread-protocol';import { asRecord } from '@inkeep/open-knowledge-core/acp/tool-call-input';-import { sessionWriterId, toBroadcasterKey } from '../agent-id.ts';+import { toBroadcasterKey } from '../agent-id.ts';import type { AgentPresenceBroadcaster } from '../agent-presence.ts';import { observeReadiness } from '../agent-registry-gate.ts';-import {- type AgentSessionManager,- agentWriteLossDetect,- applyAgentMarkdownWrite,- snapshotBlocks,-} from '../agent-sessions.ts';+import type { AgentSessionManager } from '../agent-sessions.ts';import { resolveBundledSkillDir } from '../build-skill-zip.ts';-import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import {- CONCURRENT_OVERWRITE_REFUSED_DETAIL,- CONCURRENT_OVERWRITE_REFUSED_TYPE,- CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,- ConcurrentOverwriteRefusedError,- logConcurrentOverwriteRefusal,-} from '../concurrent-overwrite-refused-error.ts';+ isConfigDoc,+ isEditableTextDoc,+ isExcalidrawDoc,+ isMermaidDoc,+ isSystemDoc,+} from '../cc1-broadcast.ts';import { tracedRm } from '../fs-traced.ts';import { resolveOnPath } from '../git-preflight.ts';+import type { LocalApiDispatch } from '../http/local-api-dispatch.ts';import type { PinoLogger } from '../logger.ts';import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';import { RUNTIME_VERSION } from '../version-constants.ts';@@ -108,6 +102,7 @@ import {createDiagnosticStderrCapture,redactDiagnostic,} from './diagnostics.ts';+import { writeDocumentThroughRoute } from './document-write.ts';import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';import { exitFailureDetail } from './exit-diagnosis.ts';import {@@ -217,7 +212,6 @@ const SIGN_IN_OUTPUT_LINES = 6;const RESUME_REPLAY_QUIESCENCE_MS = 300;const RESUME_REPLAY_MAX_WAIT_MS = 3_000;const AUTH_REQUIRED_CODE = -32000;-const CONCURRENT_OVERWRITE_REFUSED_CODE = -32009;type AcquisitionPolicy = 'reuse' | 'reacquire';@@ -456,7 +450,7 @@ export interface AcpThreadManagerOptions {permissions: AcpPermissionStore;sessionManager: AgentSessionManager;agentPresenceBroadcaster?: AgentPresenceBroadcaster | null;- resolveEmbed?: (basename: string, sourcePath: string) => string | null;+ localApi?: LocalApiDispatch;isExcludedPath: (relPath: string) => boolean;isIgnoredPath: (relPosix: string) => boolean;getLoadedDocText?: (docName: string) => string | null;@@ -1118,8 +1112,7 @@ export class AcpThreadManager {}).onRequest(acpMethods.client.fs.writeTextFile, async (ctx) => {try {- await this.handleFsWrite(record, ctx.params.path, ctx.params.content);- return {};+ return await this.handleFsWrite(record, ctx.params.path, ctx.params.content);} catch (err) {this.opts.log.warn({@@ -3581,9 +3574,11 @@ export class AcpThreadManager {await t.terminals?.disposeAll();t.terminals = null;this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));- await this.opts.sessionManager.closeAllForAgent(t.agentSessionId).catch((err) => {- this.opts.log.warn({ err, threadId }, '[acp-threads] session cleanup failed');- });+ await this.opts.sessionManager+ .closeAllForAgent(toBroadcasterKey(t.agentSessionId))+ .catch((err) => {+ this.opts.log.warn({ err, threadId }, '[acp-threads] session cleanup failed');+ });const failedStart = t.info.status === 'error' || t.info.status === 'auth_required';if (!t.hadUserMessage && !failedStart) {this.threads.delete(threadId);@@ -3799,72 +3794,31 @@ export class AcpThreadManager {record: ThreadRecord,requestedPath: string,content: string,- ): Promise<void> {+ ): Promise<WriteTextFileResponse> {this.touchTurnActivity(record);const target = await this.confinePath(requestedPath);if (target.docName !== null) {- const session = await this.opts.sessionManager.getSession(- target.docName,- record.agentSessionId,- {- displayName: record.info.agent.name,- colorSeed: record.agentSessionId,- clientName: record.info.agent.id,- },- );- const embedResolver =- this.opts.resolveEmbed !== undefined- ? { resolveEmbed: this.opts.resolveEmbed, sourcePath: target.rel }- : undefined;- const suppliedWriterId = sessionWriterId(session);- try {- session.dc.document.transact(() => {- const beforeBlocks = snapshotBlocks(session.dc.document);- applyAgentMarkdownWrite(- session.dc.document,- content,- 'replace',- embedResolver,- undefined,- agentWriteLossDetect(session),- suppliedWriterId,- );- const changedBlocks =- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;- const activityMap = session.dc.document.getMap('agent-flash');- activityMap.set(record.agentSessionId, {- agentId: record.agentSessionId,- timestamp: Date.now(),- type: 'insert',- description: `Added (${record.info.agent.name}): ${content.slice(0, 50)}`,- ...(changedBlocks !== undefined ? { changedBlocks } : {}),- });- }, session.origin);- } catch (error) {- if (error instanceof ConcurrentOverwriteRefusedError) {- logConcurrentOverwriteRefusal(error, 'acp-fs-write');- throw new RequestError(- CONCURRENT_OVERWRITE_REFUSED_CODE,- CONCURRENT_OVERWRITE_REFUSED_DETAIL,- {- type: CONCURRENT_OVERWRITE_REFUSED_TYPE,- file: error.file,- retryable: true,- retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,- },- );- }- throw error;+ if (this.opts.localApi === undefined) {+ throw new Error(`document writes are not available here: ${requestedPath}`);}+ const result = await writeDocumentThroughRoute(this.opts.localApi, {+ docName: target.docName,+ file: target.rel,+ markdown: content,+ agentId: record.agentSessionId,+ agentName: record.info.agent.name,+ clientName: record.info.agent.id,+ });this.setPresence(record, target.docName);- } else {- if (this.opts.isIgnoredPath(target.rel)) {- throw new Error(`path is excluded from the project content scope: ${requestedPath}`);- }- const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');- await tracedMkdir(dirname(target.abs), { recursive: true });- await tracedWriteFile(target.abs, content);+ return result;+ }+ if (this.opts.isIgnoredPath(target.rel)) {+ throw new Error(`path is excluded from the project content scope: ${requestedPath}`);}+ const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');+ await tracedMkdir(dirname(target.abs), { recursive: true });+ await tracedWriteFile(target.abs, content);+ return {};}private confinePath(@@ -4212,16 +4166,22 @@ export async function confineToContentDir(if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {throw new Error(`path escapes the content directory: ${requestedPath}`);}- const mdMatch = /\.(md|mdx)$/.exec(rel);- let docName: string | null = null;- if (mdMatch !== null) {- const candidate = rel.slice(0, -mdMatch[0].length).split(sep).join('/');- const relPosix = rel.split(sep).join('/');- if (!isSystemDoc(candidate) && !isConfigDoc(candidate) && !isExcludedPath(relPosix)) {- docName = candidate;- }- }- return { abs: resolved, rel: rel.split(sep).join('/'), docName };+ const relPosix = rel.split(sep).join('/');+ const mdMatch = /\.(md|mdx)$/.exec(relPosix);+ const candidate =+ mdMatch !== null+ ? relPosix.slice(0, -mdMatch[0].length)+ : isMermaidDoc(relPosix) || isExcalidrawDoc(relPosix) || isEditableTextDoc(relPosix)+ ? relPosix+ : null;+ const docName =+ candidate !== null &&+ !isSystemDoc(candidate) &&+ !isConfigDoc(candidate) &&+ !isExcludedPath(relPosix)+ ? candidate+ : null;+ return { abs: resolved, rel: relPosix, docName };} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;const parent = dirname(existing);diff --git a/packages/server/src/agent-write-agent-id-coverage.test.ts b/packages/server/src/agent-write-agent-id-coverage.test.tsindex 0e3234c91..c8ef2dab4 100644--- a/packages/server/src/agent-write-agent-id-coverage.test.ts+++ b/packages/server/src/agent-write-agent-id-coverage.test.ts@@ -41,7 +41,7 @@ describe('agent-write writer-identity coverage', () => {.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => calleeName(c) === 'applyAgentMarkdownWrite'),);- expect(spineCalls.length).toBeGreaterThanOrEqual(6);+ expect(spineCalls.length).toBeGreaterThanOrEqual(5);const missing = spineCalls.filter((c) => !threadsWriterIdentity(c)).map((c) => `${basename(c.getSourceFile().getFilePath())}:${c.getStartLineNumber()}`);diff --git a/packages/server/src/agent-write-loss-detect-coverage.test.ts b/packages/server/src/agent-write-loss-detect-coverage.test.tsindex 20f19a018..17d242da7 100644--- a/packages/server/src/agent-write-loss-detect-coverage.test.ts+++ b/packages/server/src/agent-write-loss-detect-coverage.test.ts@@ -41,7 +41,7 @@ describe('agent-write loss-detect coverage', () => {.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => calleeName(c) === 'applyAgentMarkdownWrite'),);- expect(spineCalls.length).toBeGreaterThanOrEqual(6);+ expect(spineCalls.length).toBeGreaterThanOrEqual(5);const missing = spineCalls.filter((c) => !threadsLossDetect(c)).map((c) => `${basename(c.getSourceFile().getFilePath())}:${c.getStartLineNumber()}`);diff --git a/packages/server/src/agent-write-outcome.test.ts b/packages/server/src/agent-write-outcome.test.tsindex 56de77992..066ddb234 100644--- a/packages/server/src/agent-write-outcome.test.ts+++ b/packages/server/src/agent-write-outcome.test.ts@@ -4,7 +4,6 @@ import {outcomeOfSavedWrite,outcomeOfStoreFailure,REFUSAL_OUTCOMES,- reportedOutcome,} from './agent-write-outcome.ts';import {OK_DOC_MOVED,@@ -14,6 +13,7 @@ import {OK_STORE_DISCARDED,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_DROPPED,OK_WRITE_REPLACED,type StoreFailure,} from './document-durability-state.ts';@@ -51,6 +51,27 @@ describe('the outcome of each refusal', () => {{ code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unsettled' } },'projection-held/unsaved/re-read',],+ [+ 'a file whose outside version could not go to history',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-no-history-or-backup' } },+ 'projection-held/unsaved/re-read',+ ],+ [+ 'a file that holds bytes that are not text',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-not-utf8' } },+ 'refused/unsaved/none',+ ],+ ['a failed write with no errno', { message: 'm' }, 'refused/unsaved/re-read'],+ [+ 'a write under a name with no file of its own',+ { code: OK_WRITE_DROPPED, message: 'm', dropped: 'legacy-name' },+ 'refused/unsaved/retry',+ ],+ [+ 'a write to a skill whose folder is gone',+ { code: OK_WRITE_DROPPED, message: 'm', dropped: 'container-gone' },+ 'refused/unsaved/none',+ ],['a no-base hold',{ code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unreadable', noBase: true } },@@ -147,11 +168,4 @@ describe('a saved write', () => {),).toBe('projection-held/unsaved/re-read');});-- test('carries no outcome for a document saved outside the Markdown store', () => {- const applied = outcomeOfSavedWrite(undefined, null);- expect(reportedOutcome('diagrams/flow.mmd', applied)).toBeUndefined();- expect(reportedOutcome('board.excalidraw', applied)).toBeUndefined();- expect(reportedOutcome('notes/guide', applied)).toEqual(applied);- });});diff --git a/packages/server/src/agent-write-outcome.ts b/packages/server/src/agent-write-outcome.tsindex dcbd5426e..9f0d3b679 100644--- a/packages/server/src/agent-write-outcome.ts+++ b/packages/server/src/agent-write-outcome.ts@@ -4,13 +4,7 @@ import type {ReconcileMergeOutcome,} from '@inkeep/open-knowledge-core';import {- isConfigDoc,- isEditableTextDoc,- isExcalidrawDoc,- isManagedArtifactDoc,- isMermaidDoc,-} from './cc1-broadcast.ts';-import {+ type HeldSaveReason,OK_DOC_MOVED,OK_DOC_REMOVED,OK_PATH_UNRESOLVABLE,@@ -18,6 +12,7 @@ import {OK_STORE_DISCARDED,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_DROPPED,OK_WRITE_REPLACED,type StoreFailure,} from './document-durability-state.ts';@@ -70,6 +65,24 @@ const REFUSED_NONE: AgentWriteOutcomeFields = {nextStep: 'none',};+const HELD_SAVE_OUTCOMES: Readonly<Record<HeldSaveReason, AgentWriteOutcomeFields>> = {+ 'pending-unreadable': PROJECTION_HELD,+ 'pending-exhausted': PROJECTION_HELD,+ 'pending-base-moved': PROJECTION_HELD,+ 'pending-no-intake': PROJECTION_HELD,+ 'pending-intake-failed': PROJECTION_HELD,+ 'pending-intake-failed-no-base': PROJECTION_HELD,+ 'pending-conflict': REFUSED_NONE,+ 'pending-unsettled': PROJECTION_HELD,+ 'pending-rename': PROJECTION_HELD,+ 'pending-no-history-or-backup': PROJECTION_HELD,+ 'pending-not-utf8': REFUSED_NONE,+};++export function heldSaveEndsOnlyByAPerson(reason: HeldSaveReason): boolean {+ return HELD_SAVE_OUTCOMES[reason].nextStep === 'none';+}+export const REFUSAL_OUTCOMES = {'urn:ok:error:concurrent-overwrite-refused': REFUSED_RETRY,'urn:ok:error:too-many-agent-sessions': REFUSED_RETRY,@@ -87,9 +100,9 @@ export const REFUSAL_OUTCOMES = {export function outcomeOfStoreFailure(failure: StoreFailure): AgentWriteOutcomeFields {switch (failure.code) {case OK_STORE_HELD:- return failure.held?.noBase === true || failure.held?.reason === 'pending-conflict'+ return failure.held?.noBase === true? REFUSED_NONE- : PROJECTION_HELD;+ : HELD_SAVE_OUTCOMES[failure.held?.reason ?? 'pending-unreadable'];case OK_DOC_MOVED:case OK_STORE_DISCARDED:return PROJECTION_HELD;@@ -101,6 +114,9 @@ export function outcomeOfStoreFailure(failure: StoreFailure): AgentWriteOutcomeFcase OK_STORE_REFUSED:case OK_WRITE_REPLACED:return REFUSED_RE_READ;+ case OK_WRITE_DROPPED:+ if (failure.dropped === 'legacy-name') return REFUSED_RETRY;+ return failure.dropped === 'intake-landed' ? REFUSED_RE_READ : REFUSED_NONE;default:return REFUSED_RE_READ;}@@ -114,16 +130,6 @@ export function answeredWithSuccessOnAppRoutes(failure: StoreFailure): boolean {);}-function savesOutsideTheMarkdownStore(docName: string): boolean {- return (- isConfigDoc(docName) ||- isManagedArtifactDoc(docName) ||- isMermaidDoc(docName) ||- isExcalidrawDoc(docName) ||- isEditableTextDoc(docName)- );-}-export type AgentWriteFlushOutcome =| { kind: 'failure'; failure: StoreFailure }| { kind: 'stale-external-write' }@@ -146,10 +152,3 @@ export function outcomeOfSavedWrite(if (beforeWrite?.reconciled === true || atSave !== undefined) return MERGED_FIRST;return landedWithDivergence ? APPLIED_WITH_DIVERGENCE : APPLIED;}--export function reportedOutcome(- docName: string,- outcome: AgentWriteOutcomeFields,-): AgentWriteOutcomeFields | undefined {- return savesOutsideTheMarkdownStore(docName) ? undefined : outcome;-}diff --git a/packages/server/src/agent-write-pre-drain-coverage.test.ts b/packages/server/src/agent-write-pre-drain-coverage.test.tsindex 0252d6890..c563662c4 100644--- a/packages/server/src/agent-write-pre-drain-coverage.test.ts+++ b/packages/server/src/agent-write-pre-drain-coverage.test.ts@@ -69,7 +69,7 @@ describe('agent-write pre-drain coverage', () => {.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => calleeName(c) === 'applyAgentMarkdownWrite'),);- expect(spineCalls.length).toBeGreaterThanOrEqual(6);+ expect(spineCalls.length).toBeGreaterThanOrEqual(5);const preDrainable = spineCalls.filter((call) => {const positions = positionLiterals(call);diff --git a/packages/server/src/api-extension.persistence-failure.test.ts b/packages/server/src/api-extension.persistence-failure.test.tsindex 8f5d07337..63e366bf4 100644--- a/packages/server/src/api-extension.persistence-failure.test.ts+++ b/packages/server/src/api-extension.persistence-failure.test.ts@@ -181,6 +181,27 @@ describe('respondPersistenceFailure: a held save', () => {expect(String(body.detail)).not.toContain(neverSays);});+ test('a not-UTF-8 hold says only a person ends it, in every field, and carries no retryWhen', () => {+ const { res, endCalls } = makeMockRes();+ respondPersistenceFailure(+ res,+ { code: OK_STORE_HELD, message: 'chart was not saved', held: { reason: 'pending-not-utf8' } },+ 'agent-write-md',+ );+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body).toMatchObject({+ reason: 'pending-not-utf8',+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+ });+ expect(body).not.toHaveProperty('retryWhen');+ expect(String(body.detail)).toContain(+ 'no save runs until someone saves the file as text again',+ );+ expect(String(body.detail)).not.toContain('re-read the document before editing it further');+ });+test('a held save with no errno names its reason and carries no cause code', () => {const { res, endCalls } = makeMockRes();const failure: StoreFailure = {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 8a92ad4ab..50d3ab46f 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -70,6 +70,7 @@ import {pluginRepositoryUrl,type SkillsLock,} from '@inkeep/open-knowledge-core/skills-catalog';+import { ACP_DOCUMENT_WRITE_PATH } from './acp/document-write.ts';import {type AcpHarnessAvailability,createAcpHarnessAvailabilityProbe,@@ -183,10 +184,10 @@ import {} from './agent-id.ts';import {type AgentWriteFlushOutcome,+ heldSaveEndsOnlyByAPerson,outcomeOfSavedWrite,outcomeOfStoreFailure,REFUSAL_OUTCOMES,- reportedOutcome,} from './agent-write-outcome.ts';import {applyRenameMap,@@ -244,8 +245,10 @@ import {OK_STORE_DISCARDED,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_DROPPED,OK_WRITE_REPLACED,type StoreFailure,+ type WriteDropCause,type WrittenThrough,writtenThroughOf,} from './document-durability-state.ts';@@ -422,7 +425,7 @@ let _agentWriteGateFiredCounter: ReturnType<ReturnType<typeof getMeter>['createCfunction agentWriteGateFiredCounter(): ReturnType<ReturnType<typeof getMeter>['createCounter']> {_agentWriteGateFiredCounter ||= getMeter().createCounter('ok.agent_write.gate_fired_total', {description:- 'Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-write-batch, agent-patch, rollback}.',+ 'Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, acp-document-write, agent-write-batch, agent-patch, rollback}.',});return _agentWriteGateFiredCounter;}@@ -437,13 +440,18 @@ function agentWriteContentDivergenceCounter(): ReturnType<'ok.agent_write.content_divergence_total',{description:- 'Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-write-batch, agent-patch, rollback}, divergence_type.',+ 'Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, acp-document-write, agent-write-batch, agent-patch, rollback}, divergence_type.',},);return _agentWriteContentDivergenceCounter;}-type DivergenceHandler = 'agent-write-md' | 'agent-write-batch' | 'agent-patch' | 'rollback';+type DivergenceHandler =+ | 'agent-write-md'+ | 'acp-document-write'+ | 'agent-write-batch'+ | 'agent-patch'+ | 'rollback';function recordContentDivergenceGate(handler: DivergenceHandler,@@ -1500,6 +1508,29 @@ function pathFaultProblem(failure: StoreFailure) {} satisfies BatchEntryError;}+const DROPPED_WRITE_ADVICE: Readonly<Record<WriteDropCause, string>> = {+ 'legacy-name':+ 'Write the skill or template by its file path instead; that write is saved to the file.',+ unresolvable:+ 'Retrying will not help until the path resolves again. Tell the user which document it is.',+ 'container-gone':+ 'OpenKnowledge does not re-create a skill folder that was deleted or moved. Tell the user which skill it is.',+ 'intake-landed':+ 'Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing.',+};++function droppedWriteProblem(failure: StoreFailure) {+ const advice =+ failure.dropped === undefined+ ? DROPPED_WRITE_ADVICE.unresolvable+ : DROPPED_WRITE_ADVICE[failure.dropped];+ return {+ type: 'urn:ok:error:write-dropped' as const,+ title: "Edit not saved: OpenKnowledge did not write this document's file.",+ detail: `${failure.message}. The edit is only in the open document. ${advice}`,+ } satisfies BatchEntryError;+}+function replacedWriteProblem(failure: StoreFailure) {return {type: 'urn:ok:error:write-replaced' as const,@@ -1555,7 +1586,10 @@ function discardedStoreProblem(failure: StoreFailure) {type HeldSaveRetry = 'next-save' | 'next-edit' | 'conflict-resolved' | 'replaced-on-next-edit';const HELD_SAVE_RULES: Readonly<- Record<HeldSaveReason, { readonly retryWhen: HeldSaveRetry; readonly sentence: string }>+ Record<+ HeldSaveReason,+ { readonly retryWhen: HeldSaveRetry | undefined; readonly sentence: string }+ >> = {'pending-unreadable': {retryWhen: 'next-save',@@ -1591,6 +1625,16 @@ const HELD_SAVE_RULES: Readonly<sentence:'It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.',},+ 'pending-no-history-or-backup': {+ retryWhen: 'next-save',+ sentence:+ 'The file is not written over until its outside version is saved to the document history or the backup folder; a later save tries again: the next edit to this document, or the idle save within a few minutes.',+ },+ 'pending-not-utf8': {+ retryWhen: undefined,+ sentence:+ 'OpenKnowledge does not write over it, and no save runs until someone saves the file as text again. Tell the user which file it is.',+ },'pending-unsettled': {retryWhen: 'next-save',sentence:@@ -1610,7 +1654,7 @@ function heldSaveDetail(failure: StoreFailure, reason: HeldSaveReason, noBase: bif (noBase) return `${failure.message}. ${NO_BASE_HOLD_SENTENCE}`;const { sentence } = HELD_SAVE_RULES[reason];if (reason === 'pending-rename') return `${failure.message}. ${sentence}`;- if (reason === 'pending-conflict') {+ if (heldSaveEndsOnlyByAPerson(reason)) {return `${failure.message}. The edit is kept in the document. ${sentence} Do not repeat this write.`;}return `${failure.message}. The edit is kept in the document. ${sentence} Do not repeat this write: re-read the document before editing it further.`;@@ -1619,12 +1663,13 @@ function heldSaveDetail(failure: StoreFailure, reason: HeldSaveReason, noBase: bfunction heldSaveProblem(failure: StoreFailure) {const reason = failure.held?.reason ?? 'pending-unreadable';const noBase = failure.held?.noBase === true;+ const retryWhen = noBase ? 'replaced-on-next-edit' : HELD_SAVE_RULES[reason].retryWhen;return {type: 'urn:ok:error:save-held' as const,title: 'Edit applied in memory; its save to disk is held.',detail: heldSaveDetail(failure, reason, noBase),reason,- retryWhen: noBase ? ('replaced-on-next-edit' as const) : HELD_SAVE_RULES[reason].retryWhen,+ ...(retryWhen === undefined ? {} : { retryWhen }),...(failure.held?.causeCode === undefined ? {} : { causeCode: failure.held.causeCode }),} satisfies BatchEntryError;}@@ -1663,6 +1708,8 @@ function storeFailureProblem(return withOutcome(400, pathFaultProblem(failure));case OK_WRITE_REPLACED:return withOutcome(409, replacedWriteProblem(failure));+ case OK_WRITE_DROPPED:+ return withOutcome(409, droppedWriteProblem(failure));default:return undefined;}@@ -2176,19 +2223,34 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {return resident ? writtenThroughOf(resident) : undefined;}- function markPendingAgentStore(docName: string): boolean {- const debounceId = `onStoreDocument-${docName}`;- if (!hocuspocus.debouncer.isDebounced(debounceId)) return false;- durabilityState.markAgentWriteStore(docName);- return true;+ async function storeAgainAfterRunningStore(docName: string): Promise<void> {+ const resident = hocuspocus.documents.get(docName);+ if (resident === undefined) return;+ await hocuspocus.storeDocumentHooks(+ resident,+ {+ instance: hocuspocus,+ clientsCount: resident.getConnectionsCount(),+ document: resident,+ documentName: docName,+ lastContext: {},+ lastTransactionOrigin: null,+ },+ true,+ );}async function flushDiskAndDetectOutcome(docName: string,writtenThrough: WrittenThrough | undefined = writtenThroughOfResident(docName),): Promise<FlushOutcome> {- if (markPendingAgentStore(docName)) {- await hocuspocus.debouncer.executeNow(`onStoreDocument-${docName}`);+ const debounceId = `onStoreDocument-${docName}`;+ if (hocuspocus.debouncer.isDebounced(debounceId)) {+ durabilityState.markAgentWriteStore(docName);+ await hocuspocus.debouncer.executeNow(debounceId);+ } else if (hocuspocus.debouncer.isCurrentlyExecuting(debounceId)) {+ durabilityState.markAgentWriteStore(docName);+ await storeAgainAfterRunningStore(docName);}const deferredWaitStarted = Date.now();const deferredWait = await durabilityState.awaitDeferredStoreOutcome(docName);@@ -2226,6 +2288,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {}failure ??= durabilityState.takeStoreFailure(docName) ?? undefined;const atSave = durabilityState.readStoreIntake(docName, writtenThrough);+ durabilityState.consumeAgentWriteStore(docName);if (failure) return answerForCarriedEdit(docName, failure, writtenThrough);if (durabilityState.takeStaleExternalWriteFreeze(docName)) {return { kind: 'stale-external-write' };@@ -3932,6 +3995,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {});}, session.origin);writtenThrough = writtenThroughOf(session.dc.document);+ durabilityState.markAgentWriteStore(docName);recordContributor(docName,agentId,@@ -3966,11 +4030,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {...(summaryResponse ? { summary: summaryResponse } : {}),...(agentWriteWarning ? { warnings: [agentWriteWarning] } : {}),};- const agentWriteOutcome = reportedOutcome(- docName,- outcomeOfSavedWrite(agentWriteReconcile, flushOutcome),- );- if (agentWriteOutcome?.outcome === 'both-kept') {+ const agentWriteOutcome = outcomeOfSavedWrite(agentWriteReconcile, flushOutcome);+ if (agentWriteOutcome.outcome === 'both-kept') {respondBothKept(res, 'agent-write', agentWriteBody, agentWriteOutcome);return;}@@ -4240,7 +4301,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {resolvedDocName,session.dc.document.getText('source').toString(),);- markPendingAgentStore(resolvedDocName);+ durabilityState.markAgentWriteStore(resolvedDocName);} finally {disposeEntryEffectCapture();}@@ -4332,10 +4393,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {results[p.index] = {status: 'written',docName: p.docName,- ...reportedOutcome(- p.docName,- outcomeOfSavedWrite(p.reconcile, flushOutcome, p.diverged),- ),+ ...outcomeOfSavedWrite(p.reconcile, flushOutcome, p.diverged),...(p.summaryResponse ? { summary: p.summaryResponse } : {}),...(warnings.length > 0 ? { warnings } : {}),...linkAdvisory.links,@@ -5395,6 +5453,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {agentPresenceBroadcaster,buildAgentActor,flushDiskAndDetectOutcome,+ markAgentWriteStore: (docName) => durabilityState.markAgentWriteStore(docName),respondPersistenceFailure,respondStaleExternalWrite,flushDocToDisk,@@ -5426,6 +5485,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {extractAgentIdentity,sessionManager,flushDiskAndDetectOutcome,+ markAgentWriteStore: (docName) => durabilityState.markAgentWriteStore(docName),respondStaleExternalWrite,respondPersistenceFailure,attributeOkArtifactWrite,@@ -5474,6 +5534,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {extractAgentIdentity,sessionManager,flushDiskAndDetectOutcome,+ markAgentWriteStore: (docName) => durabilityState.markAgentWriteStore(docName),respondStaleExternalWrite,respondPersistenceFailure,okArtifactKey,@@ -5662,6 +5723,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {attributeOkArtifactWrite,scheduleOkArtifactFlush,flushDiskAndDetectOutcome,+ markAgentWriteStore: (docName) => durabilityState.markAgentWriteStore(docName),respondPersistenceFailure,respondStaleExternalWrite,registerWrittenDocInFileIndex,@@ -5897,8 +5959,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {throw new Error(`MCP_LOCAL_API_PATHS has no handler for ${path}`);}}+ const inProcessOnlyRoutes: ReadonlyMap<+ string,+ (req: IncomingMessage, res: ServerResponse) => Promise<void> | void+ > = new Map([[ACP_DOCUMENT_WRITE_PATH, agentWriteRoutes.acpDocumentWrite]]);const localApi = createLocalApiDispatch({resolve: (pathname) => {+ const inProcessOnly = inProcessOnlyRoutes.get(pathname);+ if (inProcessOnly !== undefined) {+ return (req, res) => dispatchMutation(async () => inProcessOnly(req, res), pathname);+ }if (!MCP_LOCAL_API_PATHS.has(pathname)) return undefined;const legacy = routes[pathname];if (legacy !== undefined) {diff --git a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.tsindex 3cade8e9f..ae712499c 100644--- a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts+++ b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts@@ -80,7 +80,11 @@ const baseHocuspocus = () =>documents: new Map(),closeConnections() {},unloadDocument: async () => {},- debouncer: { isDebounced: () => false, executeNow: async () => undefined },+ debouncer: {+ isDebounced: () => false,+ isCurrentlyExecuting: () => false,+ executeNow: async () => undefined,+ },}) as unknown as Options['hocuspocus'];let contentDir: string;diff --git a/packages/server/src/api-folder-rename-disk-enum.test.ts b/packages/server/src/api-folder-rename-disk-enum.test.tsindex a55af5b2c..e1f421760 100644--- a/packages/server/src/api-folder-rename-disk-enum.test.ts+++ b/packages/server/src/api-folder-rename-disk-enum.test.ts@@ -71,7 +71,11 @@ async function renameFolder(documents: options.documents ?? new Map(),closeConnections() {},unloadDocument: async () => {},- debouncer: { isDebounced: () => false, executeNow: async () => undefined },+ debouncer: {+ isDebounced: () => false,+ isCurrentlyExecuting: () => false,+ executeNow: async () => undefined,+ },} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],sessionManager: {closeSession: async () => {},diff --git a/packages/server/src/api-rename-crash-injection.test.ts b/packages/server/src/api-rename-crash-injection.test.tsindex ba0f3df30..07f27567f 100644--- a/packages/server/src/api-rename-crash-injection.test.ts+++ b/packages/server/src/api-rename-crash-injection.test.ts@@ -113,6 +113,7 @@ async function callRename(body: unknown): Promise<CapturedResponse> {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],diff --git a/packages/server/src/api-rename-log-emission.test.ts b/packages/server/src/api-rename-log-emission.test.tsindex 69bdccaed..06b735439 100644--- a/packages/server/src/api-rename-log-emission.test.ts+++ b/packages/server/src/api-rename-log-emission.test.ts@@ -113,6 +113,7 @@ async function callRename(body: unknown): Promise<CapturedResponse> {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],diff --git a/packages/server/src/api-rename-race-conditions.test.ts b/packages/server/src/api-rename-race-conditions.test.tsindex ef49cc625..19274e757 100644--- a/packages/server/src/api-rename-race-conditions.test.ts+++ b/packages/server/src/api-rename-race-conditions.test.ts@@ -114,6 +114,7 @@ describe('Finding 1 — folder-rename enumeration races concurrent index updatesunloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],@@ -174,6 +175,7 @@ describe('Finding 2 — admission check uses on-disk source extension', () => {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],diff --git a/packages/server/src/api-rename-rollback-summary.test.ts b/packages/server/src/api-rename-rollback-summary.test.tsindex beded8348..279ab15e0 100644--- a/packages/server/src/api-rename-rollback-summary.test.ts+++ b/packages/server/src/api-rename-rollback-summary.test.ts@@ -108,6 +108,7 @@ async function callApi(unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],diff --git a/packages/server/src/api-rename-telemetry.test.ts b/packages/server/src/api-rename-telemetry.test.tsindex b620ba831..5491bc483 100644--- a/packages/server/src/api-rename-telemetry.test.ts+++ b/packages/server/src/api-rename-telemetry.test.ts@@ -123,6 +123,7 @@ async function callApi(unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],diff --git a/packages/server/src/api-rollback-actor-identity.test.ts b/packages/server/src/api-rollback-actor-identity.test.tsindex 961b7943b..791e4c4c9 100644--- a/packages/server/src/api-rollback-actor-identity.test.ts+++ b/packages/server/src/api-rollback-actor-identity.test.ts@@ -62,6 +62,7 @@ interface RollbackHarness {unloadDocument: (doc: Y.Doc) => Promise<void>;debouncer: {isDebounced: () => boolean;+ isCurrentlyExecuting: () => boolean;executeNow: () => Promise<void>;};};@@ -114,6 +115,7 @@ async function setupRollback(tmpDir: string): Promise<RollbackHarness> {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},};diff --git a/packages/server/src/api-rollback-rename-history.test.ts b/packages/server/src/api-rollback-rename-history.test.tsindex 21e722502..c573b4351 100644--- a/packages/server/src/api-rollback-rename-history.test.ts+++ b/packages/server/src/api-rollback-rename-history.test.ts@@ -145,6 +145,7 @@ describe('handleRollback — rename history mitigation (US-005)', () => {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},};diff --git a/packages/server/src/api-skill-store-refusal.test.ts b/packages/server/src/api-skill-store-refusal.test.tsindex 0de7b4bc3..20ee29093 100644--- a/packages/server/src/api-skill-store-refusal.test.ts+++ b/packages/server/src/api-skill-store-refusal.test.ts@@ -88,7 +88,11 @@ async function callApi(method: string, url: string, body?: unknown): Promise<Capdocuments: new Map(),closeConnections() {},unloadDocument: async () => {},- debouncer: { isDebounced: () => false, executeNow: async () => undefined },+ debouncer: {+ isDebounced: () => false,+ isCurrentlyExecuting: () => false,+ executeNow: async () => undefined,+ },} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],sessionManager: {closeSession: async () => {},diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex c71c9b887..3585dba3b 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -496,7 +496,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {permissions: serverInstance.acpPermissions,sessionManager,agentPresenceBroadcaster,- resolveEmbed: serverInstance.resolveEmbed,+ localApi: serverInstance.localApi,isExcludedPath: (rel) => serverInstance.contentFilter.isExcluded(rel),isIgnoredPath: (rel) => serverInstance.contentFilter.isPathIgnored(rel),getLoadedDocText: (docName) =>diff --git a/packages/server/src/document-durability-state.ts b/packages/server/src/document-durability-state.tsindex 6580dd4be..11307adec 100644--- a/packages/server/src/document-durability-state.ts+++ b/packages/server/src/document-durability-state.ts@@ -47,7 +47,12 @@ export type RenameCarryAnswer =| { readonly kind: 'unsettled' }| { readonly kind: 'stopped' };-export type HeldSaveReason = StorePendingReason | 'pending-unsettled' | 'pending-rename';+export type HeldSaveReason =+ | StorePendingReason+ | 'pending-unsettled'+ | 'pending-rename'+ | 'pending-no-history-or-backup'+ | 'pending-not-utf8';export type StoreIntakeMerge = ReconcileMergeOutcome | 'disk-replaced';@@ -83,8 +88,11 @@ export interface StoreFailure {readonly causeCode?: string;readonly noBase?: true;};+ dropped?: WriteDropCause;}+export type WriteDropCause = 'legacy-name' | 'unresolvable' | 'container-gone' | 'intake-landed';+export type StoreFailureRemoval =| { kind: 'renamed'; renamedTo: string; carry?: Promise<RenameCarryAnswer> }| { kind: 'path-occupied' }@@ -134,6 +142,7 @@ export const OK_STORE_DISCARDED = 'OK_STORE_DISCARDED';export const OK_DOC_MOVED = 'OK_DOC_MOVED';export const OK_SERVER_STOPPED = 'OK_SERVER_STOPPED';export const OK_WRITE_REPLACED = 'OK_WRITE_REPLACED';+export const OK_WRITE_DROPPED = 'OK_WRITE_DROPPED';const IN_FLIGHT_FLUSH_TTL_MS = 60_000;diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.tsindex 06cb4dbef..67cf49100 100644--- a/packages/server/src/external-change.ts+++ b/packages/server/src/external-change.ts@@ -465,7 +465,7 @@ export function buildReconcileWarning(};}-const NOT_RECONCILED: ReconcileBeforeWriteResult = {+export const NOT_RECONCILED: ReconcileBeforeWriteResult = {reconciled: false,baseBytes: 0,diskBytes: 0,diff --git a/packages/server/src/http/agent-write-routes.test.ts b/packages/server/src/http/agent-write-routes.test.tsindex 66c6c2724..27e61da51 100644--- a/packages/server/src/http/agent-write-routes.test.ts+++ b/packages/server/src/http/agent-write-routes.test.ts@@ -1,7 +1,7 @@import type { IncomingMessage } from 'node:http';import { Readable } from 'node:stream';import { Hocuspocus } from '@hocuspocus/server';-import { describe, expect, test } from 'vitest';+import { describe, expect, test, vi } from 'vitest';import { sessionWriterId } from '../agent-id.ts';import { AgentSessionManager } from '../agent-sessions.ts';import { makeCaptureRes } from '../composition-rig.test-helper.ts';@@ -211,3 +211,66 @@ describe('edit routes refuse a document path that has nothing behind it', () =>}});});++describe('the in-app agent write runs under its own route name', () => {+ function acpWriteGroup(overrides: Partial<Deps>) {+ const hocuspocus = new Hocuspocus({ quiet: true });+ const sessionManager = new AgentSessionManager(hocuspocus);+ const gateHandlers: string[] = [];+ const summaryCounts: unknown[] = [];+ const group = buildGroup({+ hocuspocus,+ sessionManager,+ durabilityState: { markAgentWriteStore: () => {} } as unknown as DocumentDurabilityState,+ recordContentDivergenceGate: (handler) => {+ gateHandlers.push(handler);+ },+ countNormalizedSummary: (normalized) => {+ summaryCounts.push(normalized);+ },+ buildAgentActor: () => ({}),+ flushDiskAndDetectOutcome: () => Promise.resolve(null),+ flushDocToDisk: () => {},+ registerWrittenDocInFileIndex: () => {},+ ...overrides,+ });+ return { group, sessionManager, gateHandlers, summaryCounts };+ }++ const acpBody = { docName: 'note', file: 'note.md', markdown: '# Note\n', agentId: 'acp-agent' };++ test('labels the divergence gate with the ACP route, counts no summary, and skips the MCP report', async () => {+ const { group, sessionManager, gateHandlers, summaryCounts } = acpWriteGroup({});+ try {+ const { res, captured } = makeCaptureRes();+ await group.acpDocumentWrite(makeReq('/internal/acp/document-write', acpBody), res);+ expect(captured.status).toBe(200);+ expect(JSON.parse(captured.body)).toMatchObject({+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+ });+ expect(gateHandlers).toEqual(['acp-document-write']);+ expect(summaryCounts).toEqual([]);+ } finally {+ await sessionManager.closeAll();+ }+ });++ test('logs a failure under the ACP route name', async () => {+ const log = loggerFactory.getLogger('acp-document-write-test');+ const logged = vi.spyOn(log, 'error').mockImplementation(() => {});+ const { group, sessionManager } = acpWriteGroup({+ log,+ flushDiskAndDetectOutcome: () => Promise.reject(new Error('flush failed')),+ });+ try {+ const { res, captured } = makeCaptureRes();+ await group.acpDocumentWrite(makeReq('/internal/acp/document-write', acpBody), res);+ expect(captured.status).toBe(500);+ expect(logged).toHaveBeenCalledWith(expect.anything(), '[acp-document-write] handler failed');+ } finally {+ await sessionManager.closeAll();+ }+ });+});diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.tsindex 51ae698ff..07741acb4 100644--- a/packages/server/src/http/agent-write-routes.ts+++ b/packages/server/src/http/agent-write-routes.ts@@ -1,4 +1,4 @@-import type { ServerResponse } from 'node:http';+import type { IncomingMessage, ServerResponse } from 'node:http';import type { Hocuspocus } from '@hocuspocus/server';import {AGENT_ICON_COLORS,@@ -8,8 +8,10 @@ import {AgentPatchSuccessSchema,AgentUndoRequestSchema,AgentUndoSuccessSchema,+ type AgentWriteMdRequest,AgentWriteMdRequestSchema,AgentWriteMdSuccessSchema,+ agentWriteOutcomeWireFields,applyPatchToFm,changedBlockRange,colorFromSeed,@@ -27,8 +29,10 @@ import {SaveVersionRequestSchema,SaveVersionSuccessSchema,stripFrontmatter,+ validateDocName,} from '@inkeep/open-knowledge-core';import { formatRollbackSubject } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { z } from 'zod';import { captureEffect } from '../activity-log.ts';import { listAgentActivity, synthesizeVersionDiff } from '../agent-activity.ts';import type { AgentFocusBroadcaster } from '../agent-focus.ts';@@ -52,7 +56,6 @@ import {answeredWithSuccessOnAppRoutes,outcomeOfSavedWrite,REFUSAL_OUTCOMES,- reportedOutcome,} from '../agent-write-outcome.ts';import {type NormalizedSummary,@@ -72,8 +75,14 @@ import {evaluateContentDivergence,toContentDivergenceWarning,} from '../content-divergence-gate.ts';+import type { ContentFilter } from '../content-filter.ts';import { recordContributor } from '../contributor-tracker.ts';-import { canonicalDocName, registerDocExtension, stripDocExtension } from '../doc-extensions.ts';+import {+ canonicalDocName,+ registerDocExtension,+ SUPPORTED_DOC_EXTENSIONS,+ stripDocExtension,+} from '../doc-extensions.ts';import {type DocumentDurabilityState,type StoreFailure,@@ -81,6 +90,7 @@ import {writtenThroughOf,} from '../document-durability-state.ts';import {+ NOT_RECONCILED,type ReconcileBeforeWriteResult,reconcileDiskBeforeAgentWrite,} from '../external-change.ts';@@ -114,6 +124,7 @@ import { respondAgentSessionCapacity } from './agent-session-capacity.ts';import { respondBothKept } from './agent-write-response.ts';import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';import { errorResponse } from './error-response.ts';+import type { RouteHandler } from './method-router.ts';import { getRequestId } from './request-id.ts';import { withValidation } from './request-validation.ts';import { successResponse } from './success-response.ts';@@ -179,12 +190,18 @@ export interface AgentWriteRouteDeps {hocuspocus: Hocuspocus;options: {resolveEmbed?: (basename: string, sourcePath: string) => string | null;+ contentFilter?: Pick<ContentFilter, 'isExcluded'>;};getBridgeLossReporter: (() => BridgeDeriveLossReporter | undefined) | undefined;mergeHistory: MergeHistoryRecorder;agentPresenceBroadcaster: AgentPresenceBroadcaster | undefined;recordContentDivergenceGate: (- handler: 'agent-write-md' | 'agent-write-batch' | 'agent-patch' | 'rollback',+ handler:+ | 'agent-write-md'+ | 'acp-document-write'+ | 'agent-write-batch'+ | 'agent-patch'+ | 'rollback',divergence: AgentWriteContentDivergence | undefined,) => void;buildAgentActor: (args: {@@ -235,7 +252,43 @@ export interface AgentWriteRouteDeps {renameAttributionCounter: () => ReturnType<ReturnType<typeof getMeter>['createCounter']>;}-export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup {+interface MarkdownWriteMode {+ readonly handler: 'agent-write-md' | 'acp-document-write';+ readonly preWriteMerge: boolean;+ readonly callerReadsWriteReport: boolean;+}++const ROUTE_MARKDOWN_WRITE: MarkdownWriteMode = {+ handler: 'agent-write-md',+ preWriteMerge: true,+ callerReadsWriteReport: true,+};++const ACP_MARKDOWN_WRITE: MarkdownWriteMode = {+ handler: 'acp-document-write',+ preWriteMerge: false,+ callerReadsWriteReport: false,+};++const AcpDocumentWriteRequestSchema = z+ .object({+ docName: z.string().min(1),+ file: z.string().min(1),+ markdown: z.string(),+ extension: z.enum(SUPPORTED_DOC_EXTENSIONS).optional(),+ agentId: z.string().optional(),+ agentName: z.string().optional(),+ clientName: z.string().optional(),+ })+ .strict();++const AcpDocumentWriteSuccessSchema = z+ .object({ ...agentWriteOutcomeWireFields, timestamp: z.string().min(1) })+ .strict();++export function createAgentWriteRoutes(+ deps: AgentWriteRouteDeps,+): ApiRouteGroup & { readonly acpDocumentWrite: RouteHandler } {const {conflicts,getLinkAdvisoryPolicy,@@ -345,248 +398,303 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupconst handleAgentWriteMd = withValidation(AgentWriteMdRequestSchema,- async (_req, res, body) => {- try {- const linkPolicy = getLinkAdvisoryPolicy();- const position = body.position ?? 'append';- const effectiveDocName = requireNonEmptyDocName(body.docName, res, 'agent-write-md');- if (effectiveDocName === null) return;- const resolvedDocName = canonicalDocName(resolveAlias(effectiveDocName));- const {- agentId,- suppliedWriterId,- agentName,+ (req, res, body) => writeAgentMarkdownDocument(req, res, body, ROUTE_MARKDOWN_WRITE),+ { handler: 'agent-write-md', method: 'POST' },+ );++ function isAcpWritableDocument(docName: string, file: string): boolean {+ if (docName !== file && docName !== stripDocExtension(file)) return false;+ if (validateDocName(docName).ok) return true;+ return options.contentFilter !== undefined && !options.contentFilter.isExcluded(file);+ }++ async function writeAgentMarkdownDocument(+ _req: IncomingMessage,+ res: ServerResponse,+ body: AgentWriteMdRequest,+ mode: MarkdownWriteMode,+ ): Promise<void> {+ try {+ const linkPolicy = getLinkAdvisoryPolicy();+ const position = body.position ?? 'append';+ const effectiveDocName = requireNonEmptyDocName(body.docName, res, mode.handler);+ if (effectiveDocName === null) return;+ const resolvedDocName = canonicalDocName(resolveAlias(effectiveDocName));+ const { agentId, suppliedWriterId, agentName, colorSeed, clientName, clientVersion, label } =+ extractAgentIdentity(body);+ if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:reserved-doc-name',+ `'${resolvedDocName}' is a reserved document name.`,+ {+ handler: mode.handler,+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },+ );+ return;+ }+ if (+ body.extension !== undefined &&+ !docNameExistsWithAnySupportedExtension(contentDir, resolvedDocName)+ ) {+ registerDocExtension(resolvedDocName, body.extension);+ }+ const normalizedSummary = normalizeSummary(body.summary);+ const { response: summaryResponse, stored: storedSummary } =+ summaryResponseFields(normalizedSummary);+ await sessionManager.withSessions(async (getSession) => {+ const session = await getSession(resolvedDocName, agentId, {+ displayName: agentName,colorSeed,clientName,- clientVersion,- label,- } = extractAgentIdentity(body);- if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {- errorResponse(- res,- 400,- 'urn:ok:error:reserved-doc-name',- `'${resolvedDocName}' is a reserved document name.`,- {- handler: 'agent-write-md',- extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },- },- );- return;- }- if (- body.extension !== undefined &&- !docNameExistsWithAnySupportedExtension(contentDir, resolvedDocName)- ) {- registerDocExtension(resolvedDocName, body.extension);- }- const normalizedSummary = normalizeSummary(body.summary);- const { response: summaryResponse, stored: storedSummary } =- summaryResponseFields(normalizedSummary);- await sessionManager.withSessions(async (getSession) => {- const session = await getSession(resolvedDocName, agentId, {+ });+ const writeMdReconcile = mode.preWriteMerge+ ? await reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,+ resolvedDocName,+ contentDir,+ options.resolveEmbed,+ getBridgeLossReporter?.(),+ conflicts,+ mergeHistory,+ )+ : NOT_RECONCILED;+ const writeMdEmbedResolver = options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }+ : undefined;+ const writeMdPrecomputed = await prepareAgentMarkdownParse(+ session.dc.document,+ body.markdown,+ position,+ writeMdEmbedResolver,+ );+ const timestamp = new Date().toISOString();+ let writeDivergence: AgentWriteContentDivergence | undefined;+ let disposeEffectCapture: (() => void) | undefined;+ let writtenThrough: WrittenThrough | undefined;+ let writtenSource = '';+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {displayName: agentName,+ icon,+ color,+ currentDoc: resolvedDocName,+ mode: 'writing',+ ts: Date.now(),+ });+ disposeEffectCapture = captureEffect(+ session.dc.document.getText('source'),+ agentId,+ session.origin,colorSeed,clientName,- });- const writeMdReconcile = await reconcileDiskBeforeAgentWrite(- durabilityState,- hocuspocus,- resolvedDocName,- contentDir,- options.resolveEmbed,- getBridgeLossReporter?.(),- conflicts,- mergeHistory,- );- const writeMdEmbedResolver = options.resolveEmbed- ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }- : undefined;- const writeMdPrecomputed = await prepareAgentMarkdownParse(- session.dc.document,- body.markdown,- position,- writeMdEmbedResolver,);- const timestamp = new Date().toISOString();- let writeDivergence: AgentWriteContentDivergence | undefined;- let disposeEffectCapture: (() => void) | undefined;- let writtenThrough: WrittenThrough | undefined;- let writtenSource = '';- try {- const icon = iconFromClientName(clientName);- const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);- agentPresenceBroadcaster?.setPresence(agentId, {- displayName: agentName,- icon,- color,- currentDoc: resolvedDocName,- mode: 'writing',- ts: Date.now(),- });- disposeEffectCapture = captureEffect(- session.dc.document.getText('source'),- agentId,- session.origin,- colorSeed,- clientName,+ agentWritePreDrain(session.dc.document, body.markdown, position);+ session.dc.document.transact(() => {+ const beforeBlocks = snapshotBlocks(session.dc.document);+ writeDivergence = applyAgentMarkdownWrite(+ session.dc.document,+ body.markdown,+ position,+ writeMdEmbedResolver,+ writeMdPrecomputed,+ agentWriteLossDetect(session),+ suppliedWriterId,);- agentWritePreDrain(session.dc.document, body.markdown, position);- session.dc.document.transact(() => {- const beforeBlocks = snapshotBlocks(session.dc.document);- writeDivergence = applyAgentMarkdownWrite(- session.dc.document,- body.markdown,- position,- writeMdEmbedResolver,- writeMdPrecomputed,- agentWriteLossDetect(session),- suppliedWriterId,- );- const changedBlocks =- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;- const activityMap = session.dc.document.getMap('agent-flash');- activityMap.set(agentId, {- agentId,- timestamp: Date.now(),- type: 'insert',- description: `Added (${agentName}): ${body.markdown.trim().slice(0, 50)}`,- ...(changedBlocks !== undefined ? { changedBlocks } : {}),- });- }, session.origin);- writtenThrough = writtenThroughOf(session.dc.document);- writtenSource = session.dc.document.getText('source').toString();- if (writeDivergence !== undefined) {- console.warn(- JSON.stringify({- event: 'agent-write-content-divergence',- 'doc.name': resolvedDocName,- position,- intendedBytes: writeDivergence.intendedBytes,- actualBytes: writeDivergence.actualBytes,- byteDelta: writeDivergence.byteDelta,- 'agent.id': agentId,- 'agent.client_name': clientName,- }),- );- }- recordContentDivergenceGate('agent-write-md', writeDivergence);- recordContributor(- resolvedDocName,+ const changedBlocks =+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;+ const activityMap = session.dc.document.getMap('agent-flash');+ activityMap.set(agentId, {agentId,- agentName,- colorSeed,- undefined,- buildAgentActor({ clientName, clientVersion, label }),- storedSummary,+ timestamp: Date.now(),+ type: 'insert',+ description: `Added (${agentName}): ${body.markdown.trim().slice(0, 50)}`,+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),+ });+ }, session.origin);+ writtenThrough = writtenThroughOf(session.dc.document);+ durabilityState.markAgentWriteStore(resolvedDocName);+ writtenSource = session.dc.document.getText('source').toString();+ if (writeDivergence !== undefined) {+ console.warn(+ JSON.stringify({+ event: 'agent-write-content-divergence',+ 'doc.name': resolvedDocName,+ position,+ intendedBytes: writeDivergence.intendedBytes,+ actualBytes: writeDivergence.actualBytes,+ byteDelta: writeDivergence.byteDelta,+ 'agent.id': agentId,+ 'agent.client_name': clientName,+ }),);- incrementAgentWriteCalls();- countNormalizedSummary(normalizedSummary);- } finally {- disposeEffectCapture?.();- agentPresenceBroadcaster?.touchMode(agentId, 'idle');- }- const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName, writtenThrough);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'agent-write-md');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'agent-write-md', resolvedDocName);- return;}- flushDocToDisk(resolvedDocName, 'agent-write-md');- agentFocusBroadcaster?.setFocus(agentId, {- agentName,- currentDoc: resolvedDocName,- writeKind: 'write',- ts: Date.now(),- });- onAgentWrite?.();- writtenSource =- hocuspocus.documents.get(resolvedDocName)?.getText('source').toString() ??- writtenSource;- const hints = await computeOrphanHints(resolvedDocName);- registerWrittenDocInFileIndex(resolvedDocName, writtenSource);- const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);- const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(- writtenSource,+ recordContentDivergenceGate(mode.handler, writeDivergence);+ recordContributor(resolvedDocName,- linkPolicy.suppressLogLinkAdvisories,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,);- const subscriberCount = getSubscriberCount(resolvedDocName);- const systemSubscriberCount = getSystemSubscriberCount();- if (systemSubscriberCount === 0) {- hintEmittedCounter().add(1, {- 'shadow.writer': 'agent',- 'agent.type': resolveAgentType(clientName),- });+ if (mode.callerReadsWriteReport) {+ incrementAgentWriteCalls();+ countNormalizedSummary(normalizedSummary);}- const writeMdWarning = buildReconcileWarning(writeMdReconcile);- const writeMdDivergenceEntry =- writeDivergence !== undefined ? toContentDivergenceWarning(writeDivergence) : undefined;- const writeMdAdvisories = [- ...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),- ...(writeMdWarning ? [writeMdWarning] : []),- ...(renderWarnings ?? []),- ...(await computeLintViolations(writtenSource, resolvedDocName, linkPolicy)),- ...linkAdvisory.warnings,- ];- const writeMdBody = {- timestamp,- subscriberCount,- systemSubscriberCount,- ...(hints ? { hints } : {}),- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),- ...linkAdvisory.links,- };- const writeMdOutcome = reportedOutcome(- resolvedDocName,- outcomeOfSavedWrite(writeMdReconcile, flushOutcome, writeDivergence !== undefined),- );- if (writeMdOutcome?.outcome === 'both-kept') {- respondBothKept(res, 'agent-write-md', writeMdBody, writeMdOutcome);+ } finally {+ disposeEffectCapture?.();+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');+ }+ const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName, writtenThrough);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, mode.handler);+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, mode.handler, resolvedDocName);+ return;+ }+ flushDocToDisk(resolvedDocName, mode.handler);+ agentFocusBroadcaster?.setFocus(agentId, {+ agentName,+ currentDoc: resolvedDocName,+ writeKind: 'write',+ ts: Date.now(),+ });+ onAgentWrite?.();+ writtenSource =+ hocuspocus.documents.get(resolvedDocName)?.getText('source').toString() ?? writtenSource;+ const writeMdOutcome = outcomeOfSavedWrite(+ writeMdReconcile,+ flushOutcome,+ writeDivergence !== undefined,+ );+ if (!mode.callerReadsWriteReport) {+ registerWrittenDocInFileIndex(resolvedDocName, writtenSource);+ if (writeMdOutcome.outcome === 'both-kept') {+ respondBothKept(res, mode.handler, { timestamp }, writeMdOutcome);return;}successResponse(res,200,- AgentWriteMdSuccessSchema,- { ...writeMdBody, ...writeMdOutcome },- { handler: 'agent-write-md' },- );- });- } catch (e) {- if (e instanceof DocInConflictError) {- respondDocInConflict(- res,- e,- 'agent-write-md',- conflicts.findByDocName(stripDocExtension(e.file)),+ AcpDocumentWriteSuccessSchema,+ { timestamp, ...writeMdOutcome },+ { handler: mode.handler },);return;}- if (e instanceof ConcurrentOverwriteRefusedError) {- respondConcurrentOverwriteRefused(res, e, 'agent-write-md');- return;+ const hints = await computeOrphanHints(resolvedDocName);+ registerWrittenDocInFileIndex(resolvedDocName, writtenSource);+ const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);+ const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(+ writtenSource,+ resolvedDocName,+ linkPolicy.suppressLogLinkAdvisories,+ );+ const subscriberCount = getSubscriberCount(resolvedDocName);+ const systemSubscriberCount = getSystemSubscriberCount();+ if (systemSubscriberCount === 0) {+ hintEmittedCounter().add(1, {+ 'shadow.writer': 'agent',+ 'agent.type': resolveAgentType(clientName),+ });}- if (e instanceof FrontmatterMalformedError) {- respondFrontmatterMalformed(res, e, 'agent-write-md');+ const writeMdWarning = buildReconcileWarning(writeMdReconcile);+ const writeMdDivergenceEntry =+ writeDivergence !== undefined ? toContentDivergenceWarning(writeDivergence) : undefined;+ const writeMdAdvisories = [+ ...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),+ ...(writeMdWarning ? [writeMdWarning] : []),+ ...(renderWarnings ?? []),+ ...(await computeLintViolations(writtenSource, resolvedDocName, linkPolicy)),+ ...linkAdvisory.warnings,+ ];+ const writeMdBody = {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ ...(hints ? { hints } : {}),+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),+ ...linkAdvisory.links,+ };+ if (writeMdOutcome.outcome === 'both-kept') {+ respondBothKept(res, mode.handler, writeMdBody, writeMdOutcome);return;}- if (e instanceof AgentSessionCapacityError) {- respondAgentSessionCapacity(res, e, 'agent-write-md');- return;- }- log.error({ err: e, requestId: getRequestId(_req) }, '[agent-write-md] handler failed');- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {- handler: 'agent-write-md',- cause: e,- });+ successResponse(+ res,+ 200,+ AgentWriteMdSuccessSchema,+ { ...writeMdBody, ...writeMdOutcome },+ { handler: mode.handler },+ );+ });+ } catch (e) {+ if (e instanceof DocInConflictError) {+ respondDocInConflict(+ res,+ e,+ mode.handler,+ conflicts.findByDocName(stripDocExtension(e.file)),+ );+ return;+ }+ if (e instanceof ConcurrentOverwriteRefusedError) {+ respondConcurrentOverwriteRefused(res, e, mode.handler);+ return;+ }+ if (e instanceof FrontmatterMalformedError) {+ respondFrontmatterMalformed(res, e, mode.handler);+ return;+ }+ if (e instanceof AgentSessionCapacityError) {+ respondAgentSessionCapacity(res, e, mode.handler);+ return;+ }+ log.error({ err: e, requestId: getRequestId(_req) }, `[${mode.handler}] handler failed`);+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {+ handler: mode.handler,+ cause: e,+ });+ }+ }++ const acpDocumentWrite = withValidation(+ AcpDocumentWriteRequestSchema,+ async (req, res, body) => {+ if (!isAcpWritableDocument(body.docName, body.file)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `'${body.file}' is not a document OpenKnowledge keeps for the in-app agent.`,+ {+ handler: ACP_MARKDOWN_WRITE.handler,+ detail:+ 'The path is excluded from the project content, so there is no document to write it through. Nothing was written.',+ extensions: { outcome: 'refused', saved: false, nextStep: 'none' },+ },+ );+ return;}+ const { file: _file, ...write } = body;+ await writeAgentMarkdownDocument(+ req,+ res,+ { ...write, position: 'replace' },+ ACP_MARKDOWN_WRITE,+ );},- { handler: 'agent-write-md', method: 'POST' },+ { handler: ACP_MARKDOWN_WRITE.handler, method: 'POST', maxBodyBytes: Number.POSITIVE_INFINITY },);const handleFrontmatterPatch = withValidation(@@ -696,6 +804,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup}applied = true;}, session.origin);+ if (bodyMutated) durabilityState.markAgentWriteStore(resolvedDocName);},);} finally {@@ -818,11 +927,8 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup...(fmAdvisories.length > 0 ? { warnings: fmAdvisories } : {}),...linkAdvisory.links,};- const fmOutcome = reportedOutcome(- resolvedDocName,- outcomeOfSavedWrite(fmReconcile, fmFlushOutcome),- );- if (fmOutcome?.outcome === 'both-kept') {+ const fmOutcome = outcomeOfSavedWrite(fmReconcile, fmFlushOutcome);+ if (fmOutcome.outcome === 'both-kept') {respondBothKept(res, 'frontmatter-patch', fmBody, fmOutcome);return;}@@ -1013,6 +1119,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup...(changedBlocks !== undefined ? { changedBlocks } : {}),});}, session.origin);+ durabilityState.markAgentWriteStore(docName);if (patchDivergence !== undefined) {console.warn(JSON.stringify({@@ -1154,11 +1261,12 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),...linkAdvisory.links,};- const patchOutcome = reportedOutcome(- docName,- outcomeOfSavedWrite(patchReconcile, flushOutcome, patchDivergence !== undefined),+ const patchOutcome = outcomeOfSavedWrite(+ patchReconcile,+ flushOutcome,+ patchDivergence !== undefined,);- if (patchOutcome?.outcome === 'both-kept') {+ if (patchOutcome.outcome === 'both-kept') {respondBothKept(res, 'agent-patch', patchBody, patchOutcome);return;}@@ -1263,6 +1371,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupcount,);if (undone) {+ durabilityState.markAgentWriteStore(docName);recordContributor(docName,connectionId,@@ -1302,12 +1411,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupres,200,AgentUndoSuccessSchema,- {- docName,- scope,- undone,- ...reportedOutcome(docName, outcomeOfSavedWrite(undefined, undoFlushOutcome)),- },+ { docName, scope, undone, ...outcomeOfSavedWrite(undefined, undoFlushOutcome) },{ handler: 'agent-undo' },);} catch (e) {@@ -1657,6 +1761,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup'rollback',);}, ROLLBACK_ORIGIN);+ durabilityState.markAgentWriteStore(docName);if (rollbackDivergence !== undefined) {console.warn(JSON.stringify({@@ -1770,10 +1875,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup200,RollbackSuccessSchema,{- ...reportedOutcome(- docName,- outcomeOfSavedWrite(undefined, flushOutcome, rollbackDivergence !== undefined),- ),+ ...outcomeOfSavedWrite(undefined, flushOutcome, rollbackDivergence !== undefined),restoredFrom: commitSha,timestamp,...(summaryResponse ? { summary: summaryResponse } : {}),@@ -1790,7 +1892,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup},{ handler: 'rollback', method: 'POST' },);- return createApiRouteGroup(+ const group = createApiRouteGroup({'/api/agent-write-md': handleAgentWriteMd,'/api/frontmatter-patch': handleFrontmatterPatch,@@ -1812,4 +1914,5 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup],},);+ return { ...group, acpDocumentWrite };}diff --git a/packages/server/src/http/folder-template-routes.test.ts b/packages/server/src/http/folder-template-routes.test.tsindex b8c1a86c5..b172d2f46 100644--- a/packages/server/src/http/folder-template-routes.test.ts+++ b/packages/server/src/http/folder-template-routes.test.ts@@ -31,6 +31,7 @@ function buildGroup() {attributeOkArtifactWrite: () => {},scheduleOkArtifactFlush: () => {},flushDiskAndDetectOutcome: () => Promise.resolve(null),+ markAgentWriteStore: () => {},respondPersistenceFailure: () => {},respondStaleExternalWrite: () => {},registerWrittenDocInFileIndex: () => {},diff --git a/packages/server/src/http/folder-template-routes.ts b/packages/server/src/http/folder-template-routes.tsindex ce9b3347c..5b9f07412 100644--- a/packages/server/src/http/folder-template-routes.ts+++ b/packages/server/src/http/folder-template-routes.ts@@ -110,6 +110,7 @@ export interface FolderTemplateRouteDeps {) => void;scheduleOkArtifactFlush: (context: string) => void;flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;+ markAgentWriteStore: (docName: string) => void;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;registerWrittenDocInFileIndex: (docName: string, content: string) => void;@@ -157,6 +158,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRoattributeOkArtifactWrite,scheduleOkArtifactFlush,flushDiskAndDetectOutcome,+ markAgentWriteStore,respondPersistenceFailure,respondStaleExternalWrite,registerWrittenDocInFileIndex,@@ -697,6 +699,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRotemplateSession.dc.document.transact(() => {composeAndWriteRawBody(templateSession.dc.document, composed.content, 'agent');}, templateSession.origin);+ markAgentWriteStore(templateDocName);const templateFlush = await flushDiskAndDetectOutcome(templateDocName);if (@@ -1312,6 +1315,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRotemplateSession.dc.document.transact(() => {composeAndWriteRawBody(templateSession.dc.document, composed.content, 'agent');}, templateSession.origin);+ markAgentWriteStore(templateDocName);const templateFlush = await flushDiskAndDetectOutcome(templateDocName);if (diff --git a/packages/server/src/http/lint-write-routes.test.ts b/packages/server/src/http/lint-write-routes.test.tsindex fcd7e3ca4..773411bb6 100644--- a/packages/server/src/http/lint-write-routes.test.ts+++ b/packages/server/src/http/lint-write-routes.test.ts@@ -47,6 +47,7 @@ function buildGroup(overrides: Partial<Deps> = {}) {agentPresenceBroadcaster: undefined,buildAgentActor: notDispatched,flushDiskAndDetectOutcome: notDispatched,+ markAgentWriteStore: notDispatched,respondPersistenceFailure: notDispatched,respondStaleExternalWrite: notDispatched,flushDocToDisk: notDispatched,diff --git a/packages/server/src/http/lint-write-routes.ts b/packages/server/src/http/lint-write-routes.tsindex e17b79b86..60171e0ee 100644--- a/packages/server/src/http/lint-write-routes.ts+++ b/packages/server/src/http/lint-write-routes.ts@@ -103,6 +103,7 @@ export interface LintWriteRouteDeps {label?: string;};flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;+ markAgentWriteStore: (docName: string) => void;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;flushDocToDisk: (docName: string, label: string) => void;@@ -128,6 +129,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {agentPresenceBroadcaster,buildAgentActor,flushDiskAndDetectOutcome,+ markAgentWriteStore,respondPersistenceFailure,respondStaleExternalWrite,flushDocToDisk,@@ -364,6 +366,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {suppliedWriterId,);}, session.origin);+ markAgentWriteStore(resolvedDocName);if (actor.kind !== 'anonymous') {recordContributor(diff --git a/packages/server/src/http/request-validation.ts b/packages/server/src/http/request-validation.tsindex ea61963dd..5b14ed1c1 100644--- a/packages/server/src/http/request-validation.ts+++ b/packages/server/src/http/request-validation.ts@@ -11,9 +11,9 @@ const MAX_BODY_BYTES = 1_048_576;const REQUEST_BODY_TIMEOUT_MS = 30_000;-function readRequestBody(req: IncomingMessage): Promise<Buffer> {+function readRequestBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {return readBoundedJsonBody(req, {- maxBytes: MAX_BODY_BYTES,+ maxBytes,timeoutMs: REQUEST_BODY_TIMEOUT_MS,});}@@ -111,6 +111,7 @@ export interface WithValidationOptions {skipBodyParse?: boolean;method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';preBodyGate?: (req: IncomingMessage, res: ServerResponse) => boolean;+ maxBodyBytes?: number;}export function validateBody<T>(@@ -182,7 +183,7 @@ export function withValidation<T>(let raw: Buffer;try {- raw = await readRequestBody(req);+ raw = await readRequestBody(req, options.maxBodyBytes ?? MAX_BODY_BYTES);} catch (err) {if (err instanceof UnsupportedMediaTypeError) {respondUnsupportedMediaType(res, options.handler);diff --git a/packages/server/src/http/skills-document-routes.test.ts b/packages/server/src/http/skills-document-routes.test.tsindex c6b9326ce..e4440a70d 100644--- a/packages/server/src/http/skills-document-routes.test.ts+++ b/packages/server/src/http/skills-document-routes.test.ts@@ -30,6 +30,7 @@ function buildGroup() {}),sessionManager: new AgentSessionManager(new Hocuspocus({ quiet: true })),flushDiskAndDetectOutcome: () => Promise.resolve(null),+ markAgentWriteStore: () => {},respondStaleExternalWrite: () => {},respondPersistenceFailure: () => {},okArtifactKey: () => '',diff --git a/packages/server/src/http/skills-document-routes.ts b/packages/server/src/http/skills-document-routes.tsindex 051eb1d50..e8a97ccf9 100644--- a/packages/server/src/http/skills-document-routes.ts+++ b/packages/server/src/http/skills-document-routes.ts@@ -39,7 +39,6 @@ import {type AgentWriteFlushOutcome,answeredWithSuccessOnAppRoutes,outcomeOfSavedWrite,- reportedOutcome,} from '../agent-write-outcome.ts';import { composeAndWriteRawBody } from '../bridge-intake.ts';import { isLinkIndexExcludedDoc } from '../cc1-broadcast.ts';@@ -165,6 +164,7 @@ export interface SkillsDocumentRouteDeps {sessionManager: AgentSessionManager;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;+ markAgentWriteStore: (docName: string) => void;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;okArtifactKey: (kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',@@ -237,6 +237,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoextractAgentIdentity,sessionManager,flushDiskAndDetectOutcome,+ markAgentWriteStore,respondStaleExternalWrite,respondPersistenceFailure,okArtifactKey,@@ -586,6 +587,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo200,SkillPutSuccessSchema,{+ ...outcomeOfSavedWrite(undefined, null),path: `${homeRel}/${body.name}/SKILL.md`,created: true,warnings: wr.warnings,@@ -619,6 +621,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRosession.dc.document.transact(() => {composeAndWriteRawBody(session.dc.document, composed.content, 'agent');}, session.origin);+ markAgentWriteStore(docName);const flushOutcome = await flushDiskAndDetectOutcome(docName);if (@@ -648,7 +651,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo200,SkillPutSuccessSchema,{- ...reportedOutcome(docName, outcomeOfSavedWrite(undefined, flushOutcome)),+ ...outcomeOfSavedWrite(undefined, flushOutcome),path: relPath,created,warnings: composed.warnings,diff --git a/packages/server/src/http/skills-file-routes.test.ts b/packages/server/src/http/skills-file-routes.test.tsindex 821a541b4..47bb3e96f 100644--- a/packages/server/src/http/skills-file-routes.test.ts+++ b/packages/server/src/http/skills-file-routes.test.ts@@ -30,6 +30,7 @@ function buildGroup() {}),sessionManager: new AgentSessionManager(new Hocuspocus({ quiet: true })),flushDiskAndDetectOutcome: () => Promise.resolve(null),+ markAgentWriteStore: () => {},respondStaleExternalWrite: () => {},respondPersistenceFailure: () => {},okArtifactKey: () => '',diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.tsindex b699b5543..4c718af8f 100644--- a/packages/server/src/http/skills-file-routes.ts+++ b/packages/server/src/http/skills-file-routes.ts@@ -19,7 +19,6 @@ import {type AgentWriteFlushOutcome,answeredWithSuccessOnAppRoutes,outcomeOfSavedWrite,- reportedOutcome,} from '../agent-write-outcome.ts';import { composeAndWriteRawBody } from '../bridge-intake.ts';import type { RemovalLifecycleStatus } from '../conflict-kinds.ts';@@ -99,6 +98,7 @@ export interface SkillsFileRouteDeps {sessionManager: AgentSessionManager;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;+ markAgentWriteStore: (docName: string) => void;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;okArtifactKey: (kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',@@ -193,6 +193,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroupextractAgentIdentity,sessionManager,flushDiskAndDetectOutcome,+ markAgentWriteStore,respondStaleExternalWrite,respondPersistenceFailure,attributeOkArtifactWrite,@@ -411,7 +412,6 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroupreturn;const routedThroughContent = isProjectMdReference(body.scope, kind, rel);let fileFlushOutcome: AgentWriteFlushOutcome = null;- let fileDocName: string | undefined;let created: boolean;if (routedThroughContent) {@@ -420,7 +420,6 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup* (precedent #24 / #38), the same branch as the SKILL.md body.*/const refDocName = `${skillDirRel}/${rel.replace(/\.mdx?$/i, '')}`;- fileDocName = refDocName;if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;created = !existsSync(resolve(skillDirAbs, rel));if (created && countBundleFiles(skillDirAbs) >= BUNDLE_MAX_FILES) {@@ -444,6 +443,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroupsession.dc.document.transact(() => {composeAndWriteRawBody(session.dc.document, body.content, 'agent');}, session.origin);+ markAgentWriteStore(refDocName);const flushOutcome = await flushDiskAndDetectOutcome(refDocName);fileFlushOutcome = flushOutcome;if (@@ -505,9 +505,7 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup200,SkillFilePutSuccessSchema,{- ...(fileDocName === undefined- ? outcomeOfSavedWrite(undefined, fileFlushOutcome)- : reportedOutcome(fileDocName, outcomeOfSavedWrite(undefined, fileFlushOutcome))),+ ...outcomeOfSavedWrite(undefined, fileFlushOutcome),path: rel,created,kind,diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.tsindex 8f583bc96..312835ad3 100644--- a/packages/server/src/managed-artifact-persistence.test.ts+++ b/packages/server/src/managed-artifact-persistence.test.ts@@ -269,11 +269,19 @@ describe('store/load round-trip', () => {expect(readFileSync(managedArtifactAbsPath(docName, ctx), 'utf-8')).toBe(awkward);});- test('store is a no-op for the load/reconcile origin', async () => {+ test('a store after an outside version was taken in writes nothing, and drops the write when that version is not on disk yet', async () => {const ctx = makeCtx();const doc = new Y.Doc();doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');- expect(await storeManagedArtifactDoc(doc, docName, FILE_WATCHER_ORIGIN, ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, docName, FILE_WATCHER_ORIGIN, ctx)).toBe(+ 'dropped-intake-landed',+ );+ expect(existsSync(managedArtifactAbsPath(docName, ctx))).toBe(false);++ ctx.lkgCache.set(docName, SRC);+ expect(await storeManagedArtifactDoc(doc, docName, FILE_WATCHER_ORIGIN, ctx)).toBe(+ 'outside-taken-in',+ );expect(existsSync(managedArtifactAbsPath(docName, ctx))).toBe(false);});@@ -284,7 +292,9 @@ describe('store/load round-trip', () => {const doc = new Y.Doc();doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');- expect(await storeManagedArtifactDoc(doc, projectDocName, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, projectDocName, 'agent', ctx)).toBe(+ 'dropped-legacy-name',+ );expect(existsSync(projectPath)).toBe(false);mkdirSync(resolve(projectPath, '..'), { recursive: true });@@ -301,7 +311,9 @@ describe('store/load round-trip', () => {const doc = new Y.Doc();doc.transact(() => doc.getText('source').insert(0, SRC), 'agent');- expect(await storeManagedArtifactDoc(doc, templateDocName, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, templateDocName, 'agent', ctx)).toBe(+ 'dropped-legacy-name',+ );const fresh = new Y.Doc();expect(() => loadManagedArtifactDoc(fresh, templateDocName, ctx)).not.toThrow();@@ -1040,7 +1052,7 @@ describe('__extskill__ editable-unmanaged skill — guarded external write-back'loadManagedArtifactDoc(doc, docName, ctx);expect(doc.getText('source').length).toBe(0);doc.transact(() => doc.getText('source').insert(0, 'edit'), 'agent');- expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('dropped-unresolvable');});test('load seeds from the real harness file; store writes back byte-identical', async () => {@@ -1128,7 +1140,9 @@ describe('a skill doc never RESURRECTS a bundle that is gone', () => {rmSync(bundleDir, { recursive: true, force: true });editLive(doc, '---\nname: code-mode\n---\n\n# Code mode edited\n');- expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe(+ 'dropped-container-gone',+ );expect(existsSync(bundleDir)).toBe(false);});@@ -1142,7 +1156,9 @@ describe('a skill doc never RESURRECTS a bundle that is gone', () => {rmSync(bundleDir, { recursive: true, force: true });editLive(doc, '# Patterns edited\n');- expect(await storeManagedArtifactDoc(doc, fileDoc, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, fileDoc, 'agent', ctx)).toBe(+ 'dropped-container-gone',+ );expect(existsSync(bundleDir)).toBe(false);});@@ -1189,7 +1205,9 @@ describe('the liveness rule covers external skills too', () => {rmSync(dir, { recursive: true, force: true });editLive(doc, '---\nname: borrowed\n---\n\n# Resurrected\n');- expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe('no-op');+ expect(await storeManagedArtifactDoc(doc, docName, 'agent', ctx)).toBe(+ 'dropped-container-gone',+ );expect(existsSync(dir)).toBe(false);} finally {unregisterExternalSkill('borrowed');diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.tsindex cd567632b..46a59102b 100644--- a/packages/server/src/managed-artifact-persistence.ts+++ b/packages/server/src/managed-artifact-persistence.ts@@ -79,10 +79,18 @@ export interface ManagedArtifactCtx {type SettledMergeOutcome = Exclude<ManagedArtifactMergeOutcome, 'held'>;+export type ManagedArtifactDrop =+ | 'dropped-legacy-name'+ | 'dropped-unresolvable'+ | 'dropped-container-gone'+ | 'dropped-intake-landed';+export type StoreManagedArtifactOutcome =| 'persisted'| 'no-op'| 'write-failed'+ | 'outside-taken-in'+ | ManagedArtifactDrop| SettledMergeOutcome| SaveHold;@@ -99,6 +107,11 @@ export function storeManagedArtifactWroteFile(outcome: StoreManagedArtifactOutcocase 'write-failed':case 'applied':case 'unchanged':+ case 'outside-taken-in':+ case 'dropped-legacy-name':+ case 'dropped-unresolvable':+ case 'dropped-container-gone':+ case 'dropped-intake-landed':return false;default:return assertNeverStoreOutcome(outcome);@@ -501,25 +514,32 @@ export async function storeManagedArtifactDoc(ctx: ManagedArtifactCtx,): Promise<StoreManagedArtifactOutcome> {const parsedStore = parseManagedArtifactName(documentName);- if (parsedStore?.kind === 'skill' && parsedStore.scope === 'project') return 'no-op';+ if (parsedStore?.kind === 'skill' && parsedStore.scope === 'project') {+ return 'dropped-legacy-name';+ }- if (documentName.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) return 'no-op';+ if (documentName.startsWith(MANAGED_ARTIFACT_PREFIX_TEMPLATE)) return 'dropped-legacy-name';const extStore = parseExternalSkillDocName(documentName);- if (extStore && externalSkillAbsPath(extStore.name, extStore.rel) === null) return 'no-op';+ if (extStore && externalSkillAbsPath(extStore.name, extStore.rel) === null) {+ return 'dropped-unresolvable';+ }- if (lastTransactionOrigin === FILE_WATCHER_ORIGIN) return 'no-op';+ const current = document.getText('source').toString() === ctx.lkgCache.get(documentName);+ if (lastTransactionOrigin === FILE_WATCHER_ORIGIN) {+ return current ? 'outside-taken-in' : 'dropped-intake-landed';+ }- if (document.getText('source').toString() === ctx.lkgCache.get(documentName)) return 'no-op';+ if (current) return 'no-op';const containerDir = managedArtifactContainerDir(documentName, ctx);- if (containerDir === null) return 'no-op';+ if (containerDir === null) return 'dropped-unresolvable';if (!existsSync(containerDir)) {log.warn({ documentName, containerDir },'store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it',);- return 'no-op';+ return 'dropped-container-gone';}const filePath = managedArtifactAbsPath(documentName, ctx);diff --git a/packages/server/src/mcp/tools/description-contract.uncached.test.ts b/packages/server/src/mcp/tools/description-contract.uncached.test.tsindex 157a953d9..0c39c6738 100644--- a/packages/server/src/mcp/tools/description-contract.uncached.test.ts+++ b/packages/server/src/mcp/tools/description-contract.uncached.test.ts@@ -26,6 +26,7 @@ import {OK_STORE_DISCARDED,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_DROPPED,OK_WRITE_REPLACED,type StoreFailure,} from '../../document-durability-state.ts';@@ -409,7 +410,20 @@ const SERVER_FIELDS_FOR_GUIDED_RESULT: Readonly<Record<string, AgentWriteOutcomemessage: 'm',held: { reason: 'pending-intake-failed-no-base', noBase: true },}),+ '`save-held` (503) with `pending-not-utf8`': held('pending-not-utf8'),'`save-held` (503) with any other `reason`': held('pending-unreadable'),+ '`write-dropped` (409) for a name with no file of its own': outcomeOfStoreFailure({+ code: OK_WRITE_DROPPED,+ message: 'm',+ dropped: 'legacy-name',+ }),+ '`write-dropped` (409) while an outside change was being taken in': outcomeOfStoreFailure({+ code: OK_WRITE_DROPPED,+ message: 'm',+ dropped: 'intake-landed',+ }),+ '`write-dropped` (409) for a skill folder that is gone or a path that does not resolve':+ outcomeOfStoreFailure({ code: OK_WRITE_DROPPED, message: 'm', dropped: 'container-gone' }),'`doc-moved` (409)': outcomeOfStoreFailure({ code: OK_DOC_MOVED, message: 'm' }),'`branch-switched` (409)': outcomeOfStoreFailure({ code: OK_STORE_DISCARDED, message: 'm' }),'`doc-removed` (409) after a rename': outcomeOfStoreFailure({diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex 446dff2ca..10bd98060 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -80,14 +80,17 @@ import {type DeferredStoreOutcome,type DeferredStoreSettlement,DocumentDurabilityState,+ type HeldSaveReason,OK_DOC_REMOVED,OK_PATH_UNRESOLVABLE,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_DROPPED,type StoreFailure,type StoreFailureRemoval,type StoreIntakeMerge,type StorePublishOutcome,+ type WriteDropCause,writtenThroughOf,} from './document-durability-state.ts';import { refuseStaleExternalWrite } from './external-change.ts';@@ -114,6 +117,7 @@ import {import {loadManagedArtifactDoc,type ManagedArtifactCtx,+ type ManagedArtifactDrop,managedArtifactContributorAttribution,managedArtifactTimelinePaths,type StoreManagedArtifactOutcome,@@ -228,9 +232,14 @@ function managedArtifactSettlement(case 'applied':return 'resolved';case 'no-op':+ case 'outside-taken-in':+ case 'dropped-legacy-name':+ case 'dropped-unresolvable':+ case 'dropped-container-gone':return retry ? 'resolved' : 'neutral';case 'unchanged':case 'write-failed':+ case 'dropped-intake-landed':return 'neutral';default:return assertNeverStoreOutcome(outcome);@@ -299,6 +308,50 @@ const STORE_PENDING_DESCRIPTIONS: Readonly<Record<StorePendingReason, string>> ='pending-conflict': 'its file changed and could not be merged, so a conflict was raised',};+const OUTSIDE_STORE_HOLDS: Readonly<+ Record<SaveHold['cause'], { readonly reason: HeldSaveReason; readonly description: string }>+> = {+ unreadable: {+ reason: 'pending-unreadable',+ description: STORE_PENDING_DESCRIPTIONS['pending-unreadable'],+ },+ 'keeps-changing': {+ reason: 'pending-exhausted',+ description: STORE_PENDING_DESCRIPTIONS['pending-exhausted'],+ },+ 'edits-changing': {+ reason: 'pending-exhausted',+ description: 'its edits kept changing while it was being saved',+ },+ 'no-history-or-backup': {+ reason: 'pending-no-history-or-backup',+ description:+ 'its file changed outside and that version could be saved neither to history nor to the backup folder',+ },+ 'not-utf8': {+ reason: 'pending-not-utf8',+ description: 'its file changed outside to bytes that are not UTF-8 text',+ },+};++const OUTSIDE_STORE_DROPS: Readonly<+ Record<ManagedArtifactDrop, { readonly cause: WriteDropCause; readonly description: string }>+> = {+ 'dropped-legacy-name': { cause: 'legacy-name', description: 'this name has no file of its own' },+ 'dropped-unresolvable': {+ cause: 'unresolvable',+ description: 'its file path could not be resolved',+ },+ 'dropped-container-gone': {+ cause: 'container-gone',+ description: 'its skill folder is gone (deleted or moved)',+ },+ 'dropped-intake-landed': {+ cause: 'intake-landed',+ description: 'an outside change to its file was being taken in when the save ran',+ },+};+function assertNeverStoreIntake(intake: never): never {throw new Error(`unhandled store intake result: ${(intake as { kind: string }).kind}`);}@@ -2698,6 +2751,7 @@ export function createPersistenceExtension(options: PersistenceOptions): Persist}return;}+ const agentTriggered = durabilityState.consumeAgentWriteStore(documentName);if (isManagedArtifactDoc(documentName)) {const outcome = await storeManagedArtifactDoc(document,@@ -2705,6 +2759,7 @@ export function createPersistenceExtension(options: PersistenceOptions): PersistlastTransactionOrigin,managedArtifactCtx,);+ if (agentTriggered) recordOutsideStoreForAgentWrite(document, documentName, outcome);settleHeldSave(documentName, managedArtifactSettlement(outcome, retry));if (storeManagedArtifactWroteFile(outcome)) {const writer = resolveWriterFromOrigin(lastTransactionOrigin, getPrincipal);@@ -2736,9 +2791,63 @@ export function createPersistenceExtension(options: PersistenceOptions): PersistlastTransactionOrigin,mermaidPersistenceCtx,);+ if (agentTriggered) recordOutsideStoreForAgentWrite(document, documentName, outcome);settleHeldSave(documentName, enginelessSettlement(outcome, retry));}+ function recordOutsideStoreForAgentWrite(+ document: Y.Doc,+ documentName: string,+ outcome: StoreMermaidOutcome | StoreManagedArtifactOutcome,+ ): void {+ if (typeof outcome === 'object') {+ const hold = OUTSIDE_STORE_HOLDS[outcome.cause];+ durabilityState.recordStoreFailure(documentName, {+ code: OK_STORE_HELD,+ message: `${documentName} was not saved: ${hold.description}`,+ held: { reason: hold.reason },+ });+ return;+ }+ switch (outcome) {+ case 'persisted':+ case 'no-op':+ case 'unchanged':+ return;+ case 'applied':+ case 'outside-taken-in':+ durabilityState.recordStoreIntake(documentName, 'clean', writtenThroughOf(document));+ return;+ case 'dropped-legacy-name':+ case 'dropped-unresolvable':+ case 'dropped-container-gone':+ case 'dropped-intake-landed': {+ const drop = OUTSIDE_STORE_DROPS[outcome];+ durabilityState.recordStoreFailure(documentName, {+ code: OK_WRITE_DROPPED,+ message: `${documentName} was not saved: ${drop.description}`,+ dropped: drop.cause,+ });+ return;+ }+ case 'merged':+ case 'both-kept':+ durabilityState.recordStoreIntake(documentName, outcome, writtenThroughOf(document));+ return;+ case 'kept-live':+ case 'stash-fallback':+ durabilityState.recordStoreIntake(documentName, 'kept-live', writtenThroughOf(document));+ return;+ case 'write-failed':+ durabilityState.recordStoreFailure(documentName, {+ message: `${documentName} was not saved: its file could not be written`,+ });+ return;+ default:+ assertNeverStoreOutcome(outcome);+ }+ }+async function retryHeldSave(document: Y.Doc, documentName: string): Promise<void> {if (!isConfigDoc(documentName) &&diff --git a/packages/server/src/save-version.test.ts b/packages/server/src/save-version.test.tsindex f475da8b7..450c3640e 100644--- a/packages/server/src/save-version.test.ts+++ b/packages/server/src/save-version.test.ts@@ -274,6 +274,7 @@ describe('PRD-6716: save-version + rollback do not mutate parent git', () => {unloadDocument: async () => {},debouncer: {isDebounced: () => false,+ isCurrentlyExecuting: () => false,executeNow: async () => undefined,},};