Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-9772 Report outcome, saved flag and next step on agent writes (#7218)
mike-inkeep454caa67c321
diff --git a/.changeset/agent-write-outcome.md b/.changeset/agent-write-outcome.mdnew file mode 100644index 000000000..817181a20--- /dev/null+++ b/.changeset/agent-write-outcome.md@@ -0,0 +1,5 @@+---+'@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.diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex dd38fa06d..f45db7551 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -48,7 +48,7 @@ The write verbs nest their result under the same target key you wrote, mirroring## Advisory warnings-`write` and `edit` results may carry a `warnings` array on the document entry (per entry for a batch); `restore_version` carries it at the top level. Entries are discriminated by `kind`. `content-divergence` and `disk-edit-reconciled` are write-integrity signals — the stored doc differs from what the call composed, so re-read it before editing further. A `disk-edit-reconciled` entry carries `mergeOutcome`, one of `clean` (the outside edit was taken as is), `merged` (both sides' edits were merged), `both-kept` or `kept-live`. `both-kept` means an outside edit and edits made in OpenKnowledge changed the same blocks, and three counts say what landed: `duplicatedBlocks` blocks are in the document twice, the OpenKnowledge version first and the outside version directly under it; `restoredDeletedHere` blocks deleted in OpenKnowledge came back with the outside version because the outside edit changed them; `restoredDeletedOutside` blocks the outside edit deleted stayed with the OpenKnowledge version because they were changed there. `kept-live` means the outside edit could not be merged, so the OpenKnowledge version stayed and the outside version was saved to the document's history. Those two outcomes also carry `nextStep: "re-read"`. In both the write landed and should not be retried; after `both-kept`, remove a duplicate, or delete a block restored over a deletion in OpenKnowledge, with an ordinary edit if the task calls for it. `mergeOutcome` and `nextStep` can gain values; treat a value you do not know like `merged`: the write landed, re-read the document. `mermaid-parse-error` means the write landed but that fence won't render — fix the fence and re-edit. `lint-violation` reports a content-rule finding at a line and column. `link-check-deferred` means the server was still building its link index after starting, or the index was busy with other writes, so links were not checked and an empty `brokenLinks` is not an all-clear; that document's links are checked again only when it is written or edited later, or by an `audit`, which can time out until startup finishes.+`write` and `edit` results may carry a `warnings` array on the document entry (per entry for a batch); `restore_version` carries it at the top level. Entries are discriminated by `kind`. `content-divergence` and `disk-edit-reconciled` are write-integrity signals — the stored doc differs from what the call composed, and the result's `nextStep` is `re-read`: re-read it before editing further. A `disk-edit-reconciled` entry carries `mergeOutcome`, one of `clean` (the outside edit was taken as is), `merged` (both sides' edits were merged), `both-kept` or `kept-live`. `both-kept` means an outside edit and edits made in OpenKnowledge changed the same blocks, and three counts say what landed: `duplicatedBlocks` blocks are in the document twice, the OpenKnowledge version first and the outside version directly under it; `restoredDeletedHere` blocks deleted in OpenKnowledge came back with the outside version because the outside edit changed them; `restoredDeletedOutside` blocks the outside edit deleted stayed with the OpenKnowledge version because they were changed there. `kept-live` means the outside edit could not be merged, so the OpenKnowledge version stayed and the outside version was saved to the document's history. What to do next is the result's `outcome` and `nextStep` (see [Write outcomes](#write-outcomes)); `mergeOutcome` can gain values, and one you do not know means the same as `merged`. `mermaid-parse-error` means the write landed but that fence won't render — fix the fence and re-edit. `lint-violation` reports a content-rule finding at a line and column. `link-check-deferred` means the server was still building its link index after starting, or the index was busy with other writes, so links were not checked and an empty `brokenLinks` is not an all-clear; that document's links are checked again only when it is written or edited later, or by an `audit`, which can time out until startup finishes.`delete`, `move` and `install` on a `skill` target carry a separate `warnings` array of plain strings, not `kind`-discriminated entries. It reports work that did not undo the operation: bookkeeping records the server could not update after the skill itself was already deleted, renamed or moved, and — on a delete — that the directory removed was one an earlier failed move had retained for recovery. The operation succeeded; the warning names what to check or repair.@@ -100,9 +100,58 @@ Template metadata/body edits and skill description/body edits through MCP resubmMCP `write({ documents: [...] })` writes entries sequentially and returns ordered results with an overall tool error if any fails. Successful entries before and after a refused entry stay written. MCP `skill.files` similarly aggregates sequential per-file outcomes. Retry only failed entries after correcting the input; do not resend successful siblings.-## Conflict-aware writes--A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OpenKnowledge's own reconciliation of the editor against disk. Reconciliation covers `stale-external-write`, which protects an acknowledged edit when another app restores the exact older file version, even with GitHub sync disabled. Every mutating tool (`write`, `edit`, `delete`, `move`, `restore_version`, and agent undo) refuses a conflicted doc with an RFC 9457 problem response (409) that names the kind and the strategies that apply to it:+## 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.++| Outcome | What happened | `saved` | What to do |+| --- | --- | --- | --- |+| Applied (`applied`) | The write landed and is saved. | `true` | Carry on; with a `content-divergence` warning, `nextStep` is `re-read`, so re-read first. |+| Merged first (`merged-first`) | An outside change to the file was handled before the write was saved: merged in, or, when it could not be merged, saved to the document's history. The write landed. | `true` | Re-read before the next edit. Never repeat the write. |+| Both kept (`both-kept`) | The write landed and is saved, and for a block changed both in OpenKnowledge and outside, both versions are in the document, the OpenKnowledge version first and the outside version directly under it. | `true` | Never repeat the write. Re-read, and remove the duplicate with an ordinary edit if the task calls for it. |+| Refused (`refused`) | Not saved. OpenKnowledge saves it only after someone acts: the agent, as `nextStep` says, or the user. | `false` | Follow `nextStep`. |+| Projection held (`projection-held`) | The write is in the document but not yet in its file, and OpenKnowledge saves it on its own. On OpenKnowledge Cloud the same outcome means the file projection of the document is held. | `false` | Never repeat the write. Re-read before the next edit. |++`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).++`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.++## Refusals and held saves++Every result an agent write can come back with, its fields, and the move they ask for. The bundled skill carries the same table, and a test checks both against the server's mapping.++| Result | `outcome` | `saved` | `nextStep` | Your move |+| - | - | - | - | - |+| `both-kept` (409) | `both-kept` | `true` | `re-read` | Never repeat the write. Re-read, and remove the duplicate with an ordinary edit if your task calls for it. |+| `applied` (200) with a `content-divergence` warning | `applied` | `true` | `re-read` | The write landed and is saved, but the stored text differs from what you sent. Re-read before the next edit. |+| `concurrent-overwrite-refused` (409) | `refused` | `false` | `retry` | Wait the seconds `retryAfterSeconds` names, then send the write again; an `append` or `prepend` is never refused this way. |+| `too-many-agent-sessions` (503) | `refused` | `false` | `retry` | Wait the seconds it names, then send the write again. |+| `doc-not-found` (404) | `refused` | `false` | `retry` | Send the edit again at the path the detail or `candidates` names. |+| `reserved-doc-name` (400) | `refused` | `false` | `retry` | Send the write again under a different name. |+| `frontmatter-malformed` (400) | `refused` | `false` | `retry` | Fix the YAML the detail points at, then send the write again. |+| `frontmatter-edit-not-supported` (400) | `refused` | `false` | `retry` | Send the frontmatter change again as a frontmatter patch. |+| `invalid-frontmatter-patch` (400) | `refused` | `false` | `retry` | Correct the patch the detail describes, then send it again. |+| `target-not-found` (404) | `refused` | `false` | `re-read` | Re-read the document, then make the edit against text that is there. |+| `stale-target` (409) | `refused` | `false` | `re-read` | Re-read the document, then make the edit against what is there now. |+| `doc-in-conflict` (409) | `refused` | `false` | `none` | Tell the user which file it is. Write to it again only after they say the conflict is resolved. |+| `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 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. |+| `doc-removed` (409) after a rename | `refused` | `false` | `re-read` | Re-read the document at the new path the detail names, and re-apply your change there if it is missing. |+| `doc-removed` (409) after a delete | `refused` | `false` | `none` | Tell the user the file is gone; the edit is in the document's history (timeline). Do not re-create the document on your own. |+| `server-stopped` (503) | `refused` | `false` | `none` | Tell the user; after the restart the edit is in the document's history (timeline). |+| `server-stopped` (503) during a move | `refused` | `false` | `re-read` | After the restart, re-read the document at the new name the detail gives, and re-apply the edit only if it is missing. |+| `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. |+| `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:```json{@@ -111,40 +160,44 @@ A doc can land in conflict through a Git merge, a pull that collides with a loca"status": 409,"detail": "The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.","file": "notes/sso.md",- "conflict": { "kind": "reconcile", "reason": "disk-markers" },- "resolutionOptions": ["mine", "content", "delete"]+ "conflict": { "kind": "merge-native" },+ "outcome": "refused",+ "saved": false,+ "nextStep": "none"}```-A write that first detects the stale file during its final disk flush returns a different 409, `urn:ok:error:stale-external-write`. The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Ask the user to resolve the conflict, then re-read the document. Do not repeat the operation: compare the resolved content with the intended result and make only any remaining edit.+The `detail` asks the user to resolve the conflict; `nextStep: none` governs what the agent does: tell the user, and write again only after they say it is resolved.-When 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 succeeds and the file holds both edits; re-read the document before editing it further. 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. The stale-external-write case above is the exception: when the file holds a version that an earlier agent write replaced, the write returns that 409 instead. If a Markdown save cannot finish safely, the write returns `urn:ok:error:save-held` (503). The body carries `reason` (what holds the save), `retryWhen` (what the server's own save waits for; it is never a cue to repeat the request) and `nextStep: re-read`; in a batch response the same fields appear on that entry's `error`. When the file cannot be read (`pending-unreadable`, with the errno in `causeCode`), keeps changing (`pending-exhausted`, `pending-base-moved`) or the outside change could not be merged (`pending-intake-failed`), the next edit or the idle save within a few minutes saves it (`retryWhen: next-save`). When OpenKnowledge has no agreed version of the file to merge with (`pending-intake-failed-no-base`, or any hold on such a document), the edit is not saved: the next edit to the document replaces it with the file on disk and moves the held edit to the document history (`retryWhen: replaced-on-next-edit`); re-read after that and re-apply the edit if it is still needed. When merging raised a conflict (`pending-conflict`), it is saved after the user resolves the conflict in the app (`conflict-resolved`). In every case, do not repeat the write now: re-read the document before editing it further.+A write that finds another app has put back an older copy of the file, one an earlier write already replaced, returns `urn:ok:error:stale-external-write` (409, `refused`, `nextStep: none`): the edit is kept in the document and the recovery snapshot, but its save is blocked. Do not repeat the write: tell the user which file it is.-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.+When 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.-`conflict.kind` says where the conflict came from, and the kind decides what a resolve does. `merge-native` is a git merge that left unmerged stages in the index. Resolving one stages your choice with git and commits the merge once no `merge-native` conflict is left. `working-tree` is a pull-only overlay collision, pinned to the origin blob it hit. `reconcile` is OpenKnowledge's own three-way merge of the editor against disk, including protected stale saves; no git object holds those stages, so OpenKnowledge snapshots them when it detects the conflict. Resolving a `working-tree` or `reconcile` conflict commits nothing.+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.-A `reconcile` conflict also carries a `reason`: `refused-conflict-markers`, `refused-no-base`, `refused-too-large`, `disk-markers`, or `stale-external-write`; `merged-with-markers` appears only on entries recorded by earlier versions, or when both kept versions could not be applied to the open document. On `stale-external-write` the compatibility field `conflictKind` is `stale-external-write`. Every other row uses `conflictKind: "git"`. An outside edit to the same block as unsaved edits is not a conflict: both versions are kept in the document. `refused-too-large` means a merge past the size cap or one that failed OpenKnowledge's fidelity check, and is raised only when the outside version could not be saved to history; otherwise the OpenKnowledge version stays and the outside version goes to the document's history. The server log names the failed check.+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.++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 document whose file was deleted, renamed or moved on disk returns `urn:ok:error:doc-removed` (409): 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, re-create the document with `write` if you still want the content. 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. 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.+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.-When OpenKnowledge follows a rename or move made outside the app, it carries the document's text, with every edit it already held, to the new name. A write whose disk save was still pending waits for that to finish, then returns `urn:ok:error:doc-moved` (409) if its edit was carried, and the `detail` names the new name: the edit is saved there, so do not repeat it; re-read the document at its new name. If the edit was not carried, the write returns `urn:ok:error:doc-removed` as described above. Waiting for the carry counts toward the same 20 seconds as the rest of the write. If the carry has not finished when they run out, the write returns success before its disk save and no error follows: the edit goes wherever the carry takes it, to the new name or, if the carry fails, to the document's history. Re-read the document at its new name to confirm. While the file of an open document is missing, OpenKnowledge holds the document for a re-check of the folder, in case the file was moved rather than deleted, and a write's disk save waits up to 20 seconds for that to settle. If OpenKnowledge then follows a move, the write returns `urn:ok:error:doc-moved` or `urn:ok:error:doc-removed` by the same rule. If the delete stands, the write returns `urn:ok:error:doc-removed` (409) and the `detail` says the edit went to the document's history, not to disk; re-create the document with `write` if you still want the content. If OpenKnowledge stops while the file is still missing, the write returns `urn:ok:error:server-stopped` (503) and the edit is in the document's history. A hold can last up to 30 seconds. If it is still unresolved when the write's 20 seconds run out, the write returns success before its disk save, so that success does not confirm the edit is on disk: the edit goes wherever the hold resolves, to the new name or to the document's history, and no error follows. Re-read the document to confirm, and if it is gone, look for it under a new name or in its history.+When OpenKnowledge follows a rename or move made outside the app, it carries the document's text, with every edit it already held, to the new name. A write whose disk save was still pending waits for that to finish, then returns `urn:ok:error:doc-moved` (409, `projection-held`) if its edit was carried, and the `detail` names the new name: OpenKnowledge saves the edit there (`saved` is `false` until it has), so do not repeat it; re-read the document at its new name. If the edit was not carried, the write returns `urn:ok:error:doc-removed` as described above. Waiting for the carry counts toward the same 20 seconds as the rest of the write; if the carry has not finished when they run out, the write returns `save-held` with `pending-rename`, whose `detail` names the new name, and the edit goes wherever the carry takes it, to the new name or, if the carry fails, to the document's history. Re-read it at the new name; do not re-create the document under its old one. While the file of an open document is missing, OpenKnowledge holds the document for a re-check of the folder, in case the file was moved rather than deleted, and a write's disk save waits up to 20 seconds for that to settle. If OpenKnowledge then follows a move, the write returns `urn:ok:error:doc-moved` or `urn:ok:error:doc-removed` by the same rule. If the delete stands, the write returns `urn:ok:error:doc-removed` (409) and the `detail` says the edit went to the document's history, not to disk; tell the user. If OpenKnowledge stops while the file is still missing, the write returns `urn:ok:error:server-stopped` (503, `refused`, `nextStep: none`) and the edit is in the document's history. If it stops while a move is being carried, the same answer names the new name and says `nextStep: re-read`: after OpenKnowledge restarts, re-read the document there and re-apply the edit only if it is missing. A hold can last up to 30 seconds; if it is still unresolved when the write's 20 seconds run out, the write returns `save-held` with `pending-unsettled`. Re-read the document to confirm, and if it is gone, look for it under a new name or in its history.-A write whose document path cannot be resolved inside the content directory returns `urn:ok:error:path-escape` (400): the edit reached collaborative state, but the disk write was refused. This covers a symlink cycle at the document's own path, a link resolving outside the content directory, and a link resolving into a `.git` folder, an OpenKnowledge config folder itself, or its machine-local state. It is not retryable — repair the path on disk before writing this content again.+A write whose document path cannot be resolved inside the content directory returns `urn:ok:error:path-escape` (400, `refused`, `nextStep: none`): the edit reached collaborative state, but the disk write was refused. This covers a symlink cycle at the document's own path, a link resolving outside the content directory, and a link resolving into a `.git` folder, an OpenKnowledge config folder itself, or its machine-local state. Tell the user: the path has to be repaired on disk before this content can be written.-A write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. Retry only after the filesystem fault is repaired.+A write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503, `refused`, `nextStep: re-read`): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. After the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.-A write that arrives while Git is updating the project's `HEAD` or index waits for that to finish and then applies to the checked-out content. That covers a branch switch, a commit, a merge or a reset, and also index-only activity such as `git add` or a `git status` that refreshes the index. Fetching from the remote during sync does not hold writes back; a disk save that sync deferred completes when sync finishes. A request waits at most 20 seconds in total, however many documents it writes. If a branch switch starts while a write's disk save is still pending, the write returns `urn:ok:error:branch-switched` (409): the edit stays in the open document, merged with the checked-out branch's version of the file the way an outside edit is, and is saved with the document's next save. Do not repeat it; re-read the document to confirm. `POST /api/agent-write-batch` reports this per entry inside its `200` envelope. `restore_version` skips the wait before applying, but its confirmation of the disk save can still wait under the same cap, and it can return the same error. If any of that Git activity is still running when the 20 seconds run out, the write applies anyway and its success response can arrive before the disk save, so that response does not confirm the edit is on disk.+A write that arrives while Git is updating the project's `HEAD` or index waits for that to finish and then applies to the checked-out content. That covers a branch switch, a commit, a merge or a reset, and also index-only activity such as `git add` or a `git status` that refreshes the index. Fetching from the remote during sync does not hold writes back; a disk save that sync deferred completes when sync finishes. A request waits at most 20 seconds in total, however many documents it writes. If a branch switch starts while a write's disk save is still pending, the write returns `urn:ok:error:branch-switched` (409, `projection-held`): the edit stays in the open document, merged with the checked-out branch's version of the file the way an outside edit is, and is saved with the document's next save. Do not repeat it; re-read the document to confirm. `POST /api/agent-write-batch` reports this per entry inside its `200` envelope. `restore_version` skips the wait before applying, but its confirmation of the disk save can still wait under the same cap, and it can return the same error. If any of that Git activity is still running when the 20 seconds run out, the write applies anyway and returns `save-held` with `pending-unsettled`: the edit is in the document and is saved once Git finishes.-A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so there is nothing to resolve. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). After whole-request schema validation succeeds, `POST /api/agent-write-batch` keeps its `200` success envelope; each concurrent-overwrite refusal carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Invalid input instead rejects the whole request before processing. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.+A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409, `refused`, `nextStep: retry`): nothing was written, so there is no partial edit to undo. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). After whole-request schema validation succeeds, `POST /api/agent-write-batch` keeps its `200` success envelope; each concurrent-overwrite refusal carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Invalid input instead rejects the whole request before processing. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.-A body or frontmatter edit addressed to a path with no document returns `urn:ok:error:doc-not-found` (404) from `POST /api/agent-patch` and `POST /api/frontmatter-patch`: nothing was written or created, and the body carries `committed: false`. Paths are relative to the content root. The problem body lists up to three likely targets in `candidates` (a folder's hub document, or documents whose trailing path segments match), and the title names them. A find that misses inside an existing document is a different error, `urn:ok:error:target-not-found`.+A body or frontmatter edit addressed to a path with no document returns `urn:ok:error:doc-not-found` (404, `refused`, `nextStep: retry`) from `POST /api/agent-patch` and `POST /api/frontmatter-patch`: nothing was written or created, and the body carries `committed: false`. Paths are relative to the content root. The problem body lists up to three likely targets in `candidates` (a folder's hub document, or documents whose trailing path segments match), and the title names them. A find that misses inside an existing document is a different error, `urn:ok:error:target-not-found` (`refused`, `nextStep: re-read`).-A write refused because the server is at its limit of concurrent agent write sessions returns `urn:ok:error:too-many-agent-sessions` (503): nothing was written, so it is safe to repeat. The problem body says so in `detail`, carries `committed: false`, and carries `retryAfterSeconds` alongside a matching `Retry-After` header. `POST /api/agent-write-md`, `POST /api/agent-patch`, `POST /api/frontmatter-patch` and `POST /api/lint/fix` answer this way, and the `write`, `edit` and `lint` fix tools append the detail and the bound to their error text (`Retry after 10s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type, `detail`, `committed: false` and `retryAfterSeconds` in its `error`, while sibling entries are unaffected. Wait that long and repeat the request. A `write` from a `template` creates the document before it patches the frontmatter, so when only that patch is refused the tool says so and the document already exists: apply the frontmatter with `edit` instead of repeating the `write`. For any other frontmatter failure on that path, re-read the document before changing it, because the patch may have been applied.+A write refused because the server is at its limit of concurrent agent write sessions returns `urn:ok:error:too-many-agent-sessions` (503, `refused`, `nextStep: retry`): nothing was written, so it is safe to repeat. The problem body says so in `detail`, carries `committed: false`, and carries `retryAfterSeconds` alongside a matching `Retry-After` header. `POST /api/agent-write-md`, `POST /api/agent-patch`, `POST /api/frontmatter-patch` and `POST /api/lint/fix` answer this way, and the `write`, `edit` and `lint` fix tools append the detail and the bound to their error text (`Retry after 10s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type, `detail`, `committed: false` and `retryAfterSeconds` in its `error`, while sibling entries are unaffected. Wait that long and repeat the request. A `write` from a `template` creates the document before it patches the frontmatter, so when only that patch is refused the tool says so and the document already exists: apply the frontmatter with `edit` instead of repeating the `write`. For any other frontmatter failure on that path, re-read the document before changing it, because the patch may have been applied.-### Resolving a conflict+### Refusals the agent cannot change-The MCP server has no conflict tools. An agent that hits `doc-in-conflict` or `stale-external-write` should name the file and ask the user to resolve it in the app; see [Resolving a conflict](../features/git/sync.mdx#resolving-a-conflict). HTTP integrations can list conflicts with `GET /api/sync/conflicts`, then read `GET /api/sync/conflict-content?file=<path>` for `base`, `ours`, `theirs`, the conflict kind, and its current `resolutionOptions`. To resolve one, send `POST /api/sync/resolve-conflict` with `{ file, strategy }`, choosing an offered strategy (`mine`, `theirs`, `content`, or `delete`). The `content` strategy also requires `content`; an empty string keeps an empty file. Content must be free of conflict markers. Use only the strategies returned for that conflict; its kind determines the commit behavior described above.+The MCP server has no conflict tools, and no write tool takes a conflict parameter. A mistake in the request itself (a path with no document, malformed frontmatter YAML, a frontmatter edit sent as find and replace, a patch value the schema refuses, a reserved name) is `refused` with `nextStep: retry`: correct the request the way the detail says and send it again. A result with `outcome: refused` and `nextStep: none` is one nothing the agent sends can change: stop writing to that file, tell the user which file it is and what the result says, and carry on with other work rather than waiting; do not work around it by writing elsewhere. Git conflicts are handled in the app; see [Resolving a conflict](../features/git/sync.mdx#resolving-a-conflict).## Preview linksdiff --git a/knip.config.ts b/knip.config.tsindex 36a395261..03ef8d4a4 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -155,11 +155,15 @@ export default {'src/shadow-fixture-launch.test-helper.mjs',],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: ['yjs'],+ ignoreDependencies: [+ 'yjs',+ ],},'packages/desktop': {entry: [diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.mdindex 741fb22b0..2263ac7d3 100644--- a/packages/app/BUNDLE-SIZE.md+++ b/packages/app/BUNDLE-SIZE.md@@ -117,3 +117,5 @@ Combined-chunks stays at 9.15 MB after merging `feat/layout-redesign` into `mainCombined-chunks 9.15->9.16 MB for `@visimer/core` and `@visimer/dom` 1.x, which split the Mermaid edge picker into separate arrow, stroke, color, animation and curve pickers. CI measured the bump at 9,150,517 B, 517 B over the 9,150,000 B ceiling. Direct local `vite build` runs of `packages/app` measured 9,146,208 B with `0.1.0` and 9,149,900 B with `1.1.2`, so the bump adds 3,692 B. CI measures about 600 B more than a local build, so `main` sat about 3.2 kB under the old ceiling before this change. The main app bundle measured 478.46 kB against its 487 kB limit, and CSS stayed at 8.36 kB against 59 kB. The 10 kB ratchet leaves about 9.5 kB of headroom over the CI measurement. None of that headroom is reserved: the HTML preview frame page, web shell CSP and desktop file protocol changes that land after this one pass under 9.16 MB with no further raise. No reclamation lever beyond the lazy-load levers above.Combined-chunks 9.16->9.17 MB for the quiet notice after a both-kept merge or a version moved to history (PRD-9735). Measured 9,157,371 B on main and 9,165,865 B with the notice, 8,494 B more: about 6.6 kB is its 14 new strings in each of the 13 locale catalogs, about 1.7 kB the notice strip, its data hook and the timeline row labels in the main bundle (481.29 kB against its 487 kB limit), and 0.15 kB the notice schema in the `schemas/api` chunk, which the app already imports through that narrow entry. No reclamation lever: the strings are the feature, and each reader downloads one catalog.++Combined-chunks 9.17->9.18 MB for keeping the edited side of engine-less files, settings and skills (PRD-9771, #7203): the history and backup-folder notices in `DocChangeNotice`, the settings notices, the held-save message, and their new strings compiled into each of the 13 locale catalogs. Measured on one machine, `main` alone builds to 9,166,292 B and the branch to 9,175,290 B, so the branch adds 8,998 B and lands 5,290 B over the prior 9,170,000 B ceiling. The 10 kB ratchet to 9,180,000 B leaves 4,710 B of headroom over the branch build. No reclamation lever: the strings are the feature, and each reader downloads one catalog.diff --git a/packages/app/tests/integration/agent-write-batch-closed-doc.test.ts b/packages/app/tests/integration/agent-write-batch-closed-doc.test.tsnew file mode 100644index 000000000..132a5551d--- /dev/null+++ b/packages/app/tests/integration/agent-write-batch-closed-doc.test.ts@@ -0,0 +1,133 @@+import { randomUUID } from 'node:crypto';+import { existsSync, readFileSync, renameSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { getMetrics } from '../../../server/src/metrics';+import { createManualClock } from '../../../server/src/watcher-clock.test-helper';+import { createWatcherDouble } from '../../../server/src/watcher-double.test-helper';+import {+ agentWriteMd,+ createTestClient,+ createTestServer,+ pollUntil,+ type TestServer,+} from './test-harness';++const SAVED = '# Doc\n\nShared paragraph.\n\nTail.\n';++const cleanups: Array<() => Promise<void> | void> = [];++afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();+});++interface BatchEntry {+ status: string;+ docName: string;+ error?: { type?: string; detail?: string };+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+}++function liveText(server: TestServer, docName: string): string {+ return server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';+}++async function seed(server: TestServer, docName: string): Promise<string> {+ const file = join(server.contentDir, `${docName}.md`);+ await agentWriteMd(server.port, SAVED, { docName, position: 'replace' });+ await pollUntil(+ () => existsSync(file) && readFileSync(file, 'utf-8') === SAVED,+ 10_000,+ 25,+ `${docName} on disk`,+ );+ return file;+}++describe('a batch agent write whose document closes while an earlier flush waits', () => {+ test('answers each document with its outcome instead of failing the whole batch', async () => {+ const double = createWatcherDouble();+ const server = await createTestServer({+ gitEnabled: true,+ commitDebounceMs: 50,+ watcherBackend: double.backend,+ watcherClock: createManualClock(Date.now()),+ freshnessIntervalMs: 5_000,+ debounce: 300_000,+ maxDebounce: 600_000,+ });+ cleanups.push(() => server.cleanup());+ const deliver = (events: Array<{ type: 'create' | 'delete'; path: string }>) =>+ double.subscriptionFor(server.contentDir).deliver(events);++ const waiting = `batch-waiting-${randomUUID()}`;+ const closing = `batch-closing-${randomUUID()}`;+ const waitingFile = await seed(server, waiting);+ const closingFile = await seed(server, closing);+ const client = await createTestClient(server.port, waiting, { skipInvariantWatcher: true });+ cleanups.push(() => client.cleanup());+ await pollUntil(() => client.ytext.toString() === SAVED, 10_000, 25, 'the client to load');++ const pendingBefore = getMetrics().vanishPending;+ const waitingMoved = join(server.contentDir, `${waiting}-moved.md`);+ renameSync(waitingFile, waitingMoved);+ deliver([{ type: 'delete', path: waitingFile }]);+ await pollUntil(+ () => getMetrics().vanishPending > pendingBefore,+ 10_000,+ 25,+ 'the first document to be held',+ );++ const batch = fetch(`${server.baseUrl}/api/agent-write-batch`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ docs: [+ { docName: waiting, markdown: 'Batch line one.\n', position: 'append' },+ { docName: closing, markdown: 'Batch line two.\n', position: 'append' },+ ],+ agentId: 'batch-writer',+ }),+ });+ await pollUntil(+ () => liveText(server, closing).includes('Batch line two.'),+ 10_000,+ 25,+ 'the batch to apply both entries',+ );++ const closingMoved = join(server.contentDir, `${closing}-moved.md`);+ renameSync(closingFile, closingMoved);+ deliver([+ { type: 'delete', path: closingFile },+ { type: 'create', path: closingMoved },+ ]);+ await pollUntil(+ () =>+ server.instance.hocuspocus.documents.get(closing)?.getMap('lifecycle').get('status') !==+ undefined,+ 10_000,+ 25,+ 'the second document to follow its move',+ );+ deliver([{ type: 'create', path: waitingMoved }]);++ const response = await batch;+ expect(response.status).toBe(200);+ const body = (await response.json()) as { results: BatchEntry[] };+ const [first, second] = body.results;+ expect(first?.error?.type).toBe('urn:ok:error:doc-moved');+ expect(second?.status).toBe('error');+ expect(second?.error?.type).toBe('urn:ok:error:doc-moved');+ for (const entry of [first, second]) {+ expect(entry).toMatchObject({+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ }+ }, 60_000);+});diff --git a/packages/app/tests/integration/agent-write-outcome.test.ts b/packages/app/tests/integration/agent-write-outcome.test.tsnew file mode 100644index 000000000..25d604728--- /dev/null+++ b/packages/app/tests/integration/agent-write-outcome.test.ts@@ -0,0 +1,354 @@+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+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';+import { createWatcherDouble } from '../../../server/src/watcher-double.test-helper';+import {+ agentWriteMd,+ createTestClient,+ createTestServer,+ pollUntil,+ type TestClient,+ type TestServer,+} from './test-harness';++const SEED = '# Doc\n\nfirst paragraph\n\nsecond 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 Answer {+ status: number;+ body: Record<string, unknown>;+}++async function boot(): Promise<TestServer> {+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 600_000,+ });+ cleanups.push(() => server.cleanup());+ return server;+}++async function open(server: TestServer, docName: string): Promise<TestClient> {+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });+ cleanups.push(() => client.cleanup());+ return client;+}++async function seedAndOpen(+ server: TestServer,+ docName: string,+): Promise<{ client: TestClient; file: 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 open(server, docName);+ await pollUntil(() => client.ytext.toString() === SEED, 10_000, 25, 'the client to load');+ return { client, file };+}++async function post(server: TestServer, path: string, body: unknown): Promise<Answer> {+ const response = await fetch(`${server.baseUrl}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ return { status: response.status, body: (await response.json()) as Record<string, unknown> };+}++function append(server: TestServer, docName: string, markdown: string): Promise<Answer> {+ return post(server, '/api/agent-write-md', {+ docName,+ markdown,+ position: 'append',+ agentId: 'outcome-agent',+ });+}++function disk(file: string): string | null {+ return existsSync(file) ? readFileSync(file, 'utf-8') : null;+}++function expectInClosedSets(answer: Answer): void {+ expect(AGENT_WRITE_OUTCOMES).toContain(answer.body.outcome);+ expect(AGENT_WRITE_NEXT_STEPS).toContain(answer.body.nextStep);+ expect(typeof answer.body.saved).toBe('boolean');+}++function liveText(server: TestServer, docName: string): string {+ return server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';+}++describe('every agent write answers its outcome, whether it is saved, and the next step', () => {+ test('a plain write is applied and saved, with nothing further to do', async () => {+ const server = await boot();+ const docName = `outcome-applied-${randomUUID()}`;+ const answer = await post(server, '/api/agent-write-md', {+ docName,+ markdown: '# Applied\n\nAlpha.\n',+ position: 'replace',+ agentId: 'outcome-agent',+ });+ expect(answer.status).toBe(200);+ expect(answer.body).toMatchObject({ outcome: 'applied', saved: true, nextStep: 'none' });+ expectInClosedSets(answer);+ expect(disk(join(server.contentDir, `${docName}.md`))).toBe('# Applied\n\nAlpha.\n');+ }, 60_000);++ test('a write over an outside edit to another block is merged first, saved, and asks for a re-read', async () => {+ const server = await boot();+ const docName = `outcome-merged-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ writeFileSync(file, '# Doc\n\nfirst paragraph\n\nsecond paragraph, edited outside\n');++ const answer = await append(server, docName, '\nagent line\n');+ expect(answer.status).toBe(200);+ expect(answer.body).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ expectInClosedSets(answer);+ expect(disk(file)).toContain('edited outside');+ expect(disk(file)).toContain('agent line');+ }, 60_000);++ test('a write over a block changed here and outside keeps both, is saved, and a re-read returns both versions', async () => {+ const server = await boot();+ const docName = `outcome-both-${randomUUID()}`;+ const { client, file } = await seedAndOpen(server, docName);+ client.doc.transact(() => {+ const at = client.ytext.toString().indexOf('first paragraph');+ client.ytext.insert(at + 'first paragraph'.length, ', edited here');+ });+ await pollUntil(() => liveText(server, docName).includes('edited here'));+ writeFileSync(file, '# Doc\n\nfirst paragraph, edited outside\n\nsecond paragraph\n');++ const answer = await append(server, docName, '\nagent line\n');+ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:both-kept',+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });+ expectInClosedSets(answer);+ expect(String(answer.body.detail)).toContain('do not retry it');+ expect(disk(file)).toContain('agent line');++ const reread = await fetch(+ `${server.baseUrl}/api/document?docName=${encodeURIComponent(docName)}`,+ );+ const { content } = (await reread.json()) as { content: string };+ expect(content).toContain('first paragraph, edited here');+ expect(content).toContain('first paragraph, edited outside');+ }, 60_000);++ test('a replace refused by a recent edit is not saved and says to retry', async () => {+ const server = await boot();+ const docName = `outcome-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 post(server, '/api/agent-write-md', {+ docName,+ markdown: '# Replacement\n',+ position: 'replace',+ agentId: 'outcome-agent',+ });+ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({ outcome: 'refused', saved: false, nextStep: 'retry' });+ expectInClosedSets(answer);+ expect(disk(file)).not.toContain('Replacement');+ }, 60_000);++ test('a write whose save is held is in the document, not saved, and asks for a re-read', async () => {+ const server = await boot();+ const docName = `outcome-held-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ process.env.OK_TEST_COMPARE_READ_FAULT = `${docName}:EBUSY:1000`;++ const answer = await append(server, docName, '\nagent line\n');+ expect(answer.status).toBe(503);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:save-held',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ expectInClosedSets(answer);+ expect(disk(file)).toBe(SEED);+ expect(liveText(server, docName)).toContain('agent line');+ }, 60_000);+});++describe('what each refusal and each kind of document reports', () => {+ test('a patch to a path with no document is refused with retry, to send again at the right path', async () => {+ const server = await boot();+ const answer = await post(server, '/api/agent-patch', {+ docName: `outcome-missing-${randomUUID()}`,+ find: 'a',+ replace: 'b',+ agentId: 'outcome-agent',+ });+ expect(answer.status).toBe(404);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:doc-not-found',+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ });+ }, 60_000);++ test('a write to a Mermaid document, and its undo, carry no outcome until the save reports back', 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', {+ 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');++ 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');+ }, 60_000);+});++describe('an agent write whose own save meets an outside change', () => {+ test('is merged first when the save merges a change the pre-write merge read as unchanged', async () => {+ const server = await boot();+ const docName = `outcome-save-merged-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ writeFileSync(file, '# Doc\n\nfirst paragraph \n\nsecond paragraph\n');++ const answer = await append(server, docName, '\nagent line\n');+ expect(answer.status).toBe(200);+ expect(answer.body).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ expect(disk(file)).toBe('# Doc\n\nfirst paragraph \n\nsecond paragraph\n\nagent line\n');+ }, 60_000);++ test('keeps both when the save finds the edited block also changed outside', async () => {+ const server = await boot();+ const docName = `outcome-save-both-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ writeFileSync(file, '# Doc\n\nfirst paragraph \n\nsecond paragraph\n');++ const answer = await post(server, '/api/agent-patch', {+ docName,+ find: 'first paragraph',+ replace: 'first paragraph, edited by the agent',+ agentId: 'outcome-agent',+ });+ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:both-kept',+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });+ expect(disk(file)).toContain('first paragraph, edited by the agent');+ }, 60_000);++ test('is refused, not saved, when the file replaced a document that had no agreed version', async () => {+ const server = await boot();+ const docName = `outcome-replaced-${randomUUID()}`;+ const file = join(server.contentDir, `${docName}.md`);+ await open(server, docName);+ writeFileSync(file, '# From another tool\n');++ const answer = await append(server, docName, '\nagent line\n');+ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({+ type: 'urn:ok:error:write-replaced',+ outcome: 'refused',+ saved: false,+ nextStep: 're-read',+ });+ expect(disk(file)).toBe('# From another tool\n');+ }, 60_000);+});++describe('a held save on a document with no agreed version', () => {+ test('is refused with the replace-on-next-write rule only when a file is there to take over', async () => {+ const server = await boot();+ const withFile = `outcome-nobase-file-${randomUUID()}`;+ await open(server, withFile);+ writeFileSync(join(server.contentDir, `${withFile}.md`), '# From another tool\n');+ process.env.OK_TEST_COMPARE_READ_FAULT = `${withFile}:EBUSY:1000`;+ const refused = await append(server, withFile, '\nagent line\n');+ expect(refused.status).toBe(503);+ expect(refused.body).toMatchObject({ outcome: 'refused', saved: false, nextStep: 'none' });+ expect(String(refused.body.detail)).toContain('replaces the document with the file on disk');++ const noFile = `outcome-nobase-new-${randomUUID()}`;+ await open(server, noFile);+ process.env.OK_TEST_COMPARE_READ_FAULT = `${noFile}:EBUSY:1000`;+ const held = await append(server, noFile, '\nagent line\n');+ expect(held.status).toBe(503);+ expect(held.body).toMatchObject({ outcome: 'projection-held', saved: false });+ expect(String(held.body.detail)).not.toContain('replaces the document with the file on disk');+ }, 60_000);+});++describe('a rename outside the app of a document nobody has open', () => {+ test('leaves no rename-carry record once it settles', async () => {+ const double = createWatcherDouble();+ const server = await createTestServer({ watcherBackend: double.backend });+ cleanups.push(() => server.cleanup());+ const pages = async (): Promise<string> =>+ JSON.stringify(await (await fetch(`${server.baseUrl}/api/pages`)).json());+ const docName = `outcome-unopened-${randomUUID()}`;+ const file = join(server.contentDir, `${docName}.md`);+ writeFileSync(file, SEED);+ double.subscriptionFor(server.contentDir).deliver([{ type: 'create', path: file }]);+ await pollUntil(async () => (await pages()).includes(docName), 10_000, 25, 'the new file');+ expect(server.instance.hocuspocus.documents.has(docName)).toBe(false);+ const carries = vi.spyOn(server.instance.durabilityState, 'beginRenameCarry');+ cleanups.push(() => carries.mockRestore());++ const moved = join(server.contentDir, `${docName}-moved.md`);+ renameSync(file, moved);+ double.subscriptionFor(server.contentDir).deliver([+ { type: 'delete', path: file },+ { type: 'create', path: moved },+ ]);+ await pollUntil(+ async () => (await pages()).includes(`${docName}-moved`),+ 10_000,+ 25,+ 'the move to be followed',+ );+ expect(carries).toHaveBeenCalledWith(docName);+ expect(server.instance.durabilityState.renameCarryOf(docName)).toBeUndefined();+ }, 60_000);+});diff --git a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts b/packages/app/tests/integration/api-error-envelope/skill-install.test.tsindex 055af7405..4b0b96ba0 100644--- a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts+++ b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts@@ -45,7 +45,11 @@ describe('skill install-projection lifecycle', () => {const res = await installSkill({ name: 'trip-log', targets: ['claude', 'cursor'] });expect(res.status).toBe(200);- const parsed = SkillInstallSuccessSchema.safeParse(await res.json());+ const installed = (await res.json()) as Record<string, unknown>;+ expect(installed).not.toHaveProperty('outcome');+ expect(installed).not.toHaveProperty('saved');+ expect(installed).not.toHaveProperty('nextStep');+ const parsed = SkillInstallSuccessSchema.safeParse(installed);expect(parsed.success).toBe(true);if (parsed.success) {expect(parsed.data.hosts.sort()).toEqual(['claude', 'cursor']);diff --git a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.tsindex b2b9e6164..e476b88e0 100644--- a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts+++ b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts@@ -101,6 +101,9 @@ describe('global-scope skills', () => {expect(res.status).toBe(200);const body = (await res.json()) as { hosts: string[] };expect(body.hosts).toContain('claude');+ expect(body).not.toHaveProperty('outcome');+ expect(body).not.toHaveProperty('saved');+ expect(body).not.toHaveProperty('nextStep');expect(existsSync(join(tmpHome, '.claude', 'skills', 'daily-standup', 'SKILL.md'))).toBe(true);});diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a50b00123..4549c74b3 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/concurrent-replace-refusal.test.ts b/packages/app/tests/integration/concurrent-replace-refusal.test.tsindex 47a40ebc8..befe5c38e 100644--- a/packages/app/tests/integration/concurrent-replace-refusal.test.ts+++ b/packages/app/tests/integration/concurrent-replace-refusal.test.ts@@ -166,11 +166,15 @@ describe('concurrent whole-document replace refusal', () => {expect(problem.file).toBe(`${docName}.md`);expect(problem.retryAfterSeconds).toBe(3);expect(refused.headers.get('Retry-After')).toBe('3');+ expect(problem).toMatchObject({ outcome: 'refused', saved: false, nextStep: 'retry' });expect(Object.keys(problem).sort()).toEqual(['detail','file','instance',+ 'nextStep',+ 'outcome','retryAfterSeconds',+ 'saved','status','title','type',diff --git a/packages/app/tests/integration/disk-authority-reconcile.test.ts b/packages/app/tests/integration/disk-authority-reconcile.test.tsindex edabaaefa..65df31813 100644--- a/packages/app/tests/integration/disk-authority-reconcile.test.ts+++ b/packages/app/tests/integration/disk-authority-reconcile.test.ts@@ -257,13 +257,22 @@ describe('PRD-6832 β L1: agent write reconciles a newer out-of-band disk edit',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ docName, markdown: 'agent-line\n', position: 'append' }),});- expect(res.status).toBe(200);+ expect(res.status).toBe(409);const body = (await res.json()) as {- warnings?: Array<{ kind?: string; mergeOutcome?: string; nextStep?: string }>;+ type?: string;+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+ warnings?: Array<{ kind?: string; mergeOutcome?: string }>;};+ expect(body).toMatchObject({+ type: 'urn:ok:error:both-kept',+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });const reconciled = body.warnings?.find((w) => w.kind === 'disk-edit-reconciled');expect(reconciled?.mergeOutcome).toBe('both-kept');- expect(reconciled?.nextStep).toBe('re-read');expect(serverYtext()).toContain('shared-line crdt-version\n\nshared-line disk-version\n\nagent-line',diff --git a/packages/app/tests/integration/doc-notice.test.ts b/packages/app/tests/integration/doc-notice.test.tsindex 67cee5ddb..bae49b58d 100644--- a/packages/app/tests/integration/doc-notice.test.ts+++ b/packages/app/tests/integration/doc-notice.test.ts@@ -199,7 +199,13 @@ describe('the notice on a document after an outside edit', () => {headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ docName, markdown: 'Agent line.\n', position: 'append' }),});- expect(res.status).toBe(200);+ expect(res.status).toBe(409);+ expect(await res.json()).toMatchObject({+ type: 'urn:ok:error:both-kept',+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });expect(await noticesFor(docName)).toEqual([expect.objectContaining({diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 6fcdc23f2..4fc2c11f9 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 40b5cdfd6..9f2f6feb6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keep-both-collision.test.ts b/packages/app/tests/integration/keep-both-collision.test.tsindex 193b08e23..d59f0da48 100644--- a/packages/app/tests/integration/keep-both-collision.test.ts+++ b/packages/app/tests/integration/keep-both-collision.test.ts@@ -170,7 +170,7 @@ describe('an outside edit to the block being edited here keeps both versions', (});describe('an agent write over an outside edit to the block being edited here', () => {- test('lands on both versions and reports both-kept with re-read as the next step', async () => {+ test('lands on both versions and answers both-kept, saved, with re-read as the next step', async () => {const docName = `agent-keep-both-${randomUUID()}`;const { s, file } = await openWithUnsavedEdit(docName, SAVED, PARAGRAPH_EDIT);writeFileSync(file, EDITED_OUTSIDE);@@ -180,13 +180,26 @@ describe('an agent write over an outside edit to the block being edited here', (headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ docName, markdown: 'Agent line.\n', position: 'append' }),});- expect(res.status).toBe(200);+ expect(res.status).toBe(409);const body = (await res.json()) as {- warnings?: Array<{ kind?: string; mergeOutcome?: string; nextStep?: string }>;+ type?: string;+ title?: string;+ detail?: string;+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+ warnings?: Array<{ kind?: string; mergeOutcome?: string }>;};+ expect(body).toMatchObject({+ type: 'urn:ok:error:both-kept',+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });+ expect(body.detail).toContain('do not retry it');+ expect(readFileSync(file, 'utf-8')).toContain('Agent line.');expect(body.warnings?.find((w) => w.kind === 'disk-edit-reconciled')).toMatchObject({mergeOutcome: 'both-kept',- nextStep: 're-read',});const live = liveText(s, docName);@@ -200,7 +213,7 @@ describe('an agent write over an outside edit to the block being edited here', (]);}, 60_000);- test('a merge that fails the fidelity check lands the write on the version here and reports kept-live', async () => {+ test('a merge that fails the fidelity check lands the write on the version here and answers merged-first', async () => {const docName = `agent-keep-live-${randomUUID()}`;const { s, file } = await openWithUnsavedEdit(docName, CHECK_SAVED, CHECK_EDIT);writeFileSync(file, CHECK_OUTSIDE);@@ -212,11 +225,14 @@ describe('an agent write over an outside edit to the block being edited here', (});expect(res.status).toBe(200);const body = (await res.json()) as {- warnings?: Array<{ kind?: string; mergeOutcome?: string; nextStep?: string }>;+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+ warnings?: Array<{ kind?: string; mergeOutcome?: string }>;};+ expect(body).toMatchObject({ outcome: 'merged-first', saved: true, nextStep: 're-read' });expect(body.warnings?.find((w) => w.kind === 'disk-edit-reconciled')).toMatchObject({mergeOutcome: 'kept-live',- nextStep: 're-read',});const live = liveText(s, docName);diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 93666af70..2a085742b 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/mcp-write-outcome.test.ts b/packages/app/tests/integration/mcp-write-outcome.test.tsnew file mode 100644index 000000000..ed1dba6d0--- /dev/null+++ b/packages/app/tests/integration/mcp-write-outcome.test.ts@@ -0,0 +1,190 @@+import { randomUUID } from 'node:crypto';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';+import { createWatcherDouble } from '../../../server/src/watcher-double.test-helper';+import {+ agentWriteMd,+ createTestClient,+ createTestServer,+ pollUntil,+ type TestClient,+ type TestServer,+} from './test-harness';++const SEED = '# Doc\n\nfirst paragraph\n\nsecond 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();+});++type Mcp = Awaited<ReturnType<typeof connectMcpTestClient>>;++async function rig(): Promise<{ server: TestServer; mcp: Mcp }> {+ const server = await createTestServer({+ gitEnabled: true,+ watcherBackend: createWatcherDouble().backend,+ debounce: 300_000,+ maxDebounce: 600_000,+ });+ cleanups.push(() => server.cleanup());+ const mcp = await connectMcpTestClient(`${server.baseUrl}/mcp`, { name: 'outcome-reader' });+ cleanups.push(() => mcp.close());+ await mcp.listTools();+ return { server, mcp };+}++async function seedAndOpen(+ server: TestServer,+ docName: string,+): Promise<{ client: TestClient; file: 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 liveText(server: TestServer, docName: string): string {+ return server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';+}++function textOf(result: { content: unknown }): string {+ return (result.content as Array<{ text?: string }>)[0]?.text ?? '';+}++function appendWith(mcp: Mcp, path: string, content: string) {+ return mcp.callTool({+ name: 'write',+ arguments: { document: { path, content, position: 'append' } },+ });+}++describe('an MCP client that has listed the tools reads the outcome on every write result', () => {+ test('applied and refused write results carry the same three fields', async () => {+ const { server, mcp } = await rig();+ const docName = `mcp-outcome-${randomUUID()}`;+ const applied = await mcp.callTool({+ name: 'write',+ arguments: { document: { path: docName, content: '# Applied\n\nAlpha.\n' } },+ });+ expect(applied.isError).toBeFalsy();+ expect(applied.structuredContent).toMatchObject({+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+ });++ const { client } = await seedAndOpen(server, `${docName}-refused`);+ client.doc.transact(() => client.ytext.insert(client.ytext.length, '\ntyped here\n'));+ await pollUntil(() => liveText(server, `${docName}-refused`).includes('typed here'));+ const refused = await mcp.callTool({+ name: 'write',+ arguments: {+ document: { path: `${docName}-refused`, content: '# Replacement\n', position: 'replace' },+ },+ });+ expect(refused.isError).toBe(true);+ expect(refused.structuredContent).toMatchObject({+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ });+ expect(textOf(refused)).toContain('Outcome: refused; saved: no; next step: retry.');+ }, 60_000);++ test('a both-kept write is not a plain success, and its text says it landed and is not to be retried', async () => {+ const { server, mcp } = await rig();+ const docName = `mcp-both-${randomUUID()}`;+ const { client, file } = await seedAndOpen(server, docName);+ client.doc.transact(() => {+ const at = client.ytext.toString().indexOf('first paragraph');+ client.ytext.insert(at + 'first paragraph'.length, ', edited here');+ });+ await pollUntil(() => liveText(server, docName).includes('edited here'));+ writeFileSync(file, '# Doc\n\nfirst paragraph, edited outside\n\nsecond paragraph\n');++ const result = await appendWith(mcp, docName, '\nagent line\n');+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+ });+ const text = textOf(result);+ expect(text).toContain('The write landed and is saved; do not retry it.');+ expect(text).not.toMatch(/^Error/);+ }, 60_000);++ test('a write whose save is held says it is in the document and not to be retried', async () => {+ const { server, mcp } = await rig();+ const docName = `mcp-held-${randomUUID()}`;+ await seedAndOpen(server, docName);+ process.env.OK_TEST_COMPARE_READ_FAULT = `${docName}:EBUSY:1000`;++ const result = await appendWith(mcp, docName, '\nagent line\n');+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ expect(result.structuredContent).not.toHaveProperty('document');+ expect(textOf(result)).toContain('Do not retry it.');+ }, 60_000);++ test('an edit over an outside change to another block reads as merged first', async () => {+ const { server, mcp } = await rig();+ const docName = `mcp-merged-${randomUUID()}`;+ const { file } = await seedAndOpen(server, docName);+ writeFileSync(file, '# Doc\n\nfirst paragraph\n\nsecond paragraph, edited outside\n');++ const result = await mcp.callTool({+ name: 'edit',+ arguments: {+ document: { path: docName, find: 'first paragraph', replace: 'first paragraph, edited' },+ },+ });+ expect(result.isError).toBeFalsy();+ expect(result.structuredContent).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ }, 60_000);++ test('each entry of a batch write carries its own outcome', async () => {+ const { server, mcp } = await rig();+ const fresh = `mcp-batch-fresh-${randomUUID()}`;+ const busy = `mcp-batch-busy-${randomUUID()}`;+ const { client } = await seedAndOpen(server, busy);+ client.doc.transact(() => client.ytext.insert(client.ytext.length, '\ntyped here\n'));+ await pollUntil(() => liveText(server, busy).includes('typed here'));++ const result = await mcp.callTool({+ name: 'write',+ arguments: {+ documents: [+ { path: fresh, content: '# Fresh\n' },+ { path: busy, content: '# Replacement\n', position: 'replace' },+ ],+ },+ });+ expect(result.isError).toBe(true);+ const structured = result.structuredContent as {+ outcome?: string;+ documents: Array<{ docName: string; outcome?: string; nextStep?: string }>;+ };+ expect(structured.outcome).toBeUndefined();+ expect(structured.documents.map((entry) => [entry.outcome, entry.nextStep])).toEqual([+ ['applied', 'none'],+ ['refused', 'retry'],+ ]);+ }, 60_000);+});diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 867598d34..878d5196b 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 0970ac12f..4ada3cf26 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex b632185e1..cbe2b705f 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,3 +1,4 @@+import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex c530ce4ba..89bc9b4d9 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex d3767adc9..a78aeb0e4 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,3 +1,4 @@+import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex b076f955c..e7cc69c3f 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 7935e35f8..9ddcd0730 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,3 +1,4 @@+import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex e7e63f43d..ffd8fce06 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.tsindex 2955ce83f..02a45b39d 100644--- a/packages/core/src/handoff/urn-ipc-registry.ts+++ b/packages/core/src/handoff/urn-ipc-registry.ts@@ -65,6 +65,8 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>(['urn:ok:error:branch-switched','urn:ok:error:doc-moved','urn:ok:error:server-stopped',+ 'urn:ok:error:both-kept',+ 'urn:ok:error:write-replaced','urn:ok:error:doc-in-conflict','urn:ok:error:no-conflict-tracked','urn:ok:error:unresolved-conflict-markers',diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 5dcd4797e..82738202e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1208,6 +1208,10 @@ export {AdvisoryWarningSchema,AdvisoryWarningsSchema,AGENT_WRITE_BATCH_MAX_DOCS,+ AGENT_WRITE_NEXT_STEP_MEANINGS,+ AGENT_WRITE_NEXT_STEPS,+ AGENT_WRITE_OUTCOME_MEANINGS,+ AGENT_WRITE_OUTCOMES,type AgentActivitySuccess,AgentActivitySuccessSchema,type AgentBurstDiffSuccess,@@ -1248,6 +1252,9 @@ export {AgentWriteMdRequestSchema,type AgentWriteMdSuccess,AgentWriteMdSuccessSchema,+ type AgentWriteNextStep,+ type AgentWriteOutcome,+ type AgentWriteOutcomeFields,type AgentWriteRequest,AgentWriteRequestSchema,type AgentWriteSuccess,@@ -1255,6 +1262,7 @@ export {type Anchor,type ApiConfigSuccess,ApiConfigSuccessSchema,+ agentWriteOutcomeWireFields,assertNeverProblemType,assertNeverSemanticProviderErrorReason,assertNeverSemanticQueryOutcome,@@ -1421,6 +1429,8 @@ export {type InstallSkillSuccess,InstallSkillSuccessSchema,interpretSkillMoveFailure,+ isAgentWriteNextStep,+ isAgentWriteOutcome,isBranchNotFoundGitError,isLoginFixableGitAuthError,isReconcileMergeOutcome,@@ -1497,6 +1507,8 @@ export {MetricsReconciliationSuccessSchema,type MetricsWatcherRecentSuccess,MetricsWatcherRecentSuccessSchema,+ type NormalizedAgentWriteOutcome,+ normalizeAgentWriteOutcome,normalizeApiWarnings,type OrphanEntry,OrphanEntrySchema,diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fc267cbea..fb0ba5a7c 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex dfecb41e1..a04a6940d 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -4,6 +4,7 @@ import {BrokenLinkSuppressionSchema,LocalTargetDiagnosticEvidenceSchema,} from '../../schemas/api/agent-write.ts';+import { agentWriteOutcomeWireFields } from '../../schemas/api/agent-write-outcome.ts';import { DEFAULT_MARKDOWNLINT_CONFIG } from './default-config.ts';import type { OkfRuleId } from './okf-rule-meta.ts';import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';@@ -274,6 +275,7 @@ export const ReLintFailureSchema = z.object({export type ReLintFailure = z.infer<typeof ReLintFailureSchema>;export const LintFixResultSchema = z.object({+ ...agentWriteOutcomeWireFields,file: z.string(),fixedCount: z.number(),diagnostics: z.array(LintDiagnosticSchema),diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex 861003fb4..ae8cb390b 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 4e13984c0..9c625647d 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -89,6 +89,8 @@ export const ProblemTypeSchema = z.enum(['urn:ok:error:branch-switched','urn:ok:error:doc-moved','urn:ok:error:server-stopped',+ 'urn:ok:error:both-kept',+ 'urn:ok:error:write-replaced','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.tsnew file mode 100644index 000000000..81e9dce4c--- /dev/null+++ b/packages/core/src/schemas/api/agent-write-outcome.test.ts@@ -0,0 +1,136 @@+import { describe, expect, test } from 'vitest';+import {+ AGENT_WRITE_NEXT_STEPS,+ AGENT_WRITE_OUTCOMES,+ AgentWriteBatchResultSchema,+ AgentWriteMdSuccessSchema,+ normalizeAgentWriteOutcome,+ ProblemTypeSchema,+} from './index.ts';++describe('the agent write outcome contract', () => {+ test('the outcome and next-step sets are the owner-directed closed sets', () => {+ expect(AGENT_WRITE_OUTCOMES).toEqual([+ 'applied',+ 'merged-first',+ 'both-kept',+ 'refused',+ 'projection-held',+ ]);+ expect(AGENT_WRITE_NEXT_STEPS).toEqual(['retry', 're-read', 'none']);+ });++ test('a success body and both batch arms carry the three fields', () => {+ const fields = { outcome: 'merged-first', saved: true, nextStep: 're-read' };+ expect(+ AgentWriteMdSuccessSchema.parse({+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 0,+ brokenLinks: [],+ ...fields,+ }),+ ).toMatchObject(fields);+ expect(+ AgentWriteBatchResultSchema.parse({+ status: 'written',+ docName: 'a',+ brokenLinks: [],+ ...fields,+ }),+ ).toMatchObject(fields);+ expect(+ AgentWriteBatchResultSchema.parse({+ status: 'error',+ docName: 'a',+ error: { type: 'urn:ok:error:save-held', title: 't' },+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ }),+ ).toMatchObject({ outcome: 'projection-held', saved: false });+ });++ test('a newer server may send values this build does not know without failing the parse', () => {+ expect(+ AgentWriteMdSuccessSchema.safeParse({+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 0,+ brokenLinks: [],+ outcome: 'displaced',+ saved: false,+ nextStep: 'ask',+ }).success,+ ).toBe(true);+ });++ test('the both-kept and write-replaced 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);+ });+});++describe('normalizeAgentWriteOutcome', () => {+ test('known values pass through unchanged', () => {+ expect(+ normalizeAgentWriteOutcome({ outcome: 'both-kept', saved: true, nextStep: 're-read' }),+ ).toEqual({ outcome: 'both-kept', saved: true, nextStep: 're-read' });+ expect(+ normalizeAgentWriteOutcome({ outcome: 'refused', saved: false, nextStep: 'retry' }),+ ).toEqual({ outcome: 'refused', saved: false, nextStep: 'retry' });+ });++ test('an older server that sends no outcome yields nothing, so nothing is invented', () => {+ expect(normalizeAgentWriteOutcome({})).toBeUndefined();+ expect(normalizeAgentWriteOutcome({ nextStep: 're-read' })).toBeUndefined();+ expect(normalizeAgentWriteOutcome({ saved: false, nextStep: 're-read' })).toBeUndefined();+ });++ test('an unknown outcome on a saved write reads as merged-first with a re-read', () => {+ expect(+ normalizeAgentWriteOutcome({ outcome: 'displaced', saved: true, nextStep: 'none' }),+ ).toEqual({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ unknownOutcome: 'displaced',+ });+ });++ test('an unknown outcome on an unsaved write reads as refused with a re-read, never a retry', () => {+ expect(+ normalizeAgentWriteOutcome({ outcome: 'held', saved: false, nextStep: 'retry' }),+ ).toEqual({ outcome: 'refused', saved: false, nextStep: 're-read', unknownOutcome: 'held' });+ });++ test('an unknown next step becomes re-read, and a malformed saved flag is left out', () => {+ expect(+ normalizeAgentWriteOutcome({ outcome: 'projection-held', saved: 'yes', nextStep: 'ask' }),+ ).toEqual({+ outcome: 'projection-held',+ nextStep: 're-read',+ unknownNextStep: 'ask',+ });+ });++ test('an absent saved or next step stays absent next to a known outcome', () => {+ expect(normalizeAgentWriteOutcome({ outcome: 'both-kept', nextStep: 're-read' })).toEqual({+ outcome: 'both-kept',+ nextStep: 're-read',+ });+ expect(normalizeAgentWriteOutcome({ outcome: 'both-kept', saved: true })).toEqual({+ outcome: 'both-kept',+ saved: true,+ });+ expect(normalizeAgentWriteOutcome({ outcome: 'applied' })).toEqual({ outcome: 'applied' });+ });++ test('an unknown outcome with no saved flag reads as refused and invents no saved flag', () => {+ expect(normalizeAgentWriteOutcome({ outcome: 'displaced' })).toEqual({+ outcome: 'refused',+ nextStep: 're-read',+ unknownOutcome: 'displaced',+ });+ });+});diff --git a/packages/core/src/schemas/api/agent-write-outcome.ts b/packages/core/src/schemas/api/agent-write-outcome.tsnew file mode 100644index 000000000..13553c4d9--- /dev/null+++ b/packages/core/src/schemas/api/agent-write-outcome.ts@@ -0,0 +1,88 @@+import { z } from 'zod';++export const AGENT_WRITE_OUTCOMES = [+ 'applied',+ 'merged-first',+ 'both-kept',+ 'refused',+ 'projection-held',+] as const;+export type AgentWriteOutcome = (typeof AGENT_WRITE_OUTCOMES)[number];++export const AGENT_WRITE_NEXT_STEPS = ['retry', 're-read', 'none'] as const;+export type AgentWriteNextStep = (typeof AGENT_WRITE_NEXT_STEPS)[number];++export interface AgentWriteOutcomeFields {+ readonly outcome: AgentWriteOutcome;+ readonly saved: boolean;+ readonly nextStep: AgentWriteNextStep;+}++export const AGENT_WRITE_OUTCOME_MEANINGS: Readonly<Record<AgentWriteOutcome, string>> = {+ applied:+ 'the write landed and is saved to the file; carry on, or re-read first when nextStep says re-read (the stored text differs from what was sent)',+ 'merged-first':+ 'an outside change to the file was handled before the write was saved (merged in, or saved to the document history when it could not be merged); the write landed; re-read before the next edit',+ 'both-kept':+ 'the write landed and is saved, and for a block changed both here and outside both versions are in the document, this side first; never retry it; re-read and tidy the duplicate with an ordinary edit if the task calls for it',+ refused:+ 'not saved; OpenKnowledge saves it only after someone acts: the agent, as nextStep says, or the user; follow nextStep',+ 'projection-held':+ 'the write is in the document but not yet in its file, and OpenKnowledge saves it on its own (on either runtime: a held local save or a held cloud projection); never retry it; re-read before the next edit',+};++export const AGENT_WRITE_NEXT_STEP_MEANINGS: Readonly<Record<AgentWriteNextStep, string>> = {+ retry:+ 'the write did not land; send it again, corrected the way the detail says or after the wait it names',+ 're-read': 're-read the document before doing anything further with it',+ 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 detail says',+};++export function isAgentWriteOutcome(value: unknown): value is AgentWriteOutcome {+ return (AGENT_WRITE_OUTCOMES as readonly unknown[]).includes(value);+}++export function isAgentWriteNextStep(value: unknown): value is AgentWriteNextStep {+ return (AGENT_WRITE_NEXT_STEPS as readonly unknown[]).includes(value);+}++export const agentWriteOutcomeWireFields = {+ outcome: z.string().optional(),+ saved: z.boolean().optional(),+ nextStep: z.string().optional(),+} as const;++export interface NormalizedAgentWriteOutcome {+ readonly outcome: AgentWriteOutcome;+ readonly saved?: boolean;+ readonly nextStep?: AgentWriteNextStep;+ readonly unknownOutcome?: string;+ readonly unknownNextStep?: string;+}++function normalizedNextStep(+ raw: unknown,+): Pick<NormalizedAgentWriteOutcome, 'nextStep' | 'unknownNextStep'> {+ if (raw === undefined) return {};+ if (isAgentWriteNextStep(raw)) return { nextStep: raw };+ return { nextStep: 're-read', unknownNextStep: String(raw) };+}++export function normalizeAgentWriteOutcome(raw: {+ readonly outcome?: unknown;+ readonly saved?: unknown;+ readonly nextStep?: unknown;+}): NormalizedAgentWriteOutcome | undefined {+ if (raw.outcome === undefined) return undefined;+ const saved = typeof raw.saved === 'boolean' ? { saved: raw.saved } : {};+ if (!isAgentWriteOutcome(raw.outcome)) {+ return {+ outcome: raw.saved === true ? 'merged-first' : 'refused',+ ...saved,+ ...normalizedNextStep(raw.nextStep),+ nextStep: 're-read',+ unknownOutcome: String(raw.outcome),+ };+ }+ return { outcome: raw.outcome, ...saved, ...normalizedNextStep(raw.nextStep) };+}diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.tsindex a8c75e749..5c973945a 100644--- a/packages/core/src/schemas/api/agent-write.ts+++ b/packages/core/src/schemas/api/agent-write.ts@@ -16,6 +16,7 @@ import {safeDocNameField,summaryField,} from './_shared.ts';+import { agentWriteOutcomeWireFields } from './agent-write-outcome.ts';export const AgentWriteRequestSchema = z.object({@@ -124,7 +125,7 @@ export const DiskEditReconciledWarningSchema = zduplicatedBlocks: z.number().int().nonnegative().optional(),restoredDeletedHere: z.number().int().nonnegative().optional(),restoredDeletedOutside: z.number().int().nonnegative().optional(),- nextStep: z.string().optional(),+ nextStep: z.string().optional().meta({ deprecated: true }),hint: z.string().optional(),}).loose() satisfies StandardSchemaV1;@@ -250,6 +251,7 @@ export type BrokenLinkSuppression = z.infer<typeof BrokenLinkSuppressionSchema>;export const AgentWriteSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,timestamp: z.string().min(1),summary: SummaryResponseFieldSchema.optional(),warnings: AdvisoryWarningsSchema.optional(),@@ -259,6 +261,7 @@ export type AgentWriteSuccess = z.infer<typeof AgentWriteSuccessSchema>;export const AgentWriteMdSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,timestamp: z.string().min(1),subscriberCount: z.number().int().nonnegative(),systemSubscriberCount: z.number().int().nonnegative(),@@ -273,6 +276,7 @@ export type AgentWriteMdSuccess = z.infer<typeof AgentWriteMdSuccessSchema>;export const AgentPatchSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,timestamp: z.string().min(1),subscriberCount: z.number().int().nonnegative(),systemSubscriberCount: z.number().int().nonnegative(),@@ -286,6 +290,7 @@ export type AgentPatchSuccess = z.infer<typeof AgentPatchSuccessSchema>;export const AgentUndoSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,docName: z.string().min(1),scope: z.enum(['last', 'session', 'count']),undone: z.boolean(),@@ -328,6 +333,7 @@ export const AgentWriteBatchResultSchema = z.discriminatedUnion('status', [.object({status: z.literal('written'),docName: z.string().min(1),+ ...agentWriteOutcomeWireFields,summary: SummaryResponseFieldSchema.optional(),warnings: AdvisoryWarningsSchema.optional(),brokenLinks: BrokenLinksSchema,@@ -338,6 +344,7 @@ export const AgentWriteBatchResultSchema = z.discriminatedUnion('status', [.object({status: z.literal('error'),docName: z.string().min(1),+ ...agentWriteOutcomeWireFields,error: BatchEntryErrorSchema,}).loose(),@@ -367,6 +374,7 @@ export type FrontmatterPatchRequest = z.infer<typeof FrontmatterPatchRequestScheexport const FrontmatterPatchSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,timestamp: z.string().min(1),subscriberCount: z.number().int().nonnegative(),systemSubscriberCount: z.number().int().nonnegative(),diff --git a/packages/core/src/schemas/api/index.ts b/packages/core/src/schemas/api/index.tsindex 14b0d41a4..ce2abf755 100644--- a/packages/core/src/schemas/api/index.ts+++ b/packages/core/src/schemas/api/index.ts@@ -1,6 +1,7 @@export * from './_envelope.ts';export * from './agent-integrations.ts';export * from './agent-write.ts';+export * from './agent-write-outcome.ts';export * from './client-logs.ts';export * from './comments.ts';export * from './doc-notices.ts';diff --git a/packages/core/src/schemas/api/pages.ts b/packages/core/src/schemas/api/pages.tsindex 34016d75c..ddbe487a3 100644--- a/packages/core/src/schemas/api/pages.ts+++ b/packages/core/src/schemas/api/pages.ts@@ -2,6 +2,7 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';import { agentIdentityFields, summaryField } from './_shared.ts';import { AdvisoryWarningsSchema, SummaryResponseFieldSchema } from './agent-write.ts';+import { agentWriteOutcomeWireFields } from './agent-write-outcome.ts';export const RenamedDocMappingSchema = z.object({@@ -185,6 +186,7 @@ export type RollbackRequest = z.infer<typeof RollbackRequestSchema>;export const RollbackSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,restoredFrom: z.string().min(1),timestamp: z.string().min(1),summary: SummaryResponseFieldSchema.optional(),diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.tsindex 261f485cd..7b38cd9e0 100644--- a/packages/core/src/schemas/api/tags-search.ts+++ b/packages/core/src/schemas/api/tags-search.ts@@ -13,6 +13,7 @@ import {checkAgentContent,summaryField,} from './_shared.ts';+import { agentWriteOutcomeWireFields } from './agent-write-outcome.ts';export const TagSummaryEntrySchema = z.object({@@ -145,6 +146,7 @@ export type TemplatePutRequest = z.infer<typeof TemplatePutRequestSchema>;export const TemplatePutSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,path: z.string().min(1),created: z.boolean(),warnings: z.array(z.string()),@@ -167,6 +169,7 @@ export type TemplateImportRequest = z.infer<typeof TemplateImportRequestSchema>;export const TemplateImportSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,path: z.string().min(1),created: z.boolean(),warnings: z.array(z.string()),@@ -398,6 +401,7 @@ const authoringWarningCodesField = z.array(z.enum(SKILL_AUTHORING_WARNING_CODES)export const SkillPutSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,path: z.string().min(1),created: z.boolean(),warnings: z.array(z.string()),@@ -693,6 +697,7 @@ export type SkillFilePutRequest = z.infer<typeof SkillFilePutRequestSchema>;export const SkillFilePutSuccessSchema = z.object({+ ...agentWriteOutcomeWireFields,path: z.string().min(1),created: z.boolean(),kind: SkillFileKindSchema,diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 2dd528606..ca9fdc6a5 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -103,9 +103,9 @@ Every `.md` / `.mdx` needs YAML frontmatter — `title` + `description` required- **Use a template when one fits (MUST).** Instantiate via `write({ document: { path, template } })`; inherited templates count. Skip only when none match or the user asked for free-form (note why in chat). Create templates proactively when a shape recurs.- **When recurring per-doc properties emerge (MUST).** Writing the same frontmatter on multiple siblings → bake those starting values into a template (`write({ template })`). Folder frontmatter does not cascade values into docs.-## Conflict-aware writes+## Write outcomes-For a conflict refusal, follow the tool's recovery instructions and `references/conflict-resolution.md`; ask the user to resolve tracked conflicts in the app.+For every write result, read `outcome` and follow `nextStep` (`references/conflict-resolution.md` has each outcome's move): never repeat a write that landed (`merged-first`, `both-kept`, `projection-held`), and when a refusal says `nextStep: none`, nothing you send changes it: tell the user which file and what the result says, and carry on.## Anti-patterns — the top offendersdiff --git a/packages/server/assets/skills/project/references/conflict-resolution.md b/packages/server/assets/skills/project/references/conflict-resolution.mdindex 4d5b53a4f..e07ed5270 100644--- a/packages/server/assets/skills/project/references/conflict-resolution.md+++ b/packages/server/assets/skills/project/references/conflict-resolution.md@@ -1,50 +1,69 @@-# Conflict-aware writes+# Write outcomes and conflicts-A doc can land in conflict through a Git merge, a pull that collides with a local overlay, or OK's own reconciliation of the editor against disk. Reconciliation also protects an acknowledged edit when another app restores the exact older file version; that `stale-external-write` path works with GitHub sync disabled. The MCP server refuses a mutating call against a conflicted doc with a structured RFC 9457 response:+A document, template or skill write through `write` or `edit`, a document `restore_version` and a `lint` fix that changed the doc carry three fields once the server answers, success or not: `outcome` (what happened to the write), `saved` (whether its bytes were in the file when the server answered) and `nextStep` (what to do next). Read them before anything else in the result, and follow `nextStep`.-```json-{- "type": "urn:ok:error:doc-in-conflict",- "title": "Document is in conflict.",- "status": 409,- "detail": "The document is in a conflict state. Ask the user to resolve it in the OpenKnowledge app, then retry.",- "file": "notes/sso.md",- "conflict": { "kind": "reconcile", "reason": "disk-markers" },- "resolutionOptions": ["mine", "content", "delete"]-}-```+| `outcome` | What happened | `saved` | Your move |+| - | - | - | - |+| `applied` | The write landed and is saved. | `true` | Carry on (`nextStep: none`); with a `content-divergence` warning `nextStep` is `re-read` (below). |+| `merged-first` | An outside change to the file was handled before your write was saved: merged in, or saved to the doc's history when it could not be merged. Your write landed. | `true` | Re-read before the next edit (`exec("cat <path>")`). Never repeat the write. |+| `both-kept` | Your write landed and is saved. A block was changed both here and outside, so both versions are in the doc, this doc's version first and the outside version directly under it. | `true` | Never repeat the write. Re-read, and remove the duplicate with an ordinary `edit` if your task calls for it. |+| `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. |-The gate covers `write`, `edit`, `delete`, `move`, `restore_version`, and agent undo (the doc-CRDT write spine; template/folder ops are fs-direct). You cannot route around it by writing content that byte-matches one of the stages. The gate refuses on tracked state, not on body equality.+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 write that first detects a stale file during its final disk flush returns `urn:ok:error:stale-external-write` (409). The edit reached collaborative state and the recovery snapshot, but the disk write did not happen. Ask the user to resolve it in the app, then re-read. Do not repeat the operation: a retried append can duplicate content already retained in the current version.+## What each result asks of you-**You cannot resolve a conflict over MCP.** There is no conflict tool, and `exec` is read-only. On either 409, stop writing to that file, tell the user which file is in conflict, and ask them to resolve it in the OpenKnowledge app. After they confirm, re-read the document. For `doc-in-conflict`, the operation was refused; retry only if it is still needed. For `stale-external-write`, the operation already reached collaborative state; do not repeat it. Compare the resolved document with the intended result and make only any remaining edit.+The fields come from one table on the server, and this one repeats it: for every result below, the move matches its `nextStep`. With `none`, nothing you send changes the result: stop writing to that file, tell the user which file it is and what the result says, and carry on with other work; do not wait on them. **You cannot resolve a conflict over MCP**: there is no conflict tool, no write tool takes a conflict parameter, and `exec` is read-only. Never work around a refusal by writing the same content somewhere else.-## The three kinds+| Result | `outcome` | `saved` | `nextStep` | Your move |+| - | - | - | - | - |+| `both-kept` (409) | `both-kept` | `true` | `re-read` | Never repeat the write. Re-read, and remove the duplicate with an ordinary edit if your task calls for it. |+| `applied` (200) with a `content-divergence` warning | `applied` | `true` | `re-read` | The write landed and is saved, but the stored text differs from what you sent. Re-read before the next edit. |+| `concurrent-overwrite-refused` (409) | `refused` | `false` | `retry` | Wait the seconds `retryAfterSeconds` names, then send the write again; an `append` or `prepend` is never refused this way. |+| `too-many-agent-sessions` (503) | `refused` | `false` | `retry` | Wait the seconds it names, then send the write again. |+| `doc-not-found` (404) | `refused` | `false` | `retry` | Send the edit again at the path the detail or `candidates` names. |+| `reserved-doc-name` (400) | `refused` | `false` | `retry` | Send the write again under a different name. |+| `frontmatter-malformed` (400) | `refused` | `false` | `retry` | Fix the YAML the detail points at, then send the write again. |+| `frontmatter-edit-not-supported` (400) | `refused` | `false` | `retry` | Send the frontmatter change again as a frontmatter patch. |+| `invalid-frontmatter-patch` (400) | `refused` | `false` | `retry` | Correct the patch the detail describes, then send it again. |+| `target-not-found` (404) | `refused` | `false` | `re-read` | Re-read the document, then make the edit against text that is there. |+| `stale-target` (409) | `refused` | `false` | `re-read` | Re-read the document, then make the edit against what is there now. |+| `doc-in-conflict` (409) | `refused` | `false` | `none` | Tell the user which file it is. Write to it again only after they say the conflict is resolved. |+| `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 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. |+| `doc-removed` (409) after a rename | `refused` | `false` | `re-read` | Re-read the document at the new path the detail names, and re-apply your change there if it is missing. |+| `doc-removed` (409) after a delete | `refused` | `false` | `none` | Tell the user the file is gone; the edit is in the document's history (timeline). Do not re-create the document on your own. |+| `server-stopped` (503) | `refused` | `false` | `none` | Tell the user; after the restart the edit is in the document's history (timeline). |+| `server-stopped` (503) during a move | `refused` | `false` | `re-read` | After the restart, re-read the document at the new name the detail gives, and re-apply the edit only if it is missing. |+| `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. |+| `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.++Stale-save recovery data lives in `.ok/local/stale-external-writes.json`, with owner-only permissions. Do not delete that file or restart with empty state when it is corrupt or unreadable; it may hold the only copy of protected edits. Preserve it, restore a known-good backup, and run `ok bug-report` from the project directory for diagnostics.++## Git conflicts++A Git merge or a pull that collides with local edits puts a doc in conflict until the user resolves it in the app. `conflict.kind` says which:| `conflict.kind` | Where it comes from | What a resolve does || - | - | - || `merge-native` | a git merge left unmerged stages in the index | stages your choice with git, and commits the merge once no `merge-native` conflict is left (other kinds do not hold the commit back) || `working-tree` | a pull-only overlay collision, pinned to the origin blob it collided with | writes the chosen bytes to disk; nothing is committed |-| `reconcile` | OK's own three-way merge of the editor against disk, including stale external saves. No git object holds the stages, so OK snapshots them at detection | writes the chosen bytes to disk and into the loaded document; no git command runs |--A `reconcile` conflict carries a `reason`: `refused-conflict-markers` (the disk bytes already carried markers), `disk-markers` (markers landed on disk under an open doc), `refused-no-base` (there was no acknowledged version to merge against), `refused-too-large` (a merge past the size cap or one that failed OpenKnowledge's fidelity check, raised only when the outside version could not be saved to history), or `stale-external-write` (an older displaced version returned on disk). `merged-with-markers` appears only on entries recorded by earlier versions, or in the rare case where both versions were merged but could not be applied to the open document. An outside edit to the same block as edits made here is not a conflict: both versions are kept, this document's version first, and your write reports `disk-edit-reconciled` with `mergeOutcome: "both-kept"` (see `references/doc-editing.md`). The compatibility `conflictKind` field is `stale-external-write` for that last reason and `git` otherwise.--## What the user choosesThe controls depend on the conflict's shape:| Shape | What the app shows | Controls || - | - | - |-| Conflict markers (`resolutionOptions` includes `content`) | The Conflict view, comparing both sides | **Accept current**, **Accept incoming** and, where available, **Accept both** for each conflict; the user then applies the resolution |-| Whole file, such as `refused-too-large` (no `content` option) | A preview of the user's version | **Keep my version**, plus **Use their version** and **Delete the file** when offered |+| Conflict markers | The Conflict view, comparing both sides | **Accept current**, **Accept incoming** and, where available, **Accept both** for each conflict; the user then applies the resolution || Deleted locally, modified upstream | A preview of the upstream version | **Keep file deleted**, plus **Restore with remote changes** when offered || Modified locally, deleted upstream | A preview of the user's version | **Keep my version** or **Accept their deletion** |-For a stale external write, Current is the version OpenKnowledge protected and Incoming is the restored older version. `resolutionOptions` lists the strategies the app offers for that file; no MCP tool accepts them, so never try to apply one yourself. Explain what each choice would keep, but leave the choice and application to the user.--If applying a resolution fails, ask the user to inspect the remaining conflict in the app. OpenKnowledge retains unresolved conflict and recovery state. Wait for the user to finish, then re-read the document before deciding what work remains.--A conflict can also close without you. Resolving a merge with raw git outside the app prunes the `merge-native` entry on the next disk change or HEAD move, and a `reconcile` conflict whose file comes back clean on disk dissolves on the next watcher pass.--Stale-save recovery data lives in `.ok/local/stale-external-writes.json`, with owner-only permissions. Do not delete that file or restart with empty state when it is corrupt or unreadable; it may hold the only copy of protected edits. Preserve it, restore a known-good backup, and run `ok bug-report` from the project directory for diagnostics. An unresolved conflict does not expire with the displaced-hash window.+Explain what each choice would keep, but leave the choice and its application to the user. If applying a resolution fails, ask the user to inspect the remaining conflict in the app; wait for them to finish, then re-read the doc before deciding what work remains. Resolving a merge with raw git outside the app prunes the `merge-native` entry on the next disk change or HEAD move.diff --git a/packages/server/assets/skills/project/references/doc-editing.md b/packages/server/assets/skills/project/references/doc-editing.mdindex 87f42c7ba..37434d932 100644--- a/packages/server/assets/skills/project/references/doc-editing.md+++ b/packages/server/assets/skills/project/references/doc-editing.md@@ -10,4 +10,4 @@**MDX.** To author an MDX doc (the KB renders MDX/JSX components), set `extension: ".mdx"` on the create: `write({ document: { path: "guides/widget", content, extension: ".mdx", position: "replace" } })` lands `guides/widget.mdx`. A `.mdx` suffix typed into `path` works too (the `extension` field wins if you pass both); omit both and it lands `.md`. An existing doc keeps its on-disk extension regardless — changing it in place isn't available via the MCP today.-**Advisory warnings on writes.** `write` and `edit` responses may include `structuredContent.document.warnings` (batch: per-doc `structuredContent.documents[].warnings`) — advisory entries discriminated by `kind`, each also summarized as a `⚠` line in the response text. The write always landed; the entries tell you what to do next. Write-integrity kinds mean re-read the doc (`exec("cat <path>")`) before continuing: `content-divergence` (`{ kind, intendedBytes, actualBytes, byteDelta, hint }` — the converged Y.Text doesn't match what the payload composed to: concurrent peer residue, or — rare — a primitive regression) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write landed on top; `mergeOutcome` says how: `clean`, `merged`, `both-kept` or `kept-live`). With `"both-kept"` the out-of-band edit changed the same blocks as edits made here, and three counts say what landed: `duplicatedBlocks` blocks are in the doc twice, this doc's version first and the out-of-band version directly under it; `restoredDeletedHere` blocks deleted here came back with the out-of-band version because it changed them; `restoredDeletedOutside` blocks the out-of-band edit deleted stayed with this doc's version because they were changed here. With `"kept-live"` it could not be merged, so the version here stayed and the out-of-band version was saved to the doc's history. Both carry `nextStep: "re-read"`, and in both your write landed: do not retry it. Re-read, and after `both-kept` remove a duplicate, or delete a block restored over a deletion here, with an ordinary `edit` if your task calls for it. A `mergeOutcome` or `nextStep` you do not know means the same as `merged`: re-read. The renderability kind `mermaid-parse-error` (`{ kind, fenceIndex, fenceFirstLine, message, line? }`) means that mermaid fence will not render — fix the fence and re-edit. The top-level `warning` field on write tools is unrelated: it is the preview-attach hint (`action: "attach-preview-once" | "start-ui"`), not an advisory — a separate key from `document.warnings`, and the two can coexist on one response.+**Advisory warnings on writes.** `write` and `edit` responses may include `structuredContent.document.warnings` (batch: per-doc `structuredContent.documents[].warnings`) — advisory entries discriminated by `kind`, each also summarized as a `⚠` line in the response text. What to do next is the result's `outcome` and `nextStep` (`references/conflict-resolution.md`); the entries say why. Write-integrity kinds come with `nextStep: re-read`, so re-read the doc (`exec("cat <path>")`) before continuing: `content-divergence` (`{ kind, intendedBytes, actualBytes, byteDelta, hint }` — the converged Y.Text doesn't match what the payload composed to: concurrent peer residue, or — rare — a primitive regression; the write is `applied`) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write landed on top; `mergeOutcome` says how: `clean`, `merged`, `both-kept` or `kept-live`). With `"both-kept"` the out-of-band edit changed the same blocks as edits made here, and three counts say what landed: `duplicatedBlocks` blocks are in the doc twice, this doc's version first and the out-of-band version directly under it; `restoredDeletedHere` blocks deleted here came back with the out-of-band version because it changed them; `restoredDeletedOutside` blocks the out-of-band edit deleted stayed with this doc's version because they were changed here. With `"kept-live"` it could not be merged, so the version here stayed and the out-of-band version was saved to the doc's history. In both your write landed: do not retry it. Re-read, and after `both-kept` remove a duplicate, or delete a block restored over a deletion here, with an ordinary `edit` if your task calls for it. A `mergeOutcome` you do not know means the same as `merged`: re-read. The renderability kind `mermaid-parse-error` (`{ kind, fenceIndex, fenceFirstLine, message, line? }`) means that mermaid fence will not render — fix the fence and re-edit. The top-level `warning` field on write tools is unrelated: it is the preview-attach hint (`action: "attach-preview-once" | "start-ui"`), not an advisory — a separate key from `document.warnings`, and the two can coexist on one response.diff --git a/packages/server/src/agent-write-outcome.test.ts b/packages/server/src/agent-write-outcome.test.tsnew file mode 100644index 000000000..56de77992--- /dev/null+++ b/packages/server/src/agent-write-outcome.test.ts@@ -0,0 +1,157 @@+import { describe, expect, test } from 'vitest';+import {+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+ outcomeOfStoreFailure,+ REFUSAL_OUTCOMES,+ reportedOutcome,+} from './agent-write-outcome.ts';+import {+ OK_DOC_MOVED,+ OK_DOC_REMOVED,+ OK_PATH_UNRESOLVABLE,+ OK_SERVER_STOPPED,+ OK_STORE_DISCARDED,+ OK_STORE_HELD,+ OK_STORE_REFUSED,+ OK_WRITE_REPLACED,+ type StoreFailure,+} from './document-durability-state.ts';++const steps = (fields: { outcome: string; saved: boolean; nextStep: string }) =>+ `${fields.outcome}/${fields.saved ? 'saved' : 'unsaved'}/${fields.nextStep}`;++describe('the outcome of each refusal', () => {+ test('a mistake in the request is retried once corrected, and only the unchangeable ones say none', () => {+ expect(+ Object.fromEntries(Object.entries(REFUSAL_OUTCOMES).map(([type, f]) => [type, steps(f)])),+ ).toEqual({+ 'urn:ok:error:concurrent-overwrite-refused': 'refused/unsaved/retry',+ 'urn:ok:error:too-many-agent-sessions': 'refused/unsaved/retry',+ 'urn:ok:error:doc-not-found': 'refused/unsaved/retry',+ 'urn:ok:error:reserved-doc-name': 'refused/unsaved/retry',+ 'urn:ok:error:frontmatter-malformed': 'refused/unsaved/retry',+ 'urn:ok:error:frontmatter-edit-not-supported': 'refused/unsaved/retry',+ 'urn:ok:error:invalid-frontmatter-patch': 'refused/unsaved/retry',+ 'urn:ok:error:target-not-found': 'refused/unsaved/re-read',+ 'urn:ok:error:stale-target': 'refused/unsaved/re-read',+ 'urn:ok:error:doc-in-conflict': 'refused/unsaved/none',+ 'urn:ok:error:stale-external-write': 'refused/unsaved/none',+ });+ });++ test.each<[string, StoreFailure, string]>([+ [+ 'a held save',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unreadable' } },+ 'projection-held/unsaved/re-read',+ ],+ [+ 'a held save still running',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unsettled' } },+ 'projection-held/unsaved/re-read',+ ],+ [+ 'a no-base hold',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unreadable', noBase: true } },+ 'refused/unsaved/none',+ ],+ [+ 'a conflict hold',+ { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-conflict' } },+ 'refused/unsaved/none',+ ],+ ['a carried move', { code: OK_DOC_MOVED, message: 'm' }, 'projection-held/unsaved/re-read'],+ [+ 'a branch switch',+ { code: OK_STORE_DISCARDED, message: 'm' },+ 'projection-held/unsaved/re-read',+ ],+ [+ 'a delete',+ { code: OK_DOC_REMOVED, message: 'm', removal: { kind: 'deleted-outside' } },+ 'refused/unsaved/none',+ ],+ [+ 'a rename not carried',+ { code: OK_DOC_REMOVED, message: 'm', removal: { kind: 'renamed', renamedTo: 'b' } },+ 'refused/unsaved/re-read',+ ],+ [+ 'a shutdown with the file missing',+ { code: OK_SERVER_STOPPED, message: 'm' },+ 'refused/unsaved/none',+ ],+ [+ 'a shutdown during a move',+ { code: OK_SERVER_STOPPED, message: 'm', removal: { kind: 'renamed', renamedTo: 'b' } },+ 'refused/unsaved/re-read',+ ],+ ['a path fault', { code: OK_PATH_UNRESOLVABLE, message: 'm' }, 'refused/unsaved/none'],+ ['a refused store', { code: OK_STORE_REFUSED, message: 'm' }, 'refused/unsaved/re-read'],+ ['a replaced write', { code: OK_WRITE_REPLACED, message: 'm' }, 'refused/unsaved/re-read'],+ ['an errno', { code: 'EACCES', message: 'm' }, 'refused/unsaved/re-read'],+ ])('%s maps to one outcome', (_name, failure, expected) => {+ expect(steps(outcomeOfStoreFailure(failure))).toBe(expected);+ });+});++describe('the routes the app also calls', () => {+ test('answer 200 only for a save still running at the end of the wait and a write the file replaced', () => {+ expect(+ answeredWithSuccessOnAppRoutes({+ code: OK_STORE_HELD,+ message: 'm',+ held: { reason: 'pending-unsettled' },+ }),+ ).toBe(true);+ expect(+ answeredWithSuccessOnAppRoutes({+ code: OK_STORE_HELD,+ message: 'm',+ held: { reason: 'pending-rename' },+ }),+ ).toBe(true);+ expect(answeredWithSuccessOnAppRoutes({ code: OK_WRITE_REPLACED, message: 'm' })).toBe(true);+ expect(+ answeredWithSuccessOnAppRoutes({+ code: OK_STORE_HELD,+ message: 'm',+ held: { reason: 'pending-unreadable' },+ }),+ ).toBe(false);+ expect(answeredWithSuccessOnAppRoutes({ code: OK_DOC_REMOVED, message: 'm' })).toBe(false);+ });+});++describe('a saved write', () => {+ test('reads both-kept over merged-first over applied, and a flush failure by its code', () => {+ expect(steps(outcomeOfSavedWrite(undefined, null))).toBe('applied/saved/none');+ expect(steps(outcomeOfSavedWrite({ reconciled: true, mergeOutcome: 'kept-live' }, null))).toBe(+ 'merged-first/saved/re-read',+ );+ expect(+ steps(+ outcomeOfSavedWrite(+ { reconciled: true, mergeOutcome: 'clean' },+ { kind: 'taken-in', merge: 'both-kept' },+ ),+ ),+ ).toBe('both-kept/saved/re-read');+ expect(+ steps(+ outcomeOfSavedWrite(undefined, {+ kind: 'failure',+ failure: { code: OK_STORE_HELD, message: 'm', held: { reason: 'pending-unsettled' } },+ }),+ ),+ ).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.tsnew file mode 100644index 000000000..dcbd5426e--- /dev/null+++ b/packages/server/src/agent-write-outcome.ts@@ -0,0 +1,155 @@+import type {+ AgentWriteOutcomeFields,+ ProblemType,+ ReconcileMergeOutcome,+} from '@inkeep/open-knowledge-core';+import {+ isConfigDoc,+ isEditableTextDoc,+ isExcalidrawDoc,+ isManagedArtifactDoc,+ isMermaidDoc,+} from './cc1-broadcast.ts';+import {+ OK_DOC_MOVED,+ OK_DOC_REMOVED,+ OK_PATH_UNRESOLVABLE,+ OK_SERVER_STOPPED,+ OK_STORE_DISCARDED,+ OK_STORE_HELD,+ OK_STORE_REFUSED,+ OK_WRITE_REPLACED,+ type StoreFailure,+} from './document-durability-state.ts';++const APPLIED: AgentWriteOutcomeFields = {+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+};++const APPLIED_WITH_DIVERGENCE: AgentWriteOutcomeFields = {+ outcome: 'applied',+ saved: true,+ nextStep: 're-read',+};++const MERGED_FIRST: AgentWriteOutcomeFields = {+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+};++const BOTH_KEPT: AgentWriteOutcomeFields = {+ outcome: 'both-kept',+ saved: true,+ nextStep: 're-read',+};++const PROJECTION_HELD: AgentWriteOutcomeFields = {+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+};++const REFUSED_RETRY: AgentWriteOutcomeFields = {+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+};++const REFUSED_RE_READ: AgentWriteOutcomeFields = {+ outcome: 'refused',+ saved: false,+ nextStep: 're-read',+};++const REFUSED_NONE: AgentWriteOutcomeFields = {+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+};++export const REFUSAL_OUTCOMES = {+ 'urn:ok:error:concurrent-overwrite-refused': REFUSED_RETRY,+ 'urn:ok:error:too-many-agent-sessions': REFUSED_RETRY,+ 'urn:ok:error:doc-not-found': REFUSED_RETRY,+ 'urn:ok:error:reserved-doc-name': REFUSED_RETRY,+ 'urn:ok:error:frontmatter-malformed': REFUSED_RETRY,+ 'urn:ok:error:frontmatter-edit-not-supported': REFUSED_RETRY,+ 'urn:ok:error:invalid-frontmatter-patch': REFUSED_RETRY,+ 'urn:ok:error:target-not-found': REFUSED_RE_READ,+ 'urn:ok:error:stale-target': REFUSED_RE_READ,+ 'urn:ok:error:doc-in-conflict': REFUSED_NONE,+ 'urn:ok:error:stale-external-write': REFUSED_NONE,+} as const satisfies Partial<Record<ProblemType, AgentWriteOutcomeFields>>;++export function outcomeOfStoreFailure(failure: StoreFailure): AgentWriteOutcomeFields {+ switch (failure.code) {+ case OK_STORE_HELD:+ return failure.held?.noBase === true || failure.held?.reason === 'pending-conflict'+ ? REFUSED_NONE+ : PROJECTION_HELD;+ case OK_DOC_MOVED:+ case OK_STORE_DISCARDED:+ return PROJECTION_HELD;+ case OK_DOC_REMOVED:+ case OK_SERVER_STOPPED:+ return failure.removal?.kind === 'renamed' ? REFUSED_RE_READ : REFUSED_NONE;+ case OK_PATH_UNRESOLVABLE:+ return REFUSED_NONE;+ case OK_STORE_REFUSED:+ case OK_WRITE_REPLACED:+ return REFUSED_RE_READ;+ default:+ return REFUSED_RE_READ;+ }+}++export function answeredWithSuccessOnAppRoutes(failure: StoreFailure): boolean {+ return (+ failure.code === OK_WRITE_REPLACED ||+ (failure.code === OK_STORE_HELD &&+ (failure.held?.reason === 'pending-unsettled' || failure.held?.reason === 'pending-rename'))+ );+}++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' }+ | { kind: 'taken-in'; merge: ReconcileMergeOutcome }+ | null;++export function outcomeOfSavedWrite(+ beforeWrite:+ | { readonly reconciled: boolean; readonly mergeOutcome?: ReconcileMergeOutcome }+ | undefined,+ flush: AgentWriteFlushOutcome,+ landedWithDivergence = false,+): AgentWriteOutcomeFields {+ if (flush?.kind === 'failure') return outcomeOfStoreFailure(flush.failure);+ if (flush?.kind === 'stale-external-write') {+ return REFUSAL_OUTCOMES['urn:ok:error:stale-external-write'];+ }+ const atSave = flush?.kind === 'taken-in' ? flush.merge : undefined;+ if (beforeWrite?.mergeOutcome === 'both-kept' || atSave === 'both-kept') return BOTH_KEPT;+ 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/api-agent-patch.test.ts b/packages/server/src/api-agent-patch.test.tsindex 5bb31b1d0..873a870cf 100644--- a/packages/server/src/api-agent-patch.test.ts+++ b/packages/server/src/api-agent-patch.test.ts@@ -98,6 +98,9 @@ describe('POST /api/agent-patch', () => {subscriberCount: expect.any(Number),systemSubscriberCount: expect.any(Number),brokenLinks: [],+ outcome: 'applied',+ saved: true,+ nextStep: 'none',});expect(ytext.toString()).toBe('# Notes\n\nProject Alpha appears first. Later, Project Alpha (linked) appears second.\n',@@ -174,6 +177,9 @@ describe('POST /api/agent-patch', () => {subscriberCount: expect.any(Number),systemSubscriberCount: expect.any(Number),brokenLinks: [],+ outcome: 'applied',+ saved: true,+ nextStep: 'none',});expect(ytext.toString()).toBe('# Notes\n\nProject Alpha (linked) appears first. Later, Project Alpha appears second.\n',diff --git a/packages/server/src/api-agent-write-batch-persistence-failure.test.ts b/packages/server/src/api-agent-write-batch-persistence-failure.test.tsindex d00005939..8ffc495ba 100644--- a/packages/server/src/api-agent-write-batch-persistence-failure.test.ts+++ b/packages/server/src/api-agent-write-batch-persistence-failure.test.ts@@ -156,18 +156,22 @@ describe('agent-write-batch — store-refused flush failure rendering', () => {expect(response.status).toBe(200);const { results } = JSON.parse(response.body) as {- results: Array<{ status: string; error?: Record<string, unknown> }>;+ results: Array<{ status: string; error?: Record<string, unknown>; outcome?: string }>;};- expect(results[0]?.status).toBe('error');+ expect(results[0]).toMatchObject({+ status: 'error',+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+ });expect(results[0]?.error).toMatchObject({type: 'urn:ok:error:save-held',reason: 'pending-conflict',- retryWhen: 'conflict-resolved',- nextStep: 're-read',});- expect(String(results[0]?.error?.detail)).toContain(- 'after the conflict on this document is resolved',- );+ expect(results[0]?.error).not.toHaveProperty('outcome');+ expect(results[0]?.error).not.toHaveProperty('saved');+ expect(results[0]?.error).not.toHaveProperty('nextStep');+ expect(String(results[0]?.error?.detail)).toContain('tell the user which file it is');expect(String(results[0]?.error?.detail)).toContain('Do not repeat this write');});diff --git a/packages/server/src/api-agent-write-deferred-store-wait.test.ts b/packages/server/src/api-agent-write-deferred-store-wait.test.tsindex a33dc7006..317c72aef 100644--- a/packages/server/src/api-agent-write-deferred-store-wait.test.ts+++ b/packages/server/src/api-agent-write-deferred-store-wait.test.ts@@ -129,7 +129,7 @@ function unsettledEvents(warn: { mock: { calls: unknown[][] } }): Array<Record<s}describe('agent-write flush: bounded wait for a deferred store', () => {- test('acknowledges once the bound elapses with the store still deferred, and reports it', async () => {+ test('answers projection-held once the bound elapses with the store still deferred, and reports it', async () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const docName = 'held-store';@@ -150,7 +150,14 @@ describe('agent-write flush: bounded wait for a deferred store', () => {await vi.advanceTimersByTimeAsync(1);const response = await responding;- expect(response.status).toBe(200);+ expect(response.status).toBe(503);+ expect(JSON.parse(response.body)).toMatchObject({+ type: 'urn:ok:error:save-held',+ reason: 'pending-unsettled',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });expect(unsettledEvents(warn)).toEqual([expect.objectContaining({event: 'agent-write-deferred-store-unsettled',@@ -182,8 +189,12 @@ describe('agent-write flush: bounded wait for a deferred store', () => {const response = await responding;expect(response.status).toBe(200);- const { results } = JSON.parse(response.body) as { results: Array<{ status: string }> };- expect(results.map((result) => result.status)).toEqual(['written', 'written', 'written']);+ const { results } = JSON.parse(response.body) as {+ results: Array<{ status: string; outcome?: string; error?: { reason?: string } }>;+ };+ expect(results.map((result) => [result.status, result.outcome, result.error?.reason])).toEqual(+ docNames.map(() => ['error', 'projection-held', 'pending-unsettled']),+ );});test('answers a native-route write within one budget when a branch switch outlives it', async () => {@@ -213,7 +224,12 @@ describe('agent-write flush: bounded wait for a deferred store', () => {await vi.advanceTimersByTimeAsync(1);const response = await responding;- expect(response.status).toBe(200);+ expect(response.status).toBe(503);+ expect(JSON.parse(response.body)).toMatchObject({+ type: 'urn:ok:error:save-held',+ outcome: 'projection-held',+ saved: false,+ });});test('does not hold a write behind a Git operation that cannot discard it', async () => {@@ -358,7 +374,7 @@ describe('agent-write flush: a document renamed outside the app while the writeexpect(body.detail).toContain('re-apply your change there');});- test("a carry still running when the write's wait runs out is acknowledged, never re-applied", async () => {+ test("a carry still running when the write's wait runs out answers projection-held, never re-applied", async () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });vi.spyOn(console, 'warn').mockImplementation(() => {});const docName = 'renamed-slow';@@ -380,6 +396,69 @@ describe('agent-write flush: a document renamed outside the app while the writeawait vi.advanceTimersByTimeAsync(1);const response = await responding;+ expect(response.status).toBe(503);+ expect(JSON.parse(response.body)).toMatchObject({+ type: 'urn:ok:error:save-held',+ reason: 'pending-rename',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });+ expect(JSON.parse(response.body).detail).toContain('moved-slow');+ });++ test('a write waiting on a carry when the server stops answers server-stopped at the new name', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const docName = 'renamed-at-shutdown';+ durabilityState.holdStores(docName);+ const deferral = durabilityState.openDeferredStore(docName);+ const flushWaiting = whenFlushStartsWaiting();++ const responding = postAgentWrite(docName);+ await flushWaiting;+ const carry = durabilityState.beginRenameCarry(docName);+ deferral.settle({ kind: 'failed', failure: refusedAsRenamed(docName, 'moved-late', carry) });+ durabilityState.endAllRenameCarries();+ const response = await responding;++ expect(response.status).toBe(503);+ const body = JSON.parse(response.body) as { detail?: string };+ expect(body).toMatchObject({+ type: 'urn:ok:error:server-stopped',+ outcome: 'refused',+ saved: false,+ nextStep: 're-read',+ });+ expect(body.detail).toContain('moved-late');+ expect(body.detail).toContain('Do not re-create the document under its old name');+ });+});++describe('a route the app also calls, when the save is still running at the end of the wait', () => {+ test('agent undo keeps its 200 and says projection-held, so the app does not undo twice', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const docName = 'undo-held';+ expect((await postAgentWrite(docName)).status).toBe(200);+ durabilityState.holdWriteAdmission();+ durabilityState.openDeferredStore(docName);+ const flushWaiting = whenFlushStartsWaiting();++ const responding = post('/api/agent-undo', {+ docName,+ connectionId: 'agent-claude-1',+ scope: 'last',+ });+ await flushWaiting;+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS);+ const response = await responding;+expect(response.status).toBe(200);+ expect(JSON.parse(response.body)).toMatchObject({+ undone: true,+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ });});});diff --git a/packages/server/src/api-extension.persistence-failure.test.ts b/packages/server/src/api-extension.persistence-failure.test.tsindex 1dc5bd8f9..8f5d07337 100644--- a/packages/server/src/api-extension.persistence-failure.test.ts+++ b/packages/server/src/api-extension.persistence-failure.test.ts@@ -34,7 +34,7 @@ function makeMockRes() {}describe('respondPersistenceFailure — store-refused', () => {- test('an OK_STORE_REFUSED failure renders a 503 with the store-refused URN and retry guidance', () => {+ test('an OK_STORE_REFUSED failure renders a 503 with the store-refused URN and re-read guidance', () => {const { res, writeHeadCalls, endCalls } = makeMockRes();const failure: StoreFailure = {code: OK_STORE_REFUSED,@@ -54,7 +54,9 @@ describe('respondPersistenceFailure — store-refused', () => {const detail = String(body.detail);expect(detail).toContain('recovery buffer');expect(detail).toContain('filesystem fault');- expect(detail).toContain('Retry');+ expect(detail).toContain('repeat the edit only if it is missing');+ expect(detail).not.toContain('Retry the write');+ expect(body).toMatchObject({ outcome: 'refused', saved: false, nextStep: 're-read' });});test('a non-refusal failure keeps the generic upload rendering instead of the 503', () => {@@ -70,7 +72,7 @@ describe('respondPersistenceFailure — store-refused', () => {});describe('respondPersistenceFailure: a held save', () => {- test('an OK_STORE_HELD failure renders a 503 save-held problem with its reason, cause, retry rule and a re-read next step', () => {+ test('an OK_STORE_HELD failure renders a 503 save-held problem with its reason, cause and the projection-held outcome', () => {const { res, writeHeadCalls, endCalls } = makeMockRes();const failure: StoreFailure = {code: OK_STORE_HELD,@@ -86,10 +88,12 @@ describe('respondPersistenceFailure: a held save', () => {type: 'urn:ok:error:save-held',title: 'Edit applied in memory; its save to disk is held.',reason: 'pending-unreadable',- retryWhen: 'next-save',causeCode: 'EBUSY',+ outcome: 'projection-held',+ saved: false,nextStep: 're-read',});+ expect(body).toMatchObject({ retryWhen: 'next-save' });const detail = String(body.detail);expect(detail).toContain('kept in the document');expect(detail).toContain('once the file can be read again');@@ -99,10 +103,10 @@ describe('respondPersistenceFailure: a held save', () => {});test.each([- { held: { reason: 'pending-intake-failed-no-base' as const } },+ { held: { reason: 'pending-intake-failed-no-base' as const, noBase: true as const } },{ held: { reason: 'pending-unreadable' as const, causeCode: 'EBUSY', noBase: true as const } },])(- 'a hold on a document with no agreed version ($held.reason) never says the edit is saved',+ 'a hold on a file with no agreed version ($held.reason) is refused and says any further write replaces it',({ held }) => {const { res, endCalls } = makeMockRes();respondPersistenceFailure(@@ -115,14 +119,17 @@ describe('respondPersistenceFailure: a held save', () => {type: 'urn:ok:error:save-held',reason: held.reason,retryWhen: 'replaced-on-next-edit',- nextStep: 're-read',+ outcome: 'refused',+ saved: false,+ nextStep: 'none',});const detail = String(body.detail);- expect(detail).toContain('This edit is not saved to the file');+ expect(detail).toContain('is not saved to the file');+ expect(detail).toContain('yours included');expect(detail).toContain('replaces the document with the file on disk');expect(detail).toContain('document history (timeline)');- expect(detail).toContain('re-apply this edit');- expect(detail).not.toContain('kept in the document');+ expect(detail).toContain('tell the user');+ expect(detail).not.toContain('re-read the document before editing it further');expect(detail).not.toMatch(/saves it|writes it|is saved after/);},);@@ -130,17 +137,38 @@ describe('respondPersistenceFailure: a held save', () => {test.each([{reason: 'pending-conflict' as const,- retryWhen: 'conflict-resolved',- says: 'after the conflict on this document is resolved',+ outcome: {+ outcome: 'refused',+ saved: false,+ nextStep: 'none',+ retryWhen: 'conflict-resolved',+ },+ says: 'tell the user which file it is',neverSays: 'idle save',},{reason: 'pending-intake-failed' as const,- retryWhen: 'next-save',+ outcome: {+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ retryWhen: 'next-save',+ },says: 'the idle save within a few minutes',neverSays: 'conflict',},- ])('a $reason hold states its own retry rule', ({ reason, retryWhen, says, neverSays }) => {+ {+ reason: 'pending-unsettled' as const,+ outcome: {+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ retryWhen: 'next-save',+ },+ says: 'finishes on its own',+ neverSays: 'idle save',+ },+ ])('a $reason hold states its own rule and outcome', ({ reason, outcome, says, neverSays }) => {const { res, endCalls } = makeMockRes();respondPersistenceFailure(res,@@ -148,7 +176,7 @@ describe('respondPersistenceFailure: a held save', () => {'agent-write-md',);const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;- expect(body).toMatchObject({ reason, retryWhen, nextStep: 're-read' });+ expect(body).toMatchObject({ reason, ...outcome });expect(String(body.detail)).toContain(says);expect(String(body.detail)).not.toContain(neverSays);});@@ -224,6 +252,50 @@ describe('respondPersistenceFailure: the save of a document whose file went missexpect(String(body.detail)).toContain('history');});+ test('a shutdown while a move was being carried names the new path and says re-read there', () => {+ const { res, writeHeadCalls, endCalls } = makeMockRes();+ respondPersistenceFailure(+ res,+ {+ code: OK_SERVER_STOPPED,+ message: 'The server stopped while notes was being moved outside the app to archive/notes',+ removal: { kind: 'renamed', renamedTo: 'archive/notes' },+ },+ 'agent-write-md',+ );++ expect(writeHeadCalls[0]?.status).toBe(503);+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body).toMatchObject({+ type: 'urn:ok:error:server-stopped',+ outcome: 'refused',+ saved: false,+ nextStep: 're-read',+ });+ expect(String(body.detail)).toContain('re-read the document at archive/notes');+ expect(String(body.detail)).toContain('Do not re-create the document under its old name');+ expect(String(body.detail)).not.toContain('re-create the document with write');+ });++ test('a rename carry still running when the write stops waiting names the new path', () => {+ const { res, endCalls } = makeMockRes();+ respondPersistenceFailure(+ res,+ {+ code: OK_STORE_HELD,+ message:+ 'notes was still being moved outside the app to archive/notes when the write stopped waiting',+ held: { reason: 'pending-rename' },+ },+ 'agent-write-md',+ );+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body).toMatchObject({ reason: 'pending-rename', outcome: 'projection-held' });+ expect(String(body.detail)).toContain('archive/notes');+ expect(String(body.detail)).toContain('re-read it at its new name');+ expect(String(body.detail)).toContain('do not re-create the document under its old name');+ });+test('a shutdown while the file was missing renders a 503 server-stopped', () => {const { res, writeHeadCalls, endCalls } = makeMockRes();const failure: StoreFailure = {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex e5004a3a0..8a92ad4ab 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -26,6 +26,7 @@ import {AGENTS_SKILLS_ROOT,AgentWriteBatchRequestSchema,AgentWriteBatchSuccessSchema,+ type AgentWriteOutcomeFields,AgentWriteRequestSchema,AgentWriteSuccessSchema,asTargetNamespace,@@ -180,6 +181,13 @@ import {resolveAgentType,UNIDENTIFIED_WRITER_ID,} from './agent-id.ts';+import {+ type AgentWriteFlushOutcome,+ outcomeOfSavedWrite,+ outcomeOfStoreFailure,+ REFUSAL_OUTCOMES,+ reportedOutcome,+} from './agent-write-outcome.ts';import {applyRenameMap,BacklinkIndexRequiredError,@@ -228,6 +236,7 @@ import {type DeferredStoreDiscardCause,type DocumentDurabilityState,editWasCarried,+ type HeldSaveReason,OK_DOC_MOVED,OK_DOC_REMOVED,OK_PATH_UNRESOLVABLE,@@ -235,6 +244,7 @@ import {OK_STORE_DISCARDED,OK_STORE_HELD,OK_STORE_REFUSED,+ OK_WRITE_REPLACED,type StoreFailure,type WrittenThrough,writtenThroughOf,@@ -242,6 +252,7 @@ import {import type { RefreshDocumentsFromDisk } from './document-refresh.ts';import {buildReconcileWarning,+ type ReconcileBeforeWriteResult,reconcileDiskBeforeAgentWrite,reviveFrozenResidentDoc,} from './external-change.ts';@@ -273,6 +284,7 @@ import {AGENT_SESSION_CAPACITY_TYPE,respondAgentSessionCapacity,} from './http/agent-session-capacity.ts';+import { respondBothKept } from './http/agent-write-response.ts';import { type ApiRouteTable, createApiRequestPipeline } from './http/api-pipeline.ts';import { createAssetRoutes } from './http/asset-routes.ts';import { createCommentRoutes } from './http/comment-routes.ts';@@ -368,7 +380,6 @@ import {incrementAgentWriteCalls,incrementSummariesProvided,incrementSummariesTruncated,- type StorePendingReason,} from './metrics.ts';import { isWithinDir, toPosix } from './path-utils.ts';import { assertProjectContentSubtree } from './project-content-scope.ts';@@ -1447,14 +1458,14 @@ function removedDocProblem(failure: StoreFailure) {type: 'urn:ok:error:doc-removed' as const,title:'Edit not saved to disk: the document was deleted outside the app, and the edit went to its history.',- detail: `${failure.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; re-create the document with write if you still want the content.`,+ detail: `${failure.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; tell the user the file was deleted, and do not re-create the document on your own.`,} satisfies BatchEntryError;case undefined:return {type: 'urn:ok:error:doc-removed' as const,title:'Edit applied in memory; disk write refused because the document is no longer on disk.',- detail: `${failure.message}. Retrying will not help: re-create the document before writing this content again.`,+ detail: `${failure.message}. Retrying will not help: tell the user the file is no longer on disk.`,} satisfies BatchEntryError;}}@@ -1469,11 +1480,14 @@ function movedDocProblem(failure: StoreFailure) {}function stoppedServerProblem(failure: StoreFailure) {+ const renamedTo = failure.removal?.kind === 'renamed' ? failure.removal.renamedTo : undefined;return {type: 'urn:ok:error:server-stopped' as const,- title:- "Edit not saved to disk: the server stopped while the document's file was missing, and the edit went to its history.",- detail: `${failure.message}. After OpenKnowledge restarts, find the edit in the document's history (the timeline), and re-create the document with write if you still want it.`,+ title: 'Edit not saved to disk: the server stopped before the edit reached disk.',+ detail:+ renamedTo === undefined+ ? `${failure.message}. After OpenKnowledge restarts, the edit is in the document's history (the timeline); tell the user.`+ : `${failure.message}. After OpenKnowledge restarts, re-read the document at ${renamedTo} to see whether it holds the edit, and re-apply the edit there if it is missing. Do not re-create the document under its old name.`,} satisfies BatchEntryError;}@@ -1482,7 +1496,16 @@ function pathFaultProblem(failure: StoreFailure) {type: 'urn:ok:error:path-escape' as const,title:'Edit applied in memory; disk write refused because the document path could not be resolved.',- detail: `${failure.message}. Retrying will not help: the path has to be repaired on disk before this content can be written.`,+ detail: `${failure.message}. Retrying will not help: tell the user the path has to be repaired on disk before this content can be written.`,+ } satisfies BatchEntryError;+}++function replacedWriteProblem(failure: StoreFailure) {+ return {+ type: 'urn:ok:error:write-replaced' as const,+ title:+ 'Edit not saved: the file on disk replaced the document, and the edit went to its history.',+ detail: `${failure.message}. OpenKnowledge had no agreed version of the file to merge the edit with, so it took the file in as it is and saved the document as it was, this edit included, to the document's history (the timeline). Re-read the document, and re-apply the edit if it is still needed.`,} satisfies BatchEntryError;}@@ -1532,7 +1555,7 @@ function discardedStoreProblem(failure: StoreFailure) {type HeldSaveRetry = 'next-save' | 'next-edit' | 'conflict-resolved' | 'replaced-on-next-edit';const HELD_SAVE_RULES: Readonly<- Record<StorePendingReason, { readonly retryWhen: HeldSaveRetry; readonly sentence: string }>+ Record<HeldSaveReason, { readonly retryWhen: HeldSaveRetry; readonly sentence: string }>> = {'pending-unreadable': {retryWhen: 'next-save',@@ -1555,9 +1578,9 @@ const HELD_SAVE_RULES: Readonly<'A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.',},'pending-intake-failed-no-base': {- retryWhen: 'replaced-on-next-edit',+ retryWhen: 'next-save',sentence:- 'This edit is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. The next edit to this document replaces the document with the file on disk and moves this edit, with any typing since, to the document history (timeline). Do not repeat this write now: after that next edit, re-read the document and re-apply this edit if it is still needed.',+ 'A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.',},'pending-no-intake': {retryWhen: 'next-edit',@@ -1566,24 +1589,43 @@ const HELD_SAVE_RULES: Readonly<'pending-conflict': {retryWhen: 'conflict-resolved',sentence:- 'It is saved after the conflict on this document is resolved; ask the user to resolve it in the OpenKnowledge app.',+ 'It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.',+ },+ 'pending-unsettled': {+ retryWhen: 'next-save',+ sentence:+ 'The save was still running when the write stopped waiting for it, and it finishes on its own.',+ },+ 'pending-rename': {+ retryWhen: 'next-save',+ sentence:+ 'The edit goes with the document to its new name, or to its history if the move cannot carry it. Do not repeat this write, and do not re-create the document under its old name: re-read it at its new name.',},};+const NO_BASE_HOLD_SENTENCE =+ 'This edit is in the document but is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. Any further write to this document, yours included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history (timeline). Do not write to this document again; tell the user that its file changed outside OpenKnowledge.';++function heldSaveDetail(failure: StoreFailure, reason: HeldSaveReason, noBase: boolean): string {+ if (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') {+ 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.`;+}+function heldSaveProblem(failure: StoreFailure) {const reason = failure.held?.reason ?? 'pending-unreadable';- const noBase = failure.held?.noBase === true || reason === 'pending-intake-failed-no-base';- const rule = HELD_SAVE_RULES[noBase ? 'pending-intake-failed-no-base' : reason];+ const noBase = failure.held?.noBase === true;return {type: 'urn:ok:error:save-held' as const,title: 'Edit applied in memory; its save to disk is held.',- detail: noBase- ? `${failure.message}. ${rule.sentence}`- : `${failure.message}. The edit is kept in the document. ${rule.sentence} Do not repeat this write: re-read the document before editing it further.`,+ detail: heldSaveDetail(failure, reason, noBase),reason,- retryWhen: rule.retryWhen,+ retryWhen: noBase ? ('replaced-on-next-edit' as const) : HELD_SAVE_RULES[reason].retryWhen,...(failure.held?.causeCode === undefined ? {} : { causeCode: failure.held.causeCode }),- nextStep: 're-read' as const,} satisfies BatchEntryError;}@@ -1592,48 +1634,68 @@ function refusedStoreProblem(failure: StoreFailure) {type: 'urn:ok:error:store-refused' as const,title:'Edit applied in memory; disk write refused because the duplication baseline could not be read.',- detail: `${failure.message}. The edit is applied in collaborative state and the document file on disk was not updated; a copy of the edited document is preserved in the server's recovery buffer unless that buffer is unavailable or unwritable. Retry the write once the filesystem fault is repaired.`,+ detail: `${failure.message}. The edit is applied in collaborative state and the document file on disk was not updated; a copy of the edited document is preserved in the server's recovery buffer unless that buffer is unavailable or unwritable. Do not repeat the write now: once the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.`,} satisfies BatchEntryError;}+function storeFailureProblem(+ failure: StoreFailure,+): { status: HttpErrorStatus; problem: BatchEntryError } | undefined {+ const fields = outcomeOfStoreFailure(failure);+ const withOutcome = (status: HttpErrorStatus, problem: BatchEntryError) => ({+ status,+ problem: { ...problem, ...fields },+ });+ switch (failure.code) {+ case OK_STORE_REFUSED:+ return withOutcome(503, refusedStoreProblem(failure));+ case OK_STORE_HELD:+ return withOutcome(503, heldSaveProblem(failure));+ case OK_DOC_REMOVED:+ return withOutcome(409, removedDocProblem(failure));+ case OK_STORE_DISCARDED:+ return withOutcome(409, discardedStoreProblem(failure));+ case OK_DOC_MOVED:+ return withOutcome(409, movedDocProblem(failure));+ case OK_SERVER_STOPPED:+ return withOutcome(503, stoppedServerProblem(failure));+ case OK_PATH_UNRESOLVABLE:+ return withOutcome(400, pathFaultProblem(failure));+ case OK_WRITE_REPLACED:+ return withOutcome(409, replacedWriteProblem(failure));+ default:+ return undefined;+ }+}++function withoutOutcomeFields(problem: BatchEntryError): BatchEntryError {+ const { outcome: _outcome, saved: _saved, nextStep: _nextStep, ...rest } = problem;+ return rest;+}++function storeFailureEntryProblem(failure: StoreFailure): BatchEntryError {+ const known = storeFailureProblem(failure);+ if (known) return withoutOutcomeFields(known.problem);+ return {+ type: classifyUploadErrno({ code: failure.code } as NodeJS.ErrnoException),+ title: 'Write applied in memory but failed to persist to disk.',+ detail: `${failure.code ?? 'unknown error'}: ${failure.message}. The content was NOT saved and will be lost if the server restarts.`,+ };+}+export function respondPersistenceFailure(res: ServerResponse,failure: StoreFailure,handler: string,): void {- if (failure.code === OK_STORE_REFUSED) {- const { type, title, detail } = refusedStoreProblem(failure);- errorResponse(res, 503, type, title, { handler, detail });- return;- }- if (failure.code === OK_STORE_HELD) {- const { type, title, detail, ...extensions } = heldSaveProblem(failure);- errorResponse(res, 503, type, title, { handler, detail, extensions });- return;- }- if (failure.code === OK_DOC_REMOVED) {- const { type, title, detail } = removedDocProblem(failure);- errorResponse(res, 409, type, title, { handler, detail });- return;- }- if (failure.code === OK_STORE_DISCARDED) {- const { type, title, detail } = discardedStoreProblem(failure);- errorResponse(res, 409, type, title, { handler, detail });- return;- }- if (failure.code === OK_DOC_MOVED) {- const { type, title, detail } = movedDocProblem(failure);- errorResponse(res, 409, type, title, { handler, detail });- return;- }- if (failure.code === OK_SERVER_STOPPED) {- const { type, title, detail } = stoppedServerProblem(failure);- errorResponse(res, 503, type, title, { handler, detail });- return;- }- if (failure.code === OK_PATH_UNRESOLVABLE) {- const { type, title, detail } = pathFaultProblem(failure);- errorResponse(res, 400, type, title, { handler, detail });+ const known = storeFailureProblem(failure);+ if (known) {+ const { type, title, detail, ...extensions } = known.problem;+ errorResponse(res, known.status, type, title, {+ handler,+ ...(detail === undefined ? {} : { detail }),+ extensions,+ });return;}const reason = classifyUploadErrno({ code: failure.code } as NodeJS.ErrnoException);@@ -1642,7 +1704,7 @@ export function respondPersistenceFailure(uploadStatusFor(reason),reason,`Write applied in memory but failed to persist to disk (${failure.code ?? 'unknown error'}): ${failure.message}. The content was NOT saved and will be lost if the server restarts.`,- { handler },+ { handler, extensions: { ...outcomeOfStoreFailure(failure) } },);}@@ -2060,10 +2122,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {});}- type FlushOutcome =- | { kind: 'failure'; failure: StoreFailure }- | { kind: 'stale-external-write' }- | null;+ type FlushOutcome = AgentWriteFlushOutcome;++ function heldUnsettled(docName: string, reason: HeldSaveReason, message: string): FlushOutcome {+ return {+ kind: 'failure',+ failure: { code: OK_STORE_HELD, message: `${docName} ${message}`, held: { reason } },+ };+ }async function answerForCarriedEdit(docName: string,@@ -2074,19 +2140,35 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {return { kind: 'failure', failure };}const answer = await durabilityState.awaitRenameCarry(docName, failure.removal.carry);- if (answer.kind === 'unsettled') {- log.warn(- { docName },- "[agent-write] the rename carry did not settle within the write's wait; acknowledging before it reaches disk",- );- return null;+ const renamedTo = failure.removal.renamedTo;+ switch (answer.kind) {+ case 'unsettled':+ return heldUnsettled(+ docName,+ 'pending-rename',+ `was still being moved outside the app to ${renamedTo} when the write stopped waiting`,+ );+ case 'stopped':+ return {+ kind: 'failure',+ failure: {+ code: OK_SERVER_STOPPED,+ message: `The server stopped while ${docName} was being moved outside the app to ${renamedTo}`,+ removal: { kind: 'renamed', renamedTo },+ },+ };+ case 'settled':+ return {+ kind: 'failure',+ failure: editWasCarried(writtenThrough, answer.carried)+ ? { ...failure, code: OK_DOC_MOVED }+ : failure,+ };+ default: {+ const unhandled: never = answer;+ throw new Error(`unhandled rename carry answer: ${JSON.stringify(unhandled)}`);+ }}- return {- kind: 'failure',- failure: editWasCarried(writtenThrough, answer.carried)- ? { ...failure, code: OK_DOC_MOVED }- : failure,- };}function writtenThroughOfResident(docName: string): WrittenThrough | undefined {@@ -2094,18 +2176,24 @@ 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 flushDiskAndDetectOutcome(docName: string,writtenThrough: WrittenThrough | undefined = writtenThroughOfResident(docName),): Promise<FlushOutcome> {- const debounceId = `onStoreDocument-${docName}`;- if (hocuspocus.debouncer.isDebounced(debounceId)) {- durabilityState.markAgentWriteStore(docName);- await hocuspocus.debouncer.executeNow(debounceId);+ if (markPendingAgentStore(docName)) {+ await hocuspocus.debouncer.executeNow(`onStoreDocument-${docName}`);}const deferredWaitStarted = Date.now();const deferredWait = await durabilityState.awaitDeferredStoreOutcome(docName);let failure: StoreFailure | undefined;+ let unsettled = false;switch (deferredWait?.kind) {case undefined:case 'completed':@@ -2117,6 +2205,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {failure = durabilityState.takeStoreFailure(docName) ?? deferredWait.failure;break;case 'unsettled': {+ unsettled = true;const waitedMs = Date.now() - deferredWaitStarted;console.warn(JSON.stringify({@@ -2128,7 +2217,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {);log.warn({ docName, waitedMs },- '[agent-write] deferred store still pending after the wait; acknowledging before it reaches disk',+ '[agent-write] deferred store still pending after the wait; answering that the save is held',);break;}@@ -2136,11 +2225,28 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {assertNeverDeferredStoreWait(deferredWait);}failure ??= durabilityState.takeStoreFailure(docName) ?? undefined;+ const atSave = durabilityState.readStoreIntake(docName, writtenThrough);if (failure) return answerForCarriedEdit(docName, failure, writtenThrough);if (durabilityState.takeStaleExternalWriteFreeze(docName)) {return { kind: 'stale-external-write' };}- return null;+ if (unsettled) {+ return heldUnsettled(+ docName,+ 'pending-unsettled',+ 'was still being saved when the write stopped waiting',+ );+ }+ if (atSave === 'disk-replaced') {+ return {+ kind: 'failure',+ failure: {+ code: OK_WRITE_REPLACED,+ message: `${docName} changed on disk, and its file replaced the document`,+ },+ };+ }+ return atSave === undefined ? null : { kind: 'taken-in', merge: atSave };}function staleExternalWriteProblem(docName: string) {@@ -2156,6 +2262,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {'/',),resolutionOptions: RESOLUTION_OPTIONS,+ ...REFUSAL_OUTCOMES['urn:ok:error:stale-external-write'],} satisfies BatchEntryError;}@@ -3746,7 +3853,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {400,'urn:ok:error:reserved-doc-name',`'${docName}' is a reserved document name.`,- { handler: 'agent-write' },+ {+ handler: 'agent-write',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },);return;}@@ -3851,15 +3961,24 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {onAgentWrite?.();const agentWriteWarning = buildReconcileWarning(agentWriteReconcile);+ const agentWriteBody = {+ timestamp,+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(agentWriteWarning ? { warnings: [agentWriteWarning] } : {}),+ };+ const agentWriteOutcome = reportedOutcome(+ docName,+ outcomeOfSavedWrite(agentWriteReconcile, flushOutcome),+ );+ if (agentWriteOutcome?.outcome === 'both-kept') {+ respondBothKept(res, 'agent-write', agentWriteBody, agentWriteOutcome);+ return;+ }successResponse(res,200,AgentWriteSuccessSchema,- {- timestamp,- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(agentWriteWarning ? { warnings: [agentWriteWarning] } : {}),- },+ { ...agentWriteBody, ...agentWriteOutcome },{ handler: 'agent-write' },);} catch (e) {@@ -3907,12 +4026,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {const timestamp = new Date().toISOString();- interface BatchErrorResult {+ interface BatchErrorResult extends Partial<AgentWriteOutcomeFields> {status: 'error';docName: string;error: BatchEntryError;}- interface BatchWrittenResult extends WriteLinkAdvisoryProjection {+ interface BatchWrittenResult+ extends WriteLinkAdvisoryProjection,+ Partial<AgentWriteOutcomeFields> {status: 'written';docName: string;summary?: SummaryResponse;@@ -3926,10 +4047,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {title: string,detail?: string,extensions?: Record<string, unknown>,+ outcome?: AgentWriteOutcomeFields,): BatchErrorResult => ({status: 'error',docName,error: { type, title, ...(detail !== undefined ? { detail } : {}), ...extensions },+ ...outcome,});const classifyEntryFailure = (docName: string, e: unknown): BatchErrorResult => {@@ -3941,6 +4064,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {CONCURRENT_OVERWRITE_REFUSED_TITLE,CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,{ retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS },+ REFUSAL_OUTCOMES['urn:ok:error:concurrent-overwrite-refused'],);}if (e instanceof DocInConflictError) {@@ -3961,6 +4085,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {detail,...envelope,},+ ...REFUSAL_OUTCOMES['urn:ok:error:doc-in-conflict'],};}if (e instanceof FrontmatterMalformedError) {@@ -3970,6 +4095,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {'urn:ok:error:frontmatter-malformed','Frontmatter YAML is malformed.',frontmatterRefusalDetail(e),+ undefined,+ REFUSAL_OUTCOMES['urn:ok:error:frontmatter-malformed'],);}if (e instanceof AgentSessionCapacityError) {@@ -3979,6 +4106,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {AGENT_SESSION_CAPACITY_TITLE,AGENT_SESSION_CAPACITY_DETAIL,AGENT_SESSION_CAPACITY_EXTENSIONS,+ REFUSAL_OUTCOMES['urn:ok:error:too-many-agent-sessions'],);}log.error(@@ -3995,14 +4123,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {interface PendingEntry {index: number;docName: string;- session: Awaited<ReturnType<typeof sessionManager.getSession>>;+ reconcile: ReconcileBeforeWriteResult;summaryResponse?: SummaryResponse;warnings: AdvisoryWarning[];+ diverged: boolean;}const results: (BatchResult | undefined)[] = new Array(body.docs.length);const pending: PendingEntry[] = [];const writtenThroughByDoc = new Map<string, WrittenThrough>();+ const writtenSourceByDoc = new Map<string, string>();try {const icon = iconFromClientName(clientName);@@ -4026,6 +4156,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {resolvedDocName,'urn:ok:error:reserved-doc-name',`'${resolvedDocName}' is a reserved document name.`,+ undefined,+ undefined,+ REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'],);continue;}@@ -4103,6 +4236,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {});}, session.origin);writtenThroughByDoc.set(resolvedDocName, writtenThroughOf(session.dc.document));+ writtenSourceByDoc.set(+ resolvedDocName,+ session.dc.document.getText('source').toString(),+ );+ markPendingAgentStore(resolvedDocName);} finally {disposeEntryEffectCapture();}@@ -4130,9 +4268,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {pending.push({index: i,docName: resolvedDocName,- session,+ reconcile,summaryResponse,warnings,+ diverged: writeDivergence !== undefined,});} catch (e) {results[i] = classifyEntryFailure(resolvedDocName, e);@@ -4140,39 +4279,21 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {}const flushErrors = new Map<string, BatchErrorResult['error'] | undefined>();+ const flushOutcomes = new Map<string, FlushOutcome>();for (const p of pending) {if (flushErrors.has(p.docName)) continue;const flushOutcome = await flushDiskAndDetectOutcome(p.docName,writtenThroughByDoc.get(p.docName),);+ flushOutcomes.set(p.docName, flushOutcome);if (flushOutcome?.kind === 'failure') {- if (flushOutcome.failure.code === OK_DOC_REMOVED) {- flushErrors.set(p.docName, removedDocProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_PATH_UNRESOLVABLE) {- flushErrors.set(p.docName, pathFaultProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_STORE_REFUSED) {- flushErrors.set(p.docName, refusedStoreProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_STORE_HELD) {- flushErrors.set(p.docName, heldSaveProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_STORE_DISCARDED) {- flushErrors.set(p.docName, discardedStoreProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_DOC_MOVED) {- flushErrors.set(p.docName, movedDocProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_SERVER_STOPPED) {- flushErrors.set(p.docName, stoppedServerProblem(flushOutcome.failure));- } else {- const reason = classifyUploadErrno({- code: flushOutcome.failure.code,- } as NodeJS.ErrnoException);- flushErrors.set(p.docName, {- type: reason,- title: 'Write applied in memory but failed to persist to disk.',- detail: `${flushOutcome.failure.code ?? 'unknown error'}: ${flushOutcome.failure.message}. The content was NOT saved and will be lost if the server restarts.`,- });- }+ flushErrors.set(p.docName, storeFailureEntryProblem(flushOutcome.failure));} else if (flushOutcome?.kind === 'stale-external-write') {- flushErrors.set(p.docName, staleExternalWriteProblem(p.docName));+ flushErrors.set(+ p.docName,+ withoutOutcomeFields(staleExternalWriteProblem(p.docName)),+ );} else {flushErrors.set(p.docName, undefined);}@@ -4185,11 +4306,22 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {let lastWrittenDoc: string | undefined;for (const p of pending) {const flushError = flushErrors.get(p.docName);+ const flushOutcome = flushOutcomes.get(p.docName) ?? null;if (flushError !== undefined) {- results[p.index] = { status: 'error', docName: p.docName, error: flushError };+ results[p.index] = {+ status: 'error',+ docName: p.docName,+ error: flushError,+ ...(flushOutcome?.kind === 'failure'+ ? outcomeOfStoreFailure(flushOutcome.failure)+ : REFUSAL_OUTCOMES['urn:ok:error:stale-external-write']),+ };continue;}- const writtenSource = p.session.dc.document.getText('source').toString();+ const writtenSource =+ hocuspocus.documents.get(p.docName)?.getText('source').toString() ??+ writtenSourceByDoc.get(p.docName) ??+ '';registerWrittenDocInFileIndex(p.docName, writtenSource);const linkAdvisory = linkAdvisor(writtenSource,@@ -4200,6 +4332,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {results[p.index] = {status: 'written',docName: p.docName,+ ...reportedOutcome(+ p.docName,+ outcomeOfSavedWrite(p.reconcile, flushOutcome, p.diverged),+ ),...(p.summaryResponse ? { summary: p.summaryResponse } : {}),...(warnings.length > 0 ? { warnings } : {}),...linkAdvisory.links,diff --git a/packages/server/src/concurrent-overwrite-refused-error.ts b/packages/server/src/concurrent-overwrite-refused-error.tsindex c1c450eac..cdf72351b 100644--- a/packages/server/src/concurrent-overwrite-refused-error.ts+++ b/packages/server/src/concurrent-overwrite-refused-error.ts@@ -1,4 +1,5 @@import type { ServerResponse } from 'node:http';+import { REFUSAL_OUTCOMES } from './agent-write-outcome.ts';import { stripDocExtension } from './doc-extensions.ts';import { errorResponse } from './http/error-response.ts';import { getLogger } from './logger.ts';@@ -49,6 +50,7 @@ export function respondConcurrentOverwriteRefused(extensions: {file: error.file,retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,+ ...REFUSAL_OUTCOMES['urn:ok:error:concurrent-overwrite-refused'],},extraHeaders: { 'Retry-After': String(CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS) },});diff --git a/packages/server/src/conflict-errors.ts b/packages/server/src/conflict-errors.tsindex e7f78c28e..8c138758f 100644--- a/packages/server/src/conflict-errors.ts+++ b/packages/server/src/conflict-errors.ts@@ -1,4 +1,5 @@import type { ServerResponse } from 'node:http';+import { REFUSAL_OUTCOMES } from './agent-write-outcome.ts';import type { Conflict, ConflictKind, ReconcileReason, ResolveStrategy } from './conflict-kinds.ts';import { strategiesFor } from './conflict-kinds.ts';import { stripDocExtension } from './doc-extensions.ts';@@ -67,7 +68,11 @@ export function respondDocInConflict(errorResponse(res, 409, 'urn:ok:error:doc-in-conflict', 'Document is in conflict.', {handler,detail,- extensions: { file: conflict?.file ?? err.file, ...envelope },+ extensions: {+ file: conflict?.file ?? err.file,+ ...envelope,+ ...REFUSAL_OUTCOMES['urn:ok:error:doc-in-conflict'],+ },});}diff --git a/packages/server/src/content-divergence-gate.test.ts b/packages/server/src/content-divergence-gate.test.tsindex b484dceec..04b8eb668 100644--- a/packages/server/src/content-divergence-gate.test.ts+++ b/packages/server/src/content-divergence-gate.test.ts@@ -81,6 +81,9 @@ describe('content-divergence gate', () => {expect(w.currentState).toEqual(d.currentState);expect(typeof w.hint).toBe('string');expect(w.hint).toContain('currentState');+ expect(w.hint).toContain('the stored text differs from the bytes you sent');+ expect(w.hint).toContain('Re-read the document before the next edit');+ expect(w.hint).not.toContain('only if it is truncated');});test('toContentDivergenceWarning accepts an explicit hint override', () => {diff --git a/packages/server/src/content-divergence-gate.ts b/packages/server/src/content-divergence-gate.tsindex 4ec9803ea..2e4b6f5c0 100644--- a/packages/server/src/content-divergence-gate.ts+++ b/packages/server/src/content-divergence-gate.ts@@ -47,7 +47,7 @@ export function evaluateContentDivergence(}const DEFAULT_DIVERGENCE_HINT =- 'The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.';+ 'The write landed and is saved, but the stored text differs from the bytes you sent. Re-read the document before the next edit; `currentState` carries what it holds now.';export function toContentDivergenceWarning(d: AgentWriteContentDivergence,diff --git a/packages/server/src/document-durability-state.test.ts b/packages/server/src/document-durability-state.test.tsindex 42efc96e6..df31fb39e 100644--- a/packages/server/src/document-durability-state.test.ts+++ b/packages/server/src/document-durability-state.test.ts@@ -36,6 +36,36 @@ import { getLogger } from './logger.ts';import { getMetrics, resetMetrics } from './metrics.ts';import { contentHash } from './version-hash.ts';+describe('the merge a store recorded for agent writes', () => {+ const at = (clock: number) => ({ clientId: 7, clock });++ test('reaches every write the store carried, not only the first flush that reads it', () => {+ const state = new DocumentDurabilityState();+ state.recordStoreIntake('doc', 'both-kept', at(10));++ expect(state.readStoreIntake('doc', at(4))).toBe('both-kept');+ expect(state.readStoreIntake('doc', at(9))).toBe('both-kept');+ });++ test('never reaches a write that an earlier store did not carry', () => {+ const state = new DocumentDurabilityState();+ state.recordStoreIntake('doc', 'both-kept', at(5));+ state.recordStoreIntake('doc', 'merged', at(12));++ expect(state.readStoreIntake('doc', at(8))).toBe('merged');+ expect(state.readStoreIntake('doc', at(13))).toBeUndefined();+ expect(state.readStoreIntake('doc', { clientId: 8, clock: 1 })).toBeUndefined();+ });++ test('is cleared with the rest of the document state', () => {+ const state = new DocumentDurabilityState();+ state.recordStoreIntake('doc', 'kept-live', at(10));+ state.deleteReconciledBase('doc');++ expect(state.readStoreIntake('doc', at(4))).toBeUndefined();+ });+});+describe('DocumentDurabilityState', () => {test('starts with an empty main scope and no transient coordination state', () => {const state = new DocumentDurabilityState();@@ -1654,14 +1684,14 @@ describe('which edits a rename outside the app carried to the new name', () => {expect(state.renameCarryOf('archive')).toBeUndefined();});- test('ending every record at shutdown answers a waiting write as unsettled and leaves none', async () => {+ test('ending every record at shutdown answers a waiting write as stopped and leaves none', async () => {const state = new DocumentDurabilityState();const { carried } = frozenDocWithCarriedAndLaterEdit();const pending = state.beginRenameCarry('notes');state.beginRenameCarry('archive');state.settleRenameCarry('archive', carried);state.endAllRenameCarries();- expect(await pending).toEqual({ kind: 'unsettled' });+ expect(await pending).toEqual({ kind: 'stopped' });expect(state.renameCarryOf('notes')).toBeUndefined();expect(state.renameCarryOf('archive')).toBeUndefined();});diff --git a/packages/server/src/document-durability-state.ts b/packages/server/src/document-durability-state.tsindex b67bb8ecb..6580dd4be 100644--- a/packages/server/src/document-durability-state.ts+++ b/packages/server/src/document-durability-state.ts@@ -1,7 +1,7 @@import { AsyncLocalStorage } from 'node:async_hooks';import { existsSync, readFileSync } from 'node:fs';import { dirname } from 'node:path';-import { currentCliCommandName } from '@inkeep/open-knowledge-core';+import { currentCliCommandName, type ReconcileMergeOutcome } from '@inkeep/open-knowledge-core';import { atomicTempPath } from '@inkeep/open-knowledge-core/server';import { type Doc, getState } from 'yjs';import { type DiskReceipt, DiskReceiptLog, type FileObservation } from './disk-receipts.ts';@@ -44,7 +44,27 @@ export function editWasCarried(export type RenameCarryAnswer =| { readonly kind: 'settled'; readonly carried: WrittenThrough | null }- | { readonly kind: 'unsettled' };+ | { readonly kind: 'unsettled' }+ | { readonly kind: 'stopped' };++export type HeldSaveReason = StorePendingReason | 'pending-unsettled' | 'pending-rename';++export type StoreIntakeMerge = ReconcileMergeOutcome | 'disk-replaced';++const STORE_INTAKE_RECORDS_KEPT = 8;++const STORE_INTAKE_STRENGTH: Readonly<Record<StoreIntakeMerge, number>> = {+ clean: 0,+ merged: 1,+ 'kept-live': 2,+ 'both-kept': 3,+ 'disk-replaced': 4,+};++interface StoreIntakeRecord {+ readonly merge: StoreIntakeMerge;+ readonly through: WrittenThrough;+}type RenameCarry =| {@@ -59,7 +79,7 @@ export interface StoreFailure {message: string;removal?: StoreFailureRemoval;held?: {- readonly reason: StorePendingReason;+ readonly reason: HeldSaveReason;readonly causeCode?: string;readonly noBase?: true;};@@ -113,6 +133,7 @@ export const OK_STORE_HELD = 'OK_STORE_HELD';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';const IN_FLIGHT_FLUSH_TTL_MS = 60_000;@@ -341,6 +362,7 @@ export class DocumentDurabilityState {private readonly agentWriteStores = new Set<string>();private readonly refusedStoreDocNames = new Set<string>();private readonly storeFailures = new Map<string, StoreFailure>();+ private readonly storeIntakes = new Map<string, StoreIntakeRecord[]>();private readonly staleExternalWriteFreezes = new Set<string>();private readonly persistencePath: string | undefined;private readonly fileForDocName: (docName: string) => string;@@ -510,6 +532,7 @@ export class DocumentDurabilityState {this.receipts.forget(docName);this.refusedStoreDocNames.delete(docName);this.storeFailures.delete(docName);+ this.storeIntakes.delete(docName);const persist = this.isPersistedDocument(docName);if (!persist) {this.reconciledBaseByBranch.get(this.activeBranch)?.delete(docName);@@ -1005,7 +1028,7 @@ export class DocumentDurabilityState {endAllRenameCarries(): void {for (const current of this.renameCarries.values()) {- if (current.state === 'pending') current.answer.resolve({ kind: 'unsettled' });+ if (current.state === 'pending') current.answer.resolve({ kind: 'stopped' });}this.renameCarries.clear();}@@ -1178,6 +1201,32 @@ export class DocumentDurabilityState {return failure;}+ recordStoreIntake(docName: string, merge: StoreIntakeMerge, through: WrittenThrough): void {+ const records = this.storeIntakes.get(docName) ?? [];+ records.push({ merge, through });+ if (records.length > STORE_INTAKE_RECORDS_KEPT) {+ records.splice(0, records.length - STORE_INTAKE_RECORDS_KEPT);+ }+ this.storeIntakes.set(docName, records);+ }++ readStoreIntake(+ docName: string,+ write: WrittenThrough | undefined,+ ): StoreIntakeMerge | undefined {+ let strongest: StoreIntakeMerge | undefined;+ for (const record of this.storeIntakes.get(docName) ?? []) {+ if (!editWasCarried(write, record.through)) continue;+ if (+ strongest === undefined ||+ STORE_INTAKE_STRENGTH[record.merge] > STORE_INTAKE_STRENGTH[strongest]+ ) {+ strongest = record.merge;+ }+ }+ return strongest;+ }+recordStaleExternalWriteFreeze(docName: string): void {this.staleExternalWriteFreezes.add(docName);}diff --git a/packages/server/src/frontmatter-malformed-error.ts b/packages/server/src/frontmatter-malformed-error.tsindex 5431aae76..bf8ec1959 100644--- a/packages/server/src/frontmatter-malformed-error.ts+++ b/packages/server/src/frontmatter-malformed-error.ts@@ -4,6 +4,7 @@*/import type { ServerResponse } from 'node:http';+import { REFUSAL_OUTCOMES } from './agent-write-outcome.ts';import { stripDocExtension } from './doc-extensions.ts';import { errorResponse } from './http/error-response.ts';@@ -84,6 +85,7 @@ export function respondFrontmatterMalformed(extensions: {file: err.file,parseError: err.parseError,+ ...REFUSAL_OUTCOMES['urn:ok:error:frontmatter-malformed'],},});}diff --git a/packages/server/src/http/agent-session-capacity.ts b/packages/server/src/http/agent-session-capacity.tsindex 03046044d..6cb828b44 100644--- a/packages/server/src/http/agent-session-capacity.ts+++ b/packages/server/src/http/agent-session-capacity.ts@@ -1,5 +1,6 @@import type { ServerResponse } from 'node:http';import type { AgentSessionCapacityError } from '../agent-sessions.ts';+import { REFUSAL_OUTCOMES } from '../agent-write-outcome.ts';import { errorResponse } from './error-response.ts';export const AGENT_SESSION_CAPACITY_TYPE = 'urn:ok:error:too-many-agent-sessions';@@ -22,7 +23,10 @@ export function respondAgentSessionCapacity(handler,cause: error,detail: AGENT_SESSION_CAPACITY_DETAIL,- extensions: { ...AGENT_SESSION_CAPACITY_EXTENSIONS },+ extensions: {+ ...AGENT_SESSION_CAPACITY_EXTENSIONS,+ ...REFUSAL_OUTCOMES['urn:ok:error:too-many-agent-sessions'],+ },extraHeaders: { 'Retry-After': String(AGENT_SESSION_CAPACITY_RETRY_AFTER_SECONDS) },});}diff --git a/packages/server/src/http/agent-write-response.ts b/packages/server/src/http/agent-write-response.tsnew file mode 100644index 000000000..7025e6790--- /dev/null+++ b/packages/server/src/http/agent-write-response.ts@@ -0,0 +1,22 @@+import type { ServerResponse } from 'node:http';+import type { AgentWriteOutcomeFields } from '@inkeep/open-knowledge-core';+import { errorResponse } from './error-response.ts';++const BOTH_KEPT_TITLE = 'Edit saved; both versions of a block changed here and outside were kept.';++const BOTH_KEPT_DETAIL =+ 'Your write landed and is saved to the file; do not retry it. Where a block was changed both here and outside, both versions are in the document, the version here first and the outside version directly under it. Re-read the document and, if your task calls for it, remove the duplicate with an ordinary edit.';++export function respondBothKept(+ res: ServerResponse,+ handler: string,+ body: Record<string, unknown>,+ outcome: AgentWriteOutcomeFields,+): void {+ errorResponse(res, 409, 'urn:ok:error:both-kept', BOTH_KEPT_TITLE, {+ handler,+ detail: BOTH_KEPT_DETAIL,+ extensions: { ...body, ...outcome },+ logLevel: 'debug',+ });+}diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.tsindex d8efd84cb..51ae698ff 100644--- a/packages/server/src/http/agent-write-routes.ts+++ b/packages/server/src/http/agent-write-routes.ts@@ -47,6 +47,13 @@ import {prepareFrontmatterPatchParse,snapshotBlocks,} from '../agent-sessions.ts';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+ REFUSAL_OUTCOMES,+ reportedOutcome,+} from '../agent-write-outcome.ts';import {type NormalizedSummary,normalizeSummary,@@ -104,6 +111,7 @@ import {} from '../shadow-repo.ts';import { getMeter, withSpanSync } from '../telemetry.ts';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 { getRequestId } from './request-id.ts';@@ -194,9 +202,7 @@ export interface AgentWriteRouteDeps {flushDiskAndDetectOutcome: (docName: string,writtenThrough?: WrittenThrough,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ ) => Promise<AgentWriteFlushOutcome>;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;flushDocToDisk: (docName: string, label: string) => void;agentFocusBroadcaster: AgentFocusBroadcaster | undefined;@@ -316,7 +322,14 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup404,'urn:ok:error:doc-not-found',`No document at "${docName}" (paths are relative to the content root). ${nextStep}`,- { handler, extensions: { candidates, committed: false } },+ {+ handler,+ extensions: {+ candidates,+ committed: false,+ ...REFUSAL_OUTCOMES['urn:ok:error:doc-not-found'],+ },+ },);return true;}@@ -354,7 +367,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:reserved-doc-name',`'${resolvedDocName}' is a reserved document name.`,- { handler: 'agent-write-md' },+ {+ handler: 'agent-write-md',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },);return;}@@ -396,6 +412,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGrouplet 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);@@ -438,6 +455,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup});}, session.origin);writtenThrough = writtenThroughOf(session.dc.document);+ writtenSource = session.dc.document.getText('source').toString();if (writeDivergence !== undefined) {console.warn(JSON.stringify({@@ -485,8 +503,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupts: Date.now(),});onAgentWrite?.();+ writtenSource =+ hocuspocus.documents.get(resolvedDocName)?.getText('source').toString() ??+ writtenSource;const hints = await computeOrphanHints(resolvedDocName);- const writtenSource = session.dc.document.getText('source').toString();registerWrittenDocInFileIndex(resolvedDocName, writtenSource);const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(@@ -509,26 +529,31 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),...(writeMdWarning ? [writeMdWarning] : []),...(renderWarnings ?? []),- ...(await computeLintViolations(- session.dc.document.getText('source').toString(),- resolvedDocName,- linkPolicy,- )),+ ...(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);+ return;+ }successResponse(res,200,AgentWriteMdSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- ...(hints ? { hints } : {}),- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),- ...linkAdvisory.links,- },+ { ...writeMdBody, ...writeMdOutcome },{ handler: 'agent-write-md' },);});@@ -580,7 +605,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:reserved-doc-name',`'${resolvedDocName}' is a reserved document name.`,- { handler: 'frontmatter-patch' },+ {+ handler: 'frontmatter-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },);return;}@@ -611,6 +639,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGrouplet editError: import('@inkeep/open-knowledge-core').FmEditError | undefined;let applied = false;let bodyMutated = false;+ let fmFlushOutcome: AgentWriteFlushOutcome = null;const appliedKeys: string[] = [];try {const icon = iconFromClientName(clientName);@@ -672,6 +701,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup} finally {agentPresenceBroadcaster?.touchMode(agentId, 'idle');}+ let fmWrittenSource = session.dc.document.getText('source').toString();if (editError) {let fieldErrors: Record<string, string>;switch (editError.kind) {@@ -717,7 +747,13 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:invalid-frontmatter-patch','Frontmatter patch rejected: schema validation failed.',- { handler: 'frontmatter-patch', extensions: { fieldErrors } },+ {+ handler: 'frontmatter-patch',+ extensions: {+ fieldErrors,+ ...REFUSAL_OUTCOMES['urn:ok:error:invalid-frontmatter-patch'],+ },+ },);return;}@@ -734,7 +770,8 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupincrementAgentWriteCalls();countNormalizedSummary(normalizedSummary);if (bodyMutated) {- const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ fmFlushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ const flushOutcome = fmFlushOutcome;if (flushOutcome?.kind === 'failure') {respondPersistenceFailure(res, flushOutcome.failure, 'frontmatter-patch');return;@@ -762,29 +799,38 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup});}const fmWarning = buildReconcileWarning(fmReconcile);- registerWrittenDocInFileIndex(- resolvedDocName,- session.dc.document.getText('source').toString(),- );+ fmWrittenSource =+ hocuspocus.documents.get(resolvedDocName)?.getText('source').toString() ??+ fmWrittenSource;+ registerWrittenDocInFileIndex(resolvedDocName, fmWrittenSource);const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(- session.dc.document.getText('source').toString(),+ fmWrittenSource,resolvedDocName,linkPolicy.suppressLogLinkAdvisories,);const fmAdvisories = [...(fmWarning ? [fmWarning] : []), ...linkAdvisory.warnings];+ const fmBody = {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ appliedKeys,+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(fmAdvisories.length > 0 ? { warnings: fmAdvisories } : {}),+ ...linkAdvisory.links,+ };+ const fmOutcome = reportedOutcome(+ resolvedDocName,+ outcomeOfSavedWrite(fmReconcile, fmFlushOutcome),+ );+ if (fmOutcome?.outcome === 'both-kept') {+ respondBothKept(res, 'frontmatter-patch', fmBody, fmOutcome);+ return;+ }successResponse(res,200,FrontmatterPatchSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- appliedKeys,- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(fmAdvisories.length > 0 ? { warnings: fmAdvisories } : {}),- ...linkAdvisory.links,- },+ { ...fmBody, ...fmOutcome },{ handler: 'frontmatter-patch' },);});@@ -827,7 +873,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:reserved-doc-name',`'${docName}' is a reserved document name.`,- { handler: 'agent-patch' },+ {+ handler: 'agent-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },);return;}@@ -1003,7 +1052,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup409,'urn:ok:error:stale-target','Target text no longer matches at the requested offset.',- { handler: 'agent-patch' },+ {+ handler: 'agent-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:stale-target'] },+ },);return;}@@ -1015,6 +1067,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup'Text not found in document.',{handler: 'agent-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:target-not-found'] },},);return;@@ -1026,7 +1079,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:frontmatter-edit-not-supported','Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.',- { handler: 'agent-patch' },+ {+ handler: 'agent-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:frontmatter-edit-not-supported'] },+ },);return;}@@ -1037,10 +1093,14 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:frontmatter-edit-not-supported',"This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",- { handler: 'agent-patch' },+ {+ handler: 'agent-patch',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:frontmatter-edit-not-supported'] },+ },);return;}+ let patchedSource = session.dc.document.getText('source').toString();const flushOutcome = await flushDiskAndDetectOutcome(docName);if (flushOutcome?.kind === 'failure') {respondPersistenceFailure(res, flushOutcome.failure, 'agent-patch');@@ -1067,7 +1127,8 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup});}const { response: summaryResponse } = summaryResponseFields(normalizedSummary);- const patchedSource = session.dc.document.getText('source').toString();+ patchedSource =+ hocuspocus.documents.get(docName)?.getText('source').toString() ?? patchedSource;registerWrittenDocInFileIndex(docName, patchedSource);const renderWarnings = await validateMermaidFences(patchedSource, docName);const linkAdvisory = (await prepareWriteLinkAdvisory([docName]))(@@ -1082,25 +1143,30 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup...(patchDivergenceEntry ? [patchDivergenceEntry] : []),...(patchWarning ? [patchWarning] : []),...(renderWarnings ?? []),- ...(await computeLintViolations(- session.dc.document.getText('source').toString(),- docName,- linkPolicy,- )),+ ...(await computeLintViolations(patchedSource, docName, linkPolicy)),...linkAdvisory.warnings,];+ const patchBody = {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),+ ...linkAdvisory.links,+ };+ const patchOutcome = reportedOutcome(+ docName,+ outcomeOfSavedWrite(patchReconcile, flushOutcome, patchDivergence !== undefined),+ );+ if (patchOutcome?.outcome === 'both-kept') {+ respondBothKept(res, 'agent-patch', patchBody, patchOutcome);+ return;+ }successResponse(res,200,AgentPatchSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),- ...linkAdvisory.links,- },+ { ...patchBody, ...patchOutcome },{ handler: 'agent-patch' },);});@@ -1147,7 +1213,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup400,'urn:ok:error:reserved-doc-name',`'${docName}' is a reserved document name.`,- { handler: 'agent-undo' },+ {+ handler: 'agent-undo',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'] },+ },);return;}@@ -1206,9 +1275,14 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup} finally {agentPresenceBroadcaster?.touchMode(agentId, 'idle');}+ let undoFlushOutcome: AgentWriteFlushOutcome = null;if (undone) {- const flushOutcome = await flushDiskAndDetectOutcome(docName);- if (flushOutcome?.kind === 'failure') {+ undoFlushOutcome = await flushDiskAndDetectOutcome(docName);+ const flushOutcome = undoFlushOutcome;+ if (+ flushOutcome?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(flushOutcome.failure)+ ) {respondPersistenceFailure(res, flushOutcome.failure, 'agent-undo');return;}@@ -1228,7 +1302,12 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupres,200,AgentUndoSuccessSchema,- { docName, scope, undone },+ {+ docName,+ scope,+ undone,+ ...reportedOutcome(docName, outcomeOfSavedWrite(undefined, undoFlushOutcome)),+ },{ handler: 'agent-undo' },);} catch (e) {@@ -1537,7 +1616,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup404,'urn:ok:error:doc-not-found',`Commit ${commitSha.slice(0, 7)} does not contain document ${docName} at any known historical path.`,- { handler: 'rollback' },+ {+ handler: 'rollback',+ extensions: { ...REFUSAL_OUTCOMES['urn:ok:error:doc-not-found'] },+ },);return;}@@ -1654,7 +1736,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup}renameAttributionCounter().add(1, { kind: 'rollback', attribution_kind: actor.kind });const flushOutcome = await flushDiskAndDetectOutcome(docName);- if (flushOutcome?.kind === 'failure') {+ if (+ flushOutcome?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(flushOutcome.failure)+ ) {respondPersistenceFailure(res, flushOutcome.failure, 'rollback');return;}@@ -1685,6 +1770,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup200,RollbackSuccessSchema,{+ ...reportedOutcome(+ docName,+ outcomeOfSavedWrite(undefined, flushOutcome, rollbackDivergence !== undefined),+ ),restoredFrom: commitSha,timestamp,...(summaryResponse ? { summary: summaryResponse } : {}),diff --git a/packages/server/src/http/folder-template-routes.ts b/packages/server/src/http/folder-template-routes.tsindex 4c32f79b6..ce9b3347c 100644--- a/packages/server/src/http/folder-template-routes.ts+++ b/packages/server/src/http/folder-template-routes.ts@@ -30,6 +30,11 @@ import {} from '@inkeep/open-knowledge-core';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import type { AgentSessionManager } from '../agent-sessions.ts';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+} from '../agent-write-outcome.ts';import { composeAndWriteRawBody } from '../bridge-intake.ts';import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import type { ConflictAuthority } from '../conflict-authority.ts';@@ -104,11 +109,7 @@ export interface FolderTemplateRouteDeps {previousPaths?: Array<{ from: string; to: string }>,) => void;scheduleOkArtifactFlush: (context: string) => void;- flushDiskAndDetectOutcome: (- docName: string,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;registerWrittenDocInFileIndex: (docName: string, content: string) => void;@@ -698,7 +699,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}, templateSession.origin);const templateFlush = await flushDiskAndDetectOutcome(templateDocName);- if (templateFlush?.kind === 'failure') {+ if (+ templateFlush?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(templateFlush.failure)+ ) {respondPersistenceFailure(res, templateFlush.failure, 'template-put');return;}@@ -720,6 +724,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo200,TemplatePutSuccessSchema,{+ ...outcomeOfSavedWrite(undefined, templateFlush),path: templateRelPath,created: templateCreated,warnings: composed.warnings,@@ -1309,7 +1314,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}, templateSession.origin);const templateFlush = await flushDiskAndDetectOutcome(templateDocName);- if (templateFlush?.kind === 'failure') {+ if (+ templateFlush?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(templateFlush.failure)+ ) {respondPersistenceFailure(res, templateFlush.failure, 'template-import');return;}@@ -1348,6 +1356,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo200,TemplateImportSuccessSchema,{+ ...outcomeOfSavedWrite(undefined, templateFlush),path: templateRelPath,created: templateCreated,warnings: composed.warnings,diff --git a/packages/server/src/http/lint-write-routes.ts b/packages/server/src/http/lint-write-routes.tsindex 2af2fb2a1..e17b79b86 100644--- a/packages/server/src/http/lint-write-routes.ts+++ b/packages/server/src/http/lint-write-routes.ts@@ -2,6 +2,7 @@ import type { ServerResponse } from 'node:http';import { resolve } from 'node:path';import {AGENT_ICON_COLORS,+ type AgentWriteOutcomeFields,colorFromSeed,DEFAULT_LINTER_CONFIG,FrontmatterSchemaWriteRequestSchema,@@ -25,6 +26,11 @@ import {applyAgentMarkdownWrite,iconFromClientName,} from '../agent-sessions.ts';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+} from '../agent-write-outcome.ts';import type { NormalizedSummary, SummaryResponse } from '../agent-write-summary.ts';import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import type { ConflictAuthority } from '../conflict-authority.ts';@@ -96,11 +102,7 @@ export interface LintWriteRouteDeps {clientVersion?: string;label?: string;};- flushDiskAndDetectOutcome: (- docName: string,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;flushDocToDisk: (docName: string, label: string) => void;@@ -334,6 +336,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {let after = before;let reLintFailure: ReLintFailure | undefined;+ let fixOutcome: AgentWriteOutcomeFields | undefined;const reLintFailures: LintPluginFailure[] = [];if (fixed !== source) {try {@@ -384,7 +387,11 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {}const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);- if (flushOutcome?.kind === 'failure') {+ fixOutcome = outcomeOfSavedWrite(undefined, flushOutcome);+ if (+ flushOutcome?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(flushOutcome.failure)+ ) {respondPersistenceFailure(res, flushOutcome.failure, 'lint-fix');return;}@@ -458,6 +465,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {200,LintFixResultSchema,{+ ...fixOutcome,file: docRelPath,fixedCount,diagnostics: after,diff --git a/packages/server/src/http/skills-document-routes.ts b/packages/server/src/http/skills-document-routes.tsindex fc075a10c..051eb1d50 100644--- a/packages/server/src/http/skills-document-routes.ts+++ b/packages/server/src/http/skills-document-routes.ts@@ -35,6 +35,12 @@ import {type SkillsLock,} from '@inkeep/open-knowledge-core/skills-catalog';import type { AgentSessionManager } from '../agent-sessions.ts';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+ reportedOutcome,+} from '../agent-write-outcome.ts';import { composeAndWriteRawBody } from '../bridge-intake.ts';import { isLinkIndexExcludedDoc } from '../cc1-broadcast.ts';import type { RemovalLifecycleStatus } from '../conflict-kinds.ts';@@ -158,11 +164,7 @@ export interface SkillsDocumentRouteDeps {};sessionManager: AgentSessionManager;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;- flushDiskAndDetectOutcome: (- docName: string,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;okArtifactKey: (kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',@@ -619,7 +621,10 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo}, session.origin);const flushOutcome = await flushDiskAndDetectOutcome(docName);- if (flushOutcome?.kind === 'failure') {+ if (+ flushOutcome?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(flushOutcome.failure)+ ) {respondPersistenceFailure(res, flushOutcome.failure, 'skill-put');return;}@@ -643,6 +648,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo200,SkillPutSuccessSchema,{+ ...reportedOutcome(docName, outcomeOfSavedWrite(undefined, flushOutcome)),path: relPath,created,warnings: composed.warnings,diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.tsindex 483837c26..b699b5543 100644--- a/packages/server/src/http/skills-file-routes.ts+++ b/packages/server/src/http/skills-file-routes.ts@@ -15,6 +15,12 @@ import {skillFilePathSegments,} from '@inkeep/open-knowledge-core';import type { AgentSessionManager } from '../agent-sessions.ts';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+ outcomeOfSavedWrite,+ reportedOutcome,+} from '../agent-write-outcome.ts';import { composeAndWriteRawBody } from '../bridge-intake.ts';import type { RemovalLifecycleStatus } from '../conflict-kinds.ts';import {@@ -92,11 +98,7 @@ export interface SkillsFileRouteDeps {};sessionManager: AgentSessionManager;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;- flushDiskAndDetectOutcome: (- docName: string,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;okArtifactKey: (kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',@@ -408,6 +410,8 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup)return;const routedThroughContent = isProjectMdReference(body.scope, kind, rel);+ let fileFlushOutcome: AgentWriteFlushOutcome = null;+ let fileDocName: string | undefined;let created: boolean;if (routedThroughContent) {@@ -416,6 +420,7 @@ 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) {@@ -440,7 +445,11 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroupcomposeAndWriteRawBody(session.dc.document, body.content, 'agent');}, session.origin);const flushOutcome = await flushDiskAndDetectOutcome(refDocName);- if (flushOutcome?.kind === 'failure') {+ fileFlushOutcome = flushOutcome;+ if (+ flushOutcome?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(flushOutcome.failure)+ ) {respondPersistenceFailure(res, flushOutcome.failure, 'skill-file-put');return;}@@ -495,7 +504,15 @@ export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroupres,200,SkillFilePutSuccessSchema,- { path: rel, created, kind, content: routedThroughContent },+ {+ ...(fileDocName === undefined+ ? outcomeOfSavedWrite(undefined, fileFlushOutcome)+ : reportedOutcome(fileDocName, outcomeOfSavedWrite(undefined, fileFlushOutcome))),+ path: rel,+ created,+ kind,+ content: routedThroughContent,+ },{ handler: 'skill-file-put' },);} catch (e) {diff --git a/packages/server/src/http/skills-install-routes.test.ts b/packages/server/src/http/skills-install-routes.test.tsindex 6c21de302..ff89501b7 100644--- a/packages/server/src/http/skills-install-routes.test.ts+++ b/packages/server/src/http/skills-install-routes.test.ts@@ -5,7 +5,7 @@ import { join } from 'node:path';import { Readable } from 'node:stream';import { afterEach, describe, expect, test } from 'vitest';import { makeCaptureRes } from '../composition-rig.test-helper.ts';-import { OK_DOC_REMOVED } from '../document-durability-state.ts';+import { OK_DOC_REMOVED, OK_STORE_HELD, OK_WRITE_REPLACED } from '../document-durability-state.ts';import { loggerFactory } from '../logger.ts';import { createSkillsInstallRoutes, type SkillsInstallRouteDeps } from './skills-install-routes.ts';@@ -126,6 +126,27 @@ describe('skill-install surfaces every flush outcome instead of installing overexpect(captured.body).not.toContain('INVALID_SKILL_SOURCE');});+ test.each([+ {+ name: 'a write the file replaced',+ failure: { code: OK_WRITE_REPLACED, message: 'replaced' },+ },+ {+ name: 'a save still running when the wait ended',+ failure: {+ code: OK_STORE_HELD,+ message: 'still saving',+ held: { reason: 'pending-unsettled' as const },+ },+ },+ ])('$name does not stop the install, as on the other app routes', async ({ failure }) => {+ const captured = await dispatchInstall({+ flushDiskAndDetectOutcome: () => Promise.resolve({ kind: 'failure', failure }),+ });+ expect(captured.status).toBe(400);+ expect(captured.body).toContain('INVALID_SKILL_SOURCE');+ });+test('a clean flush falls through to validation, which rejects a SKILL.md-less source', async () => {const captured = await dispatchInstall({});expect(captured.status).toBe(400);diff --git a/packages/server/src/http/skills-install-routes.ts b/packages/server/src/http/skills-install-routes.tsindex 6b48d77a5..5c40c428b 100644--- a/packages/server/src/http/skills-install-routes.ts+++ b/packages/server/src/http/skills-install-routes.ts@@ -13,6 +13,10 @@ import {} from '@inkeep/open-knowledge-core';import type { SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';import { parseSkillsLock, SKILLS_LOCK_REL } from '@inkeep/open-knowledge-core/skills-catalog';+import {+ type AgentWriteFlushOutcome,+ answeredWithSuccessOnAppRoutes,+} from '../agent-write-outcome.ts';import type { ContentFilter } from '../content-filter.ts';import type { StoreFailure } from '../document-durability-state.ts';import { scanGlobalInPlaceSkills, scanInPlaceSkills } from '../in-place-skills.ts';@@ -50,11 +54,7 @@ export interface SkillsInstallRouteDeps {shippedBundleSkillMd: (name: string, scope?: 'project' | 'global') => string | null;respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;- flushDiskAndDetectOutcome: (- docName: string,- ) => Promise<- { kind: 'failure'; failure: StoreFailure } | { kind: 'stale-external-write' } | null- >;+ flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;skillInstallOps: SkillInstallOpsService;skillPlacementOps: SkillPlacementOpsService;signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;@@ -133,7 +133,10 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRout? `${relative(inPlaceScanBase, skillDir).split(sep).join('/')}/SKILL`: skillLiveDocName(body.scope, body.name);const liveSkillFlush = await flushDiskAndDetectOutcome(liveSkillDoc);- if (liveSkillFlush?.kind === 'failure') {+ if (+ liveSkillFlush?.kind === 'failure' &&+ !answeredWithSuccessOnAppRoutes(liveSkillFlush.failure)+ ) {respondPersistenceFailure(res, liveSkillFlush.failure, 'skill-install');return;}@@ -760,7 +763,13 @@ export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRoutres,200,SkillInstallSuccessSchema,- { name: body.name, hosts, scripts: validity.hasScripts, warnings, warningCodes },+ {+ name: body.name,+ hosts,+ scripts: validity.hasScripts,+ warnings,+ warningCodes,+ },{ handler: 'skill-install' },);} catch (e) {diff --git a/packages/server/src/mcp/tools/advisory-warnings.ts b/packages/server/src/mcp/tools/advisory-warnings.tsindex 8a67caef1..902b264a4 100644--- a/packages/server/src/mcp/tools/advisory-warnings.ts+++ b/packages/server/src/mcp/tools/advisory-warnings.ts@@ -133,7 +133,7 @@ export function formatAdvisoryBriefs(warnings: AdvisoryWarning[]): string[] {function formatIntegrityLine(d: WriteWarning): string {switch (d.kind) {case 'content-divergence':- return `⚠ Content divergence: ${d.actualBytes} actual bytes vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}). ${d.hint ?? 'currentState carries the converged content (re-read only if it is truncated).'}`;+ return `⚠ Content divergence: ${d.actualBytes} actual bytes vs ${d.intendedBytes} intended (byteDelta=${d.byteDelta}). ${d.hint ?? 'The stored text differs from what you sent; re-read the document before the next edit.'}`;case 'disk-edit-reconciled':return `⚠ ${d.hint ?? 'An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.'}`;default:diff --git a/packages/server/src/mcp/tools/description-contract.uncached.test.ts b/packages/server/src/mcp/tools/description-contract.uncached.test.tsindex 152bd9c28..157a953d9 100644--- a/packages/server/src/mcp/tools/description-contract.uncached.test.ts+++ b/packages/server/src/mcp/tools/description-contract.uncached.test.ts@@ -2,6 +2,7 @@ import { readdirSync, readFileSync } from 'node:fs';import { join, relative } from 'node:path';import { fileURLToPath } from 'node:url';import {+ type AgentWriteOutcomeFields,LINT_PLUGIN_IDS,OPEN_KNOWLEDGE_MCP_TOOLS,VALIDATION_SOURCES,@@ -11,7 +12,23 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import type { Tool } from '@modelcontextprotocol/sdk/types.js';import { afterAll, beforeAll, expect, test } from 'vitest';+import {+ outcomeOfSavedWrite,+ outcomeOfStoreFailure,+ REFUSAL_OUTCOMES,+} from '../../agent-write-outcome.ts';import { ConfigSchema } from '../../config/schema.ts';+import {+ OK_DOC_MOVED,+ OK_DOC_REMOVED,+ OK_PATH_UNRESOLVABLE,+ OK_SERVER_STOPPED,+ OK_STORE_DISCARDED,+ OK_STORE_HELD,+ OK_STORE_REFUSED,+ OK_WRITE_REPLACED,+ type StoreFailure,+} from '../../document-durability-state.ts';import { installJsonSchemaDialect, JSON_SCHEMA_DIALECT_2020_12 } from '../json-schema-dialect.ts';import { registerAllTools } from './index.ts';import { ROUTED_CWD_DESCRIPTION } from './shared.ts';@@ -289,3 +306,172 @@ test('skill router and published reference names and counts equal the actual serexpect(reference).toContain(`**${tools.length} tools**`);expect(router).not.toMatch(/\bconflicts\s*\(|\bresolve_conflict\b/);});++const resolveActionNames =+ /\bresolve_conflict\b|\/api\/sync\/(?:resolve-conflict|conflict-content|conflicts)\b|\bresolutionOptions\b|\bKeep my version\b|\bUse their version\b/;+const diskCollisionStateNames =+ /\b(?:refused-too-large|refused-no-base|refused-conflict-markers|merged-with-markers|disk-markers|conflict-resolved)\b|"kind":\s*"reconcile"|`reconcile` conflict/;+const residualDiskConflictStates = /\b(?:stale-external-write|pending-conflict)\b/;+const RESIDUAL_STATES_RETIRED_WITH_THE_CONFLICT_ROUTE: ReadonlySet<string> = new Set([+ 'docs/content/reference/mcp.mdx',+ 'packages/server/assets/skills/project/references/conflict-resolution.md',+]);++function withoutGitConflictSections(markdown: string): string {+ return markdown.replace(/^## Git conflicts\n[\s\S]*?(?=^## |(?![\s\S]))/m, '');+}++function agentFacingGuidance(root: string): Array<{ path: string; text: string }> {+ const docs = [+ 'docs/content/reference/mcp.mdx',+ 'docs/content/features/agent-activity.mdx',+ ...['docs/content/integrations', 'docs/content/remote-control'].flatMap((dir) =>+ filesUnder(join(root, dir))+ .filter((file) => /\.mdx?$/.test(file))+ .map((file) => relative(root, file)),+ ),+ ];+ const skills = filesUnder(join(root, 'packages/server/assets/skills'))+ .filter((file) => /\.mdx?$/.test(file))+ .map((file) => relative(root, file));+ return [...docs, ...skills].map((path) => ({+ path: path.replaceAll('\\', '/'),+ text: withoutGitConflictSections(readFileSync(join(root, path), 'utf8')),+ }));+}++test('no served tool names a resolve action or a disk-collision conflict state', () => {+ for (const tool of tools) {+ const served = JSON.stringify(tool);+ expect(served, tool.name).not.toMatch(resolveActionNames);+ expect(served, tool.name).not.toMatch(diskCollisionStateNames);+ expect(served, tool.name).not.toMatch(residualDiskConflictStates);+ }+});++test('no bundled skill or agent-facing doc names a resolve action or a disk-collision conflict state outside Git conflicts', () => {+ for (const { path, text } of agentFacingGuidance(adviceRoot)) {+ expect(text, path).not.toMatch(resolveActionNames);+ expect(text, path).not.toMatch(diskCollisionStateNames);+ if (!RESIDUAL_STATES_RETIRED_WITH_THE_CONFLICT_ROUTE.has(path)) {+ expect(text, path).not.toMatch(residualDiskConflictStates);+ }+ }+});++test('each page allowed to name a residual disk-side conflict state still needs to', () => {+ const guidance = new Map(agentFacingGuidance(adviceRoot).map(({ path, text }) => [path, text]));+ for (const path of RESIDUAL_STATES_RETIRED_WITH_THE_CONFLICT_ROUTE) {+ expect(guidance.get(path), path).toMatch(residualDiskConflictStates);+ }+});++const RESULT_TABLE_HEADER = '| Result | `outcome` | `saved` | `nextStep` | Your move |';++function guidedResultRows(text: string): Array<{ result: string; cells: string[] }> {+ const start = text.indexOf(RESULT_TABLE_HEADER);+ if (start === -1) return [];+ const rows: Array<{ result: string; cells: string[] }> = [];+ for (const line of text.slice(start).split('\n').slice(2)) {+ if (!line.startsWith('|')) break;+ const cells = line+ .split('|')+ .slice(1, -1)+ .map((cell) => cell.trim());+ rows.push({ result: cells[0] ?? '', cells });+ }+ return rows;+}++function held(reason: StoreFailure extends { held?: infer H } ? NonNullable<H>['reason'] : never) {+ return outcomeOfStoreFailure({ code: OK_STORE_HELD, message: 'm', held: { reason } });+}++const SERVER_FIELDS_FOR_GUIDED_RESULT: Readonly<Record<string, AgentWriteOutcomeFields>> = {+ '`applied` (200) with a `content-divergence` warning': outcomeOfSavedWrite(undefined, null, true),+ '`both-kept` (409)': outcomeOfSavedWrite({ reconciled: true, mergeOutcome: 'both-kept' }, null),+ '`concurrent-overwrite-refused` (409)':+ REFUSAL_OUTCOMES['urn:ok:error:concurrent-overwrite-refused'],+ '`too-many-agent-sessions` (503)': REFUSAL_OUTCOMES['urn:ok:error:too-many-agent-sessions'],+ '`doc-not-found` (404)': REFUSAL_OUTCOMES['urn:ok:error:doc-not-found'],+ '`reserved-doc-name` (400)': REFUSAL_OUTCOMES['urn:ok:error:reserved-doc-name'],+ '`frontmatter-malformed` (400)': REFUSAL_OUTCOMES['urn:ok:error:frontmatter-malformed'],+ '`frontmatter-edit-not-supported` (400)':+ REFUSAL_OUTCOMES['urn:ok:error:frontmatter-edit-not-supported'],+ '`invalid-frontmatter-patch` (400)': REFUSAL_OUTCOMES['urn:ok:error:invalid-frontmatter-patch'],+ '`target-not-found` (404)': REFUSAL_OUTCOMES['urn:ok:error:target-not-found'],+ '`stale-target` (409)': REFUSAL_OUTCOMES['urn:ok:error:stale-target'],+ '`doc-in-conflict` (409)': REFUSAL_OUTCOMES['urn:ok:error:doc-in-conflict'],+ '`stale-external-write` (409)': REFUSAL_OUTCOMES['urn:ok:error:stale-external-write'],+ '`save-held` (503) with `pending-conflict`': held('pending-conflict'),+ '`save-held` (503) on a file with no agreed version': outcomeOfStoreFailure({+ code: OK_STORE_HELD,+ message: 'm',+ held: { reason: 'pending-intake-failed-no-base', noBase: true },+ }),+ '`save-held` (503) with any other `reason`': held('pending-unreadable'),+ '`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({+ code: OK_DOC_REMOVED,+ message: 'm',+ removal: { kind: 'renamed', renamedTo: 'b' },+ }),+ '`doc-removed` (409) after a delete': outcomeOfStoreFailure({+ code: OK_DOC_REMOVED,+ message: 'm',+ removal: { kind: 'deleted-outside' },+ }),+ '`server-stopped` (503)': outcomeOfStoreFailure({ code: OK_SERVER_STOPPED, message: 'm' }),+ '`server-stopped` (503) during a move': outcomeOfStoreFailure({+ code: OK_SERVER_STOPPED,+ message: 'm',+ removal: { kind: 'renamed', renamedTo: 'b' },+ }),+ '`path-escape` (400)': outcomeOfStoreFailure({ code: OK_PATH_UNRESOLVABLE, message: 'm' }),+ '`store-refused` (503)': outcomeOfStoreFailure({ code: OK_STORE_REFUSED, message: 'm' }),+ '`write-replaced` (409)': outcomeOfStoreFailure({ code: OK_WRITE_REPLACED, message: 'm' }),+ '`storage-full` (507), `storage-readonly` or `storage-error` (500)': outcomeOfStoreFailure({+ code: 'ENOSPC',+ message: 'm',+ }),+};++test('the per-result guidance in the bundled skill and the reference gives the fields the server sends', () => {+ for (const path of [+ 'packages/server/assets/skills/project/references/conflict-resolution.md',+ 'docs/content/reference/mcp.mdx',+ ]) {+ const rows = guidedResultRows(readFileSync(join(adviceRoot, path), 'utf8'));+ expect(rows.map((row) => row.result).sort(), path).toEqual(+ Object.keys(SERVER_FIELDS_FOR_GUIDED_RESULT).sort(),+ );+ for (const { result, cells } of rows) {+ const fields = SERVER_FIELDS_FOR_GUIDED_RESULT[result];+ expect(cells.slice(1, 4), `${path}: ${result}`).toEqual([+ `\`${fields?.outcome}\``,+ `\`${fields?.saved}\``,+ `\`${fields?.nextStep}\``,+ ]);+ }+ }+});++test('the move for each guided result is the one its next step asks for', () => {+ const rows = guidedResultRows(+ readFileSync(+ join(adviceRoot, 'packages/server/assets/skills/project/references/conflict-resolution.md'),+ 'utf8',+ ),+ );+ for (const { result, cells } of rows) {+ const nextStep = cells[3];+ const move = cells[4] ?? '';+ if (nextStep === '`retry`') expect(move, result).toMatch(/\bsend\b[^.]*\bagain\b/i);+ if (nextStep === '`re-read`') expect(move, result).toMatch(/re-read/i);+ if (nextStep === '`none`') {+ expect(move, result).toMatch(/tell the user/i);+ expect(move, result).not.toMatch(/re-read|\bsend\b[^.]*\bagain\b|re-apply/i);+ }+ }+});diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.tsindex 609d61cd5..cec3cc03b 100644--- a/packages/server/src/mcp/tools/edit.ts+++ b/packages/server/src/mcp/tools/edit.ts@@ -68,6 +68,20 @@ import {TEMPLATE_METADATA_CONTROL_ADVICE,TEMPLATE_PATH_DESCRIBE,} from './verb-schemas.ts';+import {+ failedWriteResult,+ landedLead,+ landedWithoutSuccess,+ leadFor,+ needsAttention,+ refusedDespiteSuccess,+ refusedWriteResult,+ type WriteOutcome,+ writeOutcomeFields,+ writeOutcomeLine,+ writeOutcomeOf,+ writeOutcomeOutputShape,+} from './write-outcome.ts';const DESCRIPTION = ['Edit exactly one `document`, `folder`, `template`, or `skill`: body find/replace OR metadata, never both in one call. Requires the Hocuspocus server.',@@ -75,7 +89,7 @@ const DESCRIPTION = ["`folder: {path, frontmatter}` patches metadata (no body). `template: {path: '<folder>/<name>', ...}` takes body find/replace/occurrence or frontmatter.",'`skill: {name, ...}` takes body find/replace/occurrence OR description (its only metadata leaf). Recorded, unedited copies refresh from the source on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.','Optional summary: one-line outcome ≤80 chars for any edit, persisted to git history; avoid secrets or PII.',- 'Read structuredContent.document.warnings: content-divergence/disk-edit-reconciled means re-read with exec; mermaid-parse-error means the edit landed but fix the fence and re-edit.',+ 'Follow nextStep (retry|re-read|none). merged-first, both-kept and projection-held landed: re-read, never retry. mermaid-parse-error: the edit landed; fix the fence.',CANONICAL_COMPONENT_GUIDANCE,].join('\n');@@ -188,7 +202,13 @@ async function handleDocBody(...(args.summary !== undefined ? { summary: args.summary } : {}),...agentIdentityFields(identity),});- if (!result.ok) return textResult(errorTextWithDetail(result), true);+ const outcome = writeOutcomeOf(result);+ if (!result.ok && !landedWithoutSuccess(outcome)) {+ return failedWriteResult(errorTextWithDetail(result), outcome);+ }+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The edit of "${normalized.docName}"`, outcome);+ }return composeWritePreviewResult(result,normalized.docName,@@ -196,6 +216,7 @@ async function handleDocBody(contentDir,autoOpen,'Edit applied successfully.',+ outcome,);}@@ -217,7 +238,8 @@ async function handleDocFrontmatter(...(args.summary !== undefined ? { summary: args.summary } : {}),...agentIdentityFields(identity),});- if (!result.ok) {+ const outcome = writeOutcomeOf(result);+ if (!result.ok && !landedWithoutSuccess(outcome)) {const errorText = errorTextWithDetail(result);const fieldErrors =result.fieldErrors && typeof result.fieldErrors === 'object'@@ -225,9 +247,12 @@ async function handleDocFrontmatter(: undefined;if (fieldErrors) {const lines = Object.entries(fieldErrors).map(([k, m]) => ` ${k}: ${m}`);- return textResult(`${errorText}\n${lines.join('\n')}`, true);+ return failedWriteResult(`${errorText}\n${lines.join('\n')}`, outcome);}- return textResult(errorText, true);+ return failedWriteResult(errorText, outcome);+ }+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The frontmatter patch of "${normalized.docName}"`, outcome);}const setKeys: string[] = [];const deleteKeys: string[] = [];@@ -248,6 +273,7 @@ async function handleDocFrontmatter(contentDir,autoOpen,`Frontmatter patched (${opSummary || `${Object.keys(doc.frontmatter).length} key(s)`}).`,+ outcome,);}@@ -258,6 +284,7 @@ function composeWritePreviewResult(_contentDir: string,autoOpen: boolean,leadLine: string,+ outcome: WriteOutcome | undefined,) {const lockDir = resolveLockDir(cwd);const preview = resolvePreviewUrl(docName, { lockDir });@@ -273,7 +300,12 @@ function composeWritePreviewResult(const brokenLinks = parseBrokenLinks(result.brokenLinks);const brokenLinkSuppression = parseBrokenLinkSuppression(result.brokenLinkSuppression);- const lines: string[] = [leadLine];+ const lines: string[] = [+ outcome && landedWithoutSuccess(outcome) ? landedLead(outcome, 'Edit applied') : leadLine,+ ];+ if (outcome?.outcome === 'projection-held' && typeof result.detail === 'string') {+ lines.push(result.detail);+ }if (noPreviewAnywhere && !preview) lines.push(startUiTextHint());if (summaryHint) lines.push(summaryHint);if (advisoryWarnings) {@@ -281,6 +313,8 @@ function composeWritePreviewResult(}lines.push(...formatBrokenLinkLines(brokenLinks));if (brokenLinkSuppression) lines.push(formatBrokenLinkSuppressionLine(brokenLinkSuppression));+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);+ if (outcomeLine) lines.push(outcomeLine);const text = lines.join('\n');const document: Record<string, unknown> = {brokenLinks,@@ -289,7 +323,14 @@ function composeWritePreviewResult(if (summaryResult) document.summary = summaryResult;if (advisoryWarnings) document.warnings = advisoryWarnings;const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;- return textPlusStructured(text, nestDocResult(preview, warning, document));+ return textPlusStructured(+ text,+ {+ ...nestDocResult(preview, warning, outcome?.outcome === 'projection-held' ? {} : document),+ ...writeOutcomeFields(outcome),+ },+ needsAttention(outcome),+ );}function templateFilePath(@@ -367,14 +408,20 @@ async function handleTemplate(...(summary !== undefined ? { summary } : {}),...agentIdentityFields(deps.identityRef?.current),});+ const outcome = writeOutcomeOf(result);if (!result.ok)- return textResult(errorTextWithDetail(result, TEMPLATE_METADATA_CONTROL_ADVICE), true);+ return failedWriteResult(+ errorTextWithDetail(result, TEMPLATE_METADATA_CONTROL_ADVICE),+ outcome,+ );+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The frontmatter patch of template "${name}"`, outcome);+ }const path = typeof result.path === 'string' ? result.path : undefined;- return textPlusStructured(+ return templateEditResult(`Patched template "${name}" frontmatter${path ? ` (${path})` : ''}.`,- {- template: { ok: true, path },- },+ path,+ outcome,);}@@ -398,12 +445,29 @@ async function handleTemplate(...(summary !== undefined ? { summary } : {}),...agentIdentityFields(deps.identityRef?.current),});+ const outcome = writeOutcomeOf(result);if (!result.ok)- return textResult(errorTextWithDetail(result, TEMPLATE_EDIT_CONTROL_ADVICE), true);+ return failedWriteResult(errorTextWithDetail(result, TEMPLATE_EDIT_CONTROL_ADVICE), outcome);+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The edit of template "${name}"`, outcome);+ }const path = typeof result.path === 'string' ? result.path : undefined;- return textPlusStructured(`Edited template "${name}"${path ? ` (${path})` : ''}.`, {- template: { ok: true, path },- });+ return templateEditResult(`Edited template "${name}"${path ? ` (${path})` : ''}.`, path, outcome);+}++function templateEditResult(+ lead: string,+ path: string | undefined,+ outcome: WriteOutcome | undefined,+) {+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);+ return textPlusStructured(+ [leadFor(outcome, lead.replace(/\.$/, ''), lead), ...(outcomeLine ? [outcomeLine] : [])].join(+ '\n',+ ),+ { template: { ok: true, path }, ...writeOutcomeFields(outcome) },+ needsAttention(outcome),+ );}async function handleSkillFileEdit(@@ -666,11 +730,12 @@ export function register(server: ServerInstance, deps: EditDeps): void {cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),},outputSchema: outputSchemaWithText({+ ...writeOutcomeOutputShape,document: z.object(documentResultBaseShape).optional().describe(- 'Document edit result. Always present on a successful document edit (body or frontmatter) — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet. Absent only for folder/template edits.',+ 'Document edit result. Present on every saved document edit, body or frontmatter (absent when the outcome is projection-held, whose links were not checked) — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet. Absent only for folder/template edits.',),folder: z.object({diff --git a/packages/server/src/mcp/tools/lint.ts b/packages/server/src/mcp/tools/lint.tsindex 3cdfaa93e..77fe150e8 100644--- a/packages/server/src/mcp/tools/lint.ts+++ b/packages/server/src/mcp/tools/lint.ts@@ -31,6 +31,18 @@ import {textResult,zeroFindingsSummary,} from './shared.ts';+import {+ failedWriteResult,+ landedLead,+ landedWithoutSuccess,+ needsAttention,+ refusedDespiteSuccess,+ refusedWriteResult,+ writeOutcomeFields,+ writeOutcomeLine,+ writeOutcomeOf,+ writeOutcomeOutputShape,+} from './write-outcome.ts';export const DESCRIPTION = ["Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; the OpenKnowledge CLI's lint --fix is the unattributed headless/CI path.",@@ -136,6 +148,7 @@ export function register(server: ServerInstance, deps: LintDeps): void {cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),},outputSchema: outputSchemaWithText({+ ...writeOutcomeOutputShape,files: looseObjectArray.optional().describe(@@ -144,11 +157,13 @@ export function register(server: ServerInstance, deps: LintDeps): void {fileCount: z.number().optional().describe('Audit only: total in-scope documents scanned.'),errorCount: z.number()+ .optional().describe('Total error-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true.',),warningCount: z.number()+ .optional().describe('Total warning-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true.',),@@ -177,7 +192,10 @@ export function register(server: ServerInstance, deps: LintDeps): void {.describe('Fix mode only: the server-reported number of problems resolved by auto-fix, or 0 if omitted. When `diagnosticsArePreFix` is true, the post-fix result is unavailable; do not treat 0 as evidence that nothing was fixed.',),- cwd: z.string().describe('Absolute directory the lint ran against.'),+ cwd: z+ .string()+ .optional()+ .describe('Absolute directory the lint ran against; absent when a fix did not land.'),}),annotations: {readOnlyHint: false,@@ -225,7 +243,11 @@ async function fixLintDoc(docName: normalized.docName,...agentIdentityFields(identity),});- if (!result.ok) return textResult(errorTextWithDetail(result), true);+ const outcome = writeOutcomeOf(result);+ if (!result.ok) return failedWriteResult(errorTextWithDetail(result), outcome);+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The auto-fix of ${normalized.docName}`, outcome);+ }const { ok: _ok, ...rest } = result;const data = rest as LintFixPayload;const file = data.file ?? normalized.docName;@@ -274,6 +296,7 @@ async function fixLintDoc(...(reLintFailure ? { reLintFailure } : {}),...(data.ran === undefined ? {} : { ran: data.ran }),cwd,+ ...writeOutcomeFields(outcome),};const header = diagnosticsArePreFix@@ -291,11 +314,25 @@ async function fixLintDoc(`${diagnostics.length} problem${diagnostics.length === 1 ? '' : 's'} remain (${countSummary(errorCount, warningCount)}) — need content edits via \`edit\`/\`write\`.`,]: [];+ const outcomeLine =+ outcome === undefined || outcome.outcome === 'applied' ? [] : [writeOutcomeLine(outcome) ?? ''];+ const landedLine =+ outcome !== undefined && landedWithoutSuccess(outcome)+ ? [landedLead(outcome, `Applied auto-fixes to ${file}`)]+ : [];const textLines =diagnostics.length === 0- ? [header, ...coverageLines, ...warningBlock]- : [header, ...lines, ...warningBlock, ...footer, ...coverageLines];- return textPlusStructured(textLines.join('\n'), structured);+ ? [...landedLine, header, ...outcomeLine, ...coverageLines, ...warningBlock]+ : [+ ...landedLine,+ header,+ ...outcomeLine,+ ...lines,+ ...warningBlock,+ ...footer,+ ...coverageLines,+ ];+ return textPlusStructured(textLines.join('\n'), structured, needsAttention(outcome));}async function lintSingleDoc(document: string, url: string, cwd: string) {diff --git a/packages/server/src/mcp/tools/restore-version.ts b/packages/server/src/mcp/tools/restore-version.tsindex 33fa187e3..57981e185 100644--- a/packages/server/src/mcp/tools/restore-version.ts+++ b/packages/server/src/mcp/tools/restore-version.ts@@ -6,6 +6,7 @@ import { resolvePreviewUrlForTool } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ errorTextWithDetail,hocuspocusNotRunningError,httpGet,httpPost,@@ -21,6 +22,17 @@ import {textResult,versionInputSchema,} from './shared.ts';+import {+ failedWriteResult,+ leadFor,+ needsAttention,+ refusedDespiteSuccess,+ refusedWriteResult,+ writeOutcomeFields,+ writeOutcomeLine,+ writeOutcomeOf,+ writeOutcomeOutputShape,+} from './write-outcome.ts';export const DESCRIPTION = ['Restore exactly one document or skill to version (40-char SHA from history). Requires the Hocuspocus server. document accepts optional .md/.mdx; restore is append-only through CRDT and visible to connected editors. skill is a PROJECT-scope name (global is unversioned); its folder is rewritten. Recorded, unedited copies refresh on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.',@@ -57,17 +69,23 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): voidcwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),},outputSchema: outputSchemaWithText({+ ...writeOutcomeOutputShape,document: z.string().optional().describe('The document that was restored (echo of the input).'),skill: z.string().optional().describe('The skill that was restored (echo of the input).'),- version: z.string().describe('The version that was restored to (echo of the input).'),+ version: z+ .string()+ .optional()+ .describe(+ 'The version that was restored to (echo of the input); absent when the restore did not land.',+ ),restoredFiles: z.array(z.string()).optional().describe('Skill restore only: the skill-dir-relative files rewritten.'),- previewUrl: previewUrlOutputField,+ previewUrl: previewUrlOutputField.optional(),previewUrlSource: previewUrlSourceField,summary: summaryOutputSchema.optional(),warnings: z@@ -144,7 +162,11 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): void...(args.summary !== undefined ? { summary: args.summary } : {}),...agentIdentityFields(identity),});- if (!result.ok) return textResult(`Error: ${result.error}`, true);+ const outcome = writeOutcomeOf(result);+ if (!result.ok) return failedWriteResult(errorTextWithDetail(result), outcome);+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The restore of "${docName}"`, outcome);+ }const summaryResult =result.summary && typeof result.summary === 'object'@@ -159,26 +181,37 @@ export function register(server: ServerInstance, deps: RestoreVersionDeps): voidtypeof versionResult.timestamp === 'string' ? versionResult.timestamp : undefined;const provenance = author && timestamp ? ` (${author}, ${timestamp})` : '';const textLines = [- `Restored "${docName}" to version ${args.version.slice(0, 8)}${provenance}. The change has been applied to all connected editors.`,+ leadFor(+ outcome,+ `Restored "${docName}" to version ${args.version.slice(0, 8)}`,+ `Restored "${docName}" to version ${args.version.slice(0, 8)}${provenance}. The change has been applied to all connected editors.`,+ ),];if (summaryHint) textLines.push(summaryHint);if (advisoryWarnings) {textLines.push(...formatAdvisoryLines(advisoryWarnings));}+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);+ if (outcomeLine) textLines.push(outcomeLine);const preview = await resolvePreviewUrlForTool(docName,{ config: deps.config, resolveCwd: deps.resolveCwd },cwd,);- return textPlusStructured(textLines.join('\n'), {- document: docName,- version: args.version,- previewUrl: preview?.url ?? null,- ...(preview ? { previewUrlSource: preview.source } : {}),- ...(summaryResult ? { summary: summaryResult } : {}),- ...(advisoryWarnings ? { warnings: advisoryWarnings } : {}),- });+ return textPlusStructured(+ textLines.join('\n'),+ {+ document: docName,+ version: args.version,+ previewUrl: preview?.url ?? null,+ ...(preview ? { previewUrlSource: preview.source } : {}),+ ...(summaryResult ? { summary: summaryResult } : {}),+ ...(advisoryWarnings ? { warnings: advisoryWarnings } : {}),+ ...writeOutcomeFields(outcome),+ },+ needsAttention(outcome),+ );},);}diff --git a/packages/server/src/mcp/tools/session-capacity-refusal.test.ts b/packages/server/src/mcp/tools/session-capacity-refusal.test.tsindex 29789b64f..6ce44f508 100644--- a/packages/server/src/mcp/tools/session-capacity-refusal.test.ts+++ b/packages/server/src/mcp/tools/session-capacity-refusal.test.ts@@ -156,7 +156,7 @@ describe('MCP write paths relaying an agent-session capacity refusal', () => {expect(result.isError).toBe(true);expect(result.content[0]?.text).toBe(- `Error: document created from template "note", but its frontmatter patch was refused, so the document exists without that frontmatter: ${REFUSAL_TEXT} Apply the frontmatter alone with edit({ document: { path: "notes/templated", frontmatter } }); do not repeat the templated write.`,+ `Error: document created from template "note"; its body landed, but its frontmatter patch was refused, so the frontmatter was not applied: ${REFUSAL_TEXT} Re-read the document, then apply the frontmatter alone with edit({ document: { path: "notes/templated", frontmatter } }); do not repeat the templated write.`,);});@@ -171,7 +171,7 @@ describe('MCP write paths relaying an agent-session capacity refusal', () => {expect(result.isError).toBe(true);expect(result.content[0]?.text).toBe(- `Error: document created from template "note", but its frontmatter patch failed, and this response does not show whether the frontmatter was applied: ${STALE_TITLE} (${STALE_DETAIL}) Re-read the document before changing it; do not repeat the templated write.`,+ `Error: document created from template "note"; its body landed, but its frontmatter patch failed, and this response does not show whether the frontmatter was applied: ${STALE_TITLE} (${STALE_DETAIL}) Re-read the document, then apply only the missing frontmatter with edit({ document: { path: "notes/templated-stale", frontmatter } }); do not repeat the templated write.`,);});@@ -186,7 +186,7 @@ describe('MCP write paths relaying an agent-session capacity refusal', () => {expect(result.isError).toBe(true);expect(result.content[0]?.text).toBe(- `Error: document created from template "note", but its frontmatter patch was refused, so the document exists without that frontmatter: ${INVALID_TITLE} Apply the frontmatter alone with edit({ document: { path: "notes/templated-invalid", frontmatter } }); do not repeat the templated write.`,+ `Error: document created from template "note"; its body landed, but its frontmatter patch was refused, so the frontmatter was not applied: ${INVALID_TITLE} Re-read the document, then apply the frontmatter alone with edit({ document: { path: "notes/templated-invalid", frontmatter } }); do not repeat the templated write.`,);});diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.tsindex b0f5cd8fc..76b6149c7 100644--- a/packages/server/src/mcp/tools/skill-target.ts+++ b/packages/server/src/mcp/tools/skill-target.ts@@ -31,6 +31,16 @@ import {SKILL_FILE_EDIT_CONTROL_ADVICE,SKILL_METADATA_CONTROL_ADVICE,} from './verb-schemas.ts';+import {+ failedWriteResult,+ leadFor,+ needsAttention,+ refusedDespiteSuccess,+ refusedWriteResult,+ writeOutcomeFields,+ writeOutcomeLine,+ writeOutcomeOf,+} from './write-outcome.ts';export type { SkillScope };@@ -69,8 +79,9 @@ export async function writeSkill(...(input.summary !== undefined ? { summary: input.summary } : {}),...agentIdentityFields(input.identity),});+ const outcome = writeOutcomeOf(result);if (!result.ok)- return textResult(+ return failedWriteResult(errorTextWithDetail(result,input.resubmitted@@ -79,8 +90,11 @@ export async function writeSkill(: SKILL_EDIT_CONTROL_ADVICE: 'Any body offset refers to the full submitted skill body.',),- true,+ outcome,);+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The write of skill "${input.name}"`, outcome);+ }const created = result.created === true;const path = typeof result.path === 'string' ? result.path : undefined;const aligned = alignWarningCodes(@@ -88,17 +102,28 @@ export async function writeSkill(result.warningCodes,KNOWN_AUTHORING_WARNING_CODES,);+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);const lines = [- `${created ? 'Created' : 'Updated'} skill "${input.name}"${path ? ` (${path})` : ''} — live for that folder's agent. Use \`install\` with \`add\` to put it in your other editors.`,+ leadFor(+ outcome,+ `${created ? 'Created' : 'Updated'} skill "${input.name}"`,+ `${created ? 'Created' : 'Updated'} skill "${input.name}"${path ? ` (${path})` : ''} — live for that folder's agent. Use \`install\` with \`add\` to put it in your other editors.`,+ ),...aligned.warnings,+ ...(outcomeLine ? [outcomeLine] : []),];const preview = input.lockDir? resolveSkillPreviewUrl(input.scope ?? 'project', input.name, { lockDir: input.lockDir }): null;- return textPlusStructured(lines.join('\n'), {- skill: { ok: true, path, created, ...aligned },- ...(preview ? { previewUrl: preview.url, previewUrlSource: preview.source } : {}),- });+ return textPlusStructured(+ lines.join('\n'),+ {+ skill: { ok: true, path, created, ...aligned },+ ...(preview ? { previewUrl: preview.url, previewUrlSource: preview.source } : {}),+ ...writeOutcomeFields(outcome),+ },+ needsAttention(outcome),+ );}export async function fetchSkill(@@ -155,8 +180,9 @@ export async function writeSkillFile(...(input.summary !== undefined ? { summary: input.summary } : {}),...agentIdentityFields(input.identity),});+ const outcome = writeOutcomeOf(result);if (!result.ok)- return textResult(+ return failedWriteResult(errorTextWithDetail(result,isMarkdownSkillFilePath(input.path)@@ -165,14 +191,26 @@ export async function writeSkillFile(: 'Any content offset refers to the whole submitted file content, including frontmatter.': undefined,),- true,+ outcome,);+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The write of "${input.path}" in skill "${input.name}"`, outcome);+ }const created = result.created === true;const path = typeof result.path === 'string' ? result.path : input.path;const kind = result.kind === 'script' ? 'script' : 'reference';+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);return textPlusStructured(- `${created ? 'Created' : 'Updated'} skill ${kind} "${input.path}" in "${input.name}".`,- { skill: { ok: true, file: { path, kind, created } } },+ [+ leadFor(+ outcome,+ `${created ? 'Created' : 'Updated'} skill ${kind} "${input.path}" in "${input.name}"`,+ `${created ? 'Created' : 'Updated'} skill ${kind} "${input.path}" in "${input.name}".`,+ ),+ ...(outcomeLine ? [outcomeLine] : []),+ ].join('\n'),+ { skill: { ok: true, file: { path, kind, created } }, ...writeOutcomeFields(outcome) },+ needsAttention(outcome),);}diff --git a/packages/server/src/mcp/tools/write-outcome.test.ts b/packages/server/src/mcp/tools/write-outcome.test.tsnew file mode 100644index 000000000..3fe8db96c--- /dev/null+++ b/packages/server/src/mcp/tools/write-outcome.test.ts@@ -0,0 +1,613 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { ConfigSchema } from '../../config/schema.ts';+import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';+import { registerAllTools } from './index.ts';++const BOTH_KEPT = { outcome: 'both-kept', saved: true, nextStep: 're-read' } as const;+const REFUSED = { outcome: 'refused', saved: false, nextStep: 're-read' } as const;+let appRouteFields: Record<string, unknown> = BOTH_KEPT;+let skillFileWrites = 0;+const LANDED = 'The write landed and is saved; do not retry it.';++const documentAnswers = new Map<string, { status: number; body: Record<string, unknown> }>([+ [+ 'newer-saved',+ {+ status: 200,+ body: {+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ brokenLinks: [],+ outcome: 'displaced',+ saved: true,+ nextStep: 'ask',+ },+ },+ ],+ [+ 'newer-unsaved',+ {+ status: 409,+ body: {+ type: 'urn:ok:error:doc-removed',+ title: 'A refusal a newer server describes.',+ status: 409,+ detail: 'Detail from a newer server.',+ outcome: 'held',+ saved: false,+ nextStep: 'retry',+ },+ },+ ],+ [+ 'older-server',+ {+ status: 200,+ body: { timestamp: 't', subscriberCount: 0, systemSubscriberCount: 1, brokenLinks: [] },+ },+ ],+ [+ 'beta-held',+ {+ status: 503,+ body: {+ type: 'urn:ok:error:save-held',+ title: 'Edit applied in memory; its save to disk is held.',+ status: 503,+ detail: 'beta-held was not saved.',+ reason: 'pending-unreadable',+ retryWhen: 'next-save',+ nextStep: 're-read',+ },+ },+ ],+ [+ 'fm-both-kept',+ {+ status: 409,+ body: {+ type: 'urn:ok:error:both-kept',+ title: 'Edit saved; both versions of a block changed here and outside were kept.',+ status: 409,+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ brokenLinks: [],+ ...BOTH_KEPT,+ },+ },+ ],+ [+ 'fm-applied',+ {+ status: 200,+ body: {+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ brokenLinks: [],+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+ },+ },+ ],+ ...['fm-malformed', 'fm-patch-unanswered'].map(+ (name) =>+ [+ name,+ {+ status: 200,+ body: {+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ brokenLinks: [],+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+ },+ },+ ] as const,+ ),+ [+ 'partial-both-kept',+ {+ status: 409,+ body: {+ type: 'urn:ok:error:both-kept',+ title: 'Edit saved; both versions of a block changed here and outside were kept.',+ status: 409,+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ brokenLinks: [],+ outcome: 'both-kept',+ },+ },+ ],+ [+ 'batch-held',+ {+ status: 503,+ body: {+ type: 'urn:ok:error:doc-moved',+ title: 'Edit kept: the document was moved outside the app, and the edit moved with it.',+ status: 409,+ detail: 'batch-held moved to moved/batch-held. Re-read moved/batch-held to confirm.',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ },+ },+ ],+ [+ 'fm-held',+ {+ status: 503,+ body: {+ type: 'urn:ok:error:save-held',+ title: 'Edit applied in memory; its save to disk is held.',+ status: 503,+ detail: 'fm-held was not saved.',+ reason: 'pending-unreadable',+ outcome: 'projection-held',+ saved: false,+ nextStep: 're-read',+ },+ },+ ],+]);++const frontmatterPatches: string[] = [];++let testServer: FetchTestServer;+let cwd: string;+let client: Client;++beforeAll(async () => {+ testServer = await startFetchTestServer({+ hostname: '127.0.0.1',+ async fetch(request) {+ const { pathname } = new URL(request.url);+ if (request.method === 'GET' && pathname.startsWith('/api/history/')) {+ return Response.json({ author: 'someone', timestamp: 't', content: '# v1\n' });+ }+ if (request.method === 'GET' && pathname === '/api/skill-file') {+ return Response.json({ path: 'references/a.md', kind: 'reference', text: 'a\n' });+ }+ const body = (await request.json()) as { docName?: string };+ switch (pathname) {+ case '/api/agent-write-md': {+ const answer = documentAnswers.get(body.docName ?? '');+ if (!answer) return Response.json({ error: 'unexpected document' }, { status: 500 });+ return Response.json(answer.body, { status: answer.status });+ }+ case '/api/frontmatter-patch':+ frontmatterPatches.push(body.docName ?? '');+ if (body.docName === 'fm-malformed') {+ return Response.json(+ {+ type: 'urn:ok:error:frontmatter-malformed',+ title: 'Frontmatter YAML is malformed.',+ status: 400,+ outcome: 'refused',+ saved: false,+ nextStep: 'retry',+ },+ { status: 400 },+ );+ }+ if (body.docName === 'fm-patch-unanswered') {+ return Response.json({ error: 'internal' }, { status: 500 });+ }+ if (body.docName === 'fm-applied') {+ return Response.json(+ {+ type: 'urn:ok:error:both-kept',+ title: 'Edit saved; both versions of a block changed here and outside were kept.',+ status: 409,+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ appliedKeys: ['title'],+ brokenLinks: [],+ ...BOTH_KEPT,+ },+ { status: 409 },+ );+ }+ return Response.json({+ timestamp: 't',+ subscriberCount: 0,+ systemSubscriberCount: 1,+ appliedKeys: ['title'],+ brokenLinks: [],+ outcome: 'applied',+ saved: true,+ nextStep: 'none',+ });+ case '/api/template':+ return Response.json({+ path: 'guides/.ok/templates/tpl.md',+ created: false,+ warnings: [],+ ...appRouteFields,+ });+ case '/api/skill':+ return Response.json({+ path: '.agents/skills/demo/SKILL.md',+ created: false,+ warnings: [],+ warningCodes: [],+ ...appRouteFields,+ });+ case '/api/skill-file':+ skillFileWrites += 1;+ return Response.json({+ path: 'references/a.md',+ created: false,+ kind: 'reference',+ content: true,+ ...appRouteFields,+ });+ case '/api/rollback':+ return Response.json({ restoredFrom: 'v1', timestamp: 't', ...appRouteFields });+ case '/api/lint/fix':+ return Response.json({+ file: 'notes/a.md',+ fixedCount: 1,+ diagnostics: [],+ errorCount: 0,+ warningCount: 0,+ ran: ['markdownlint'],+ ...appRouteFields,+ });+ default:+ return Response.json({ error: `unexpected route ${pathname}` }, { status: 500 });+ }+ },+ });+ cwd = mkdtempSync(join(tmpdir(), 'ok-write-outcome-normalize-'));+ mkdirSync(join(cwd, '.ok', 'templates'), { recursive: true });+ writeFileSync(+ join(cwd, '.ok', 'templates', 'tpl.md'),+ '---\ntitle: Tpl\n---\n\nTemplate body.\n',+ );+ mkdirSync(join(cwd, 'guides', '.ok', 'templates'), { recursive: true });+ writeFileSync(+ join(cwd, 'guides', '.ok', 'templates', 'tpl.md'),+ '---\ntitle: Tpl\n---\n\nBody line.\n',+ );+ const server = new McpServer({ name: 'write-outcome', version: '1' });+ registerAllTools(server, {+ serverUrl: `http://127.0.0.1:${testServer.port}`,+ config: ConfigSchema.parse({}),+ resolveCwd: async () => cwd,+ });+ client = new Client({ name: 'write-outcome', version: '1' });+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(serverSide), client.connect(clientSide)]);+ await client.listTools();+});++afterAll(async () => {+ await client.close();+ testServer.stop();+ rmSync(cwd, { recursive: true, force: true });+});++function write(path: string) {+ return client.callTool({+ name: 'write',+ arguments: { document: { path, content: 'Line.\n', position: 'replace' } },+ });+}++function textOf(result: { content: unknown }): string {+ return (result.content as Array<{ text?: string }>)[0]?.text ?? '';+}++describe('a write tool copy meeting outcome values it does not know', () => {+ test('reads an unknown outcome on a saved write as merged-first with a re-read, and says so', async () => {+ const result = await write('newer-saved');+ expect(result.structuredContent).toMatchObject({+ outcome: 'merged-first',+ saved: true,+ nextStep: 're-read',+ });+ const { text: _mirroredText, ...fields } = result.structuredContent as Record<string, unknown>;+ expect(JSON.stringify(fields)).not.toContain('displaced');+ expect(textOf(result)).toContain('outcome "displaced", which this tool version does not know');+ });++ test('reads an unknown outcome on an unsaved write as refused with a re-read, never a retry', async () => {+ const result = await write('newer-unsaved');+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({+ outcome: 'refused',+ saved: false,+ nextStep: 're-read',+ });+ expect(textOf(result)).toContain('A refusal a newer server describes.');+ });++ test('invents no outcome when an older server sends none', async () => {+ const result = await write('older-server');+ expect(result.isError).toBeFalsy();+ expect(result.structuredContent).not.toHaveProperty('outcome');+ expect(result.structuredContent).not.toHaveProperty('saved');+ });++ test('invents no outcome from a beta save-held that carries only nextStep and retryWhen', async () => {+ const result = await write('beta-held');+ expect(result.isError).toBe(true);+ expect(result.structuredContent ?? {}).not.toHaveProperty('outcome');+ expect(textOf(result)).not.toContain('Outcome:');+ expect(textOf(result)).toContain('its save to disk is held');+ });+});++describe('a both-kept result from every write tool opens by saying the write landed', () => {+ test.each([+ {+ tool: 'write',+ args: {+ template: {+ path: 'guides/tpl2',+ content: '# {{date}}\n',+ frontmatter: { title: 'Tpl two' },+ },+ },+ },+ {+ tool: 'edit',+ args: { template: { path: 'guides/tpl', find: 'Body line.', replace: 'Edited line.' } },+ },+ {+ tool: 'write',+ args: { skill: { name: 'demo', description: 'Use when testing.', body: '# Demo\n' } },+ },+ {+ tool: 'edit',+ args: { skill: { name: 'demo', file: 'references/a.md', find: 'a', replace: 'b' } },+ },+ { tool: 'restore_version', args: { document: 'notes/a', version: 'a'.repeat(40) } },+ { tool: 'lint', args: { document: 'notes/a', fix: true } },+ ])('$tool $args', async ({ tool, args }) => {+ const result = await client.callTool({ name: tool, arguments: args });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject(BOTH_KEPT);+ expect(textOf(result).split('\n')[0]).toContain(LANDED);+ });++ test('write skill files each open their line with the landed note', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: { skill: { name: 'demo', files: [{ path: 'references/a.md', content: 'a\n' }] } },+ });+ expect(result.isError).toBe(true);+ expect(textOf(result)).toContain(LANDED);+ expect(+ (result.structuredContent as { skill: { files: Array<Record<string, unknown>> } }).skill+ .files[0],+ ).toMatchObject(BOTH_KEPT);+ });+});++describe('a templated write with frontmatter that lands without plain success', () => {+ test('still applies the frontmatter when both versions were kept', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'fm-both-kept', template: 'tpl', frontmatter: { title: 'Mine' } },+ },+ });+ expect(result.structuredContent).toMatchObject(BOTH_KEPT);+ expect(frontmatterPatches).toContain('fm-both-kept');+ });++ test('says the frontmatter was not applied when the save is held', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'fm-held', template: 'tpl', frontmatter: { title: 'Mine' } },+ },+ });+ expect(result.structuredContent).toMatchObject({+ outcome: 'projection-held',+ nextStep: 're-read',+ });+ expect(frontmatterPatches).not.toContain('fm-held');+ expect(textOf(result)).toContain('was not applied');+ });+});++describe('a write the server answered without an error status but reported as refused', () => {+ test.each([+ {+ tool: 'write',+ args: {+ template: {+ path: 'guides/tpl3',+ content: '# {{date}}\n',+ frontmatter: { title: 'Tpl three' },+ },+ },+ success: /Created template|Updated template/,+ },+ {+ tool: 'edit',+ args: { template: { path: 'guides/tpl', find: 'Body line.', replace: 'Edited line.' } },+ success: /Edited template/,+ },+ {+ tool: 'write',+ args: { skill: { name: 'demo', description: 'Use when testing.', body: '# Demo\n' } },+ success: /Created skill|Updated skill/,+ },+ {+ tool: 'edit',+ args: { skill: { name: 'demo', file: 'references/a.md', find: 'a', replace: 'b' } },+ success: /Updated skill|Created skill/,+ },+ {+ tool: 'restore_version',+ args: { document: 'notes/a', version: 'a'.repeat(40) },+ success: /Restored/,+ },+ { tool: 'lint', args: { document: 'notes/a', fix: true }, success: /Fixed|Applied auto-fixes/ },+ ])(+ '$tool $args opens with the refusal, not the success line',+ async ({ tool, args, success }) => {+ appRouteFields = REFUSED;+ try {+ const result = await client.callTool({ name: tool, arguments: args });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject(REFUSED);+ expect(result.structuredContent).not.toHaveProperty('skill');+ expect(result.structuredContent).not.toHaveProperty('template');+ const firstLine = textOf(result).split('\n')[0] ?? '';+ expect(firstLine).toMatch(/^Error: .* was not saved\./);+ expect(textOf(result)).not.toMatch(success);+ } finally {+ appRouteFields = BOTH_KEPT;+ }+ },+ );++ test('a refused SKILL.md stops the bundle file writes', async () => {+ appRouteFields = REFUSED;+ const before = skillFileWrites;+ try {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ skill: {+ name: 'demo',+ description: 'Use when testing.',+ files: [{ path: 'references/a.md', content: 'a\n' }],+ },+ },+ });+ expect(result.isError).toBe(true);+ expect(skillFileWrites).toBe(before);+ } finally {+ appRouteFields = BOTH_KEPT;+ }+ });+});++describe('fields a server leaves out stay out', () => {+ test('a both-kept answer with no saved flag or next step reports neither', async () => {+ const result = await write('partial-both-kept');+ expect(result.structuredContent).toMatchObject({ outcome: 'both-kept' });+ expect(result.structuredContent).not.toHaveProperty('saved');+ expect(result.structuredContent).not.toHaveProperty('nextStep');+ expect(textOf(result)).not.toContain('undefined');+ expect(textOf(result)).not.toContain('saved: no');+ });+});++describe('a templated write whose frontmatter patch kept both versions', () => {+ test('reports the patch as landed with both-kept, not as a failure', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'fm-applied', template: 'tpl', frontmatter: { title: 'Mine' } },+ },+ });+ expect(result.structuredContent).toMatchObject(BOTH_KEPT);+ expect(textOf(result)).not.toContain('does not show whether the frontmatter was applied');+ expect(textOf(result).split('\n')[0]).toContain(LANDED);+ });+});++describe('a templated write whose body landed but whose frontmatter patch failed', () => {+ test('reports the body as saved and scopes the next step to the frontmatter', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ document: { path: 'fm-malformed', template: 'tpl', frontmatter: { title: 'Mine' } },+ },+ });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({+ outcome: 'applied',+ saved: true,+ nextStep: 're-read',+ });+ const text = textOf(result);+ expect(text).toContain('its body landed');+ expect(text).toContain('the frontmatter was not applied');+ expect(text).toContain('Re-read the document, then apply the frontmatter alone');+ expect(text).toContain('do not repeat the templated write');+ expect(text).not.toContain('next step: retry');+ expect(text).not.toContain('saved: no');+ });++ test('says the frontmatter result is unknown when the patch answer carries no outcome', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ document: {+ path: 'fm-patch-unanswered',+ template: 'tpl',+ frontmatter: { title: 'Mine' },+ },+ },+ });+ expect(result.structuredContent).toMatchObject({+ outcome: 'applied',+ saved: true,+ nextStep: 're-read',+ });+ expect(textOf(result)).toContain('does not show whether the frontmatter was applied');+ expect(textOf(result)).toContain('do not repeat the templated write');+ });++ test('reports a batch entry the same way', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ documents: [{ path: 'fm-malformed', template: 'tpl', frontmatter: { title: 'Mine' } }],+ },+ });+ const entries = (result.structuredContent as { documents: Array<Record<string, unknown>> })+ .documents;+ expect(entries[0]).toMatchObject({+ ok: false,+ outcome: 'applied',+ saved: true,+ nextStep: 're-read',+ });+ expect(textOf(result)).toContain('do not repeat the templated write');+ });+});++describe('a batch entry whose save is held', () => {+ test('claims no link result and carries the server detail', async () => {+ const result = await client.callTool({+ name: 'write',+ arguments: {+ documents: [+ { path: 'fm-applied', content: 'Line.\n', position: 'replace' },+ { path: 'batch-held', content: 'Line.\n', position: 'replace' },+ ],+ },+ });+ const entries = (result.structuredContent as { documents: Array<Record<string, unknown>> })+ .documents;+ expect(entries[0]).toHaveProperty('brokenLinks');+ expect(entries[1]).toMatchObject({ outcome: 'projection-held', saved: false });+ expect(entries[1]).not.toHaveProperty('brokenLinks');+ expect(textOf(result)).toContain('Re-read moved/batch-held to confirm.');+ });+});diff --git a/packages/server/src/mcp/tools/write-outcome.ts b/packages/server/src/mcp/tools/write-outcome.tsnew file mode 100644index 000000000..7fd606441--- /dev/null+++ b/packages/server/src/mcp/tools/write-outcome.ts@@ -0,0 +1,148 @@+import {+ AGENT_WRITE_NEXT_STEP_MEANINGS,+ AGENT_WRITE_NEXT_STEPS,+ AGENT_WRITE_OUTCOME_MEANINGS,+ AGENT_WRITE_OUTCOMES,+ type NormalizedAgentWriteOutcome,+ normalizeAgentWriteOutcome,+} from '@inkeep/open-knowledge-core';+import { z } from 'zod';+import { textPlusStructured, textResult } from './shared.ts';++export type WriteOutcome = NormalizedAgentWriteOutcome;++function meaningList(meanings: Readonly<Record<string, string>>): string {+ return Object.entries(meanings)+ .map(([value, meaning]) => `\`${value}\`: ${meaning}`)+ .join('; ');+}++export const writeOutcomeOutputShape = {+ outcome: z+ .enum(AGENT_WRITE_OUTCOMES)+ .optional()+ .describe(+ `What happened to this write, present on every write result the server answered, success or not. ${meaningList(AGENT_WRITE_OUTCOME_MEANINGS)}. A value this tool version does not know is reported as merged-first when saved, else refused, with nextStep re-read.`,+ ),+ saved: z+ .boolean()+ .optional()+ .describe(+ "Whether the write's bytes were in the document's file when the server answered. Not the same as the move result's `committed` (git history).",+ ),+ nextStep: z+ .enum(AGENT_WRITE_NEXT_STEPS)+ .optional()+ .describe(+ `What to do next about this write. ${meaningList(AGENT_WRITE_NEXT_STEP_MEANINGS)}. Never retry a write whose outcome is merged-first, both-kept or projection-held: it landed.`,+ ),+} as const;++export function writeOutcomeOf(result: {+ readonly [key: string]: unknown;+}): WriteOutcome | undefined {+ return normalizeAgentWriteOutcome({+ outcome: result.outcome,+ saved: result.saved,+ nextStep: result.nextStep,+ });+}++export function writeOutcomeFields(outcome: WriteOutcome | undefined): {+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+} {+ if (outcome === undefined) return {};+ return {+ outcome: outcome.outcome,+ ...(outcome.saved === undefined ? {} : { saved: outcome.saved }),+ ...(outcome.nextStep === undefined ? {} : { nextStep: outcome.nextStep }),+ };+}++export function landedWithoutSuccess(outcome: WriteOutcome | undefined): boolean {+ return outcome?.outcome === 'both-kept' || outcome?.outcome === 'projection-held';+}++export function needsAttention(outcome: WriteOutcome | undefined): boolean {+ return (+ outcome?.outcome === 'refused' ||+ outcome?.outcome === 'both-kept' ||+ outcome?.outcome === 'projection-held'+ );+}++export function writeOutcomeLine(outcome: WriteOutcome | undefined): string | null {+ if (outcome === undefined) return null;+ const unknown =+ outcome.unknownOutcome !== undefined+ ? ` The server reported outcome "${outcome.unknownOutcome}", which this tool version does not know; treated as ${outcome.outcome}.`+ : outcome.unknownNextStep !== undefined+ ? ` The server reported next step "${outcome.unknownNextStep}", which this tool version does not know; treated as re-read.`+ : '';+ const parts = [+ `Outcome: ${outcome.outcome}`,+ ...(outcome.saved === undefined ? [] : [`saved: ${outcome.saved ? 'yes' : 'no'}`]),+ ...(outcome.nextStep === undefined ? [] : [`next step: ${outcome.nextStep}`]),+ ];+ return `${parts.join('; ')}.${unknown}`;+}++export function landedLead(outcome: WriteOutcome, done: string): string {+ return outcome.outcome === 'both-kept'+ ? `${done}: both versions of a block changed here and outside were kept. The write landed and is saved; do not retry it. Re-read the document and remove the duplicate with an ordinary edit if your task calls for it.`+ : `${done}: the edit is in the document, but its save to the file is not confirmed yet; OpenKnowledge saves it on its own. Do not retry it. Re-read the document before the next edit.`;+}++export function leadFor(outcome: WriteOutcome | undefined, done: string, lead: string): string {+ return outcome !== undefined && landedWithoutSuccess(outcome) ? landedLead(outcome, done) : lead;+}++export const REFUSED_WITHOUT_ERROR_STATUS =+ 'the write was not saved. The server answered without an error status but reported the write as refused.';++const OUTCOME_WEIGHT: Readonly<Record<WriteOutcome['outcome'], number>> = {+ applied: 0,+ 'merged-first': 1,+ 'both-kept': 2,+ 'projection-held': 3,+ refused: 4,+};++export function weightierOutcome(+ first: WriteOutcome | undefined,+ second: WriteOutcome | undefined,+): WriteOutcome | undefined {+ if (first === undefined) return second;+ if (second === undefined) return first;+ return OUTCOME_WEIGHT[second.outcome] > OUTCOME_WEIGHT[first.outcome] ? second : first;+}++export function rereadAfterLanding(outcome: WriteOutcome): WriteOutcome {+ return {+ outcome: outcome.outcome,+ ...(outcome.saved === undefined ? {} : { saved: outcome.saved }),+ nextStep: 're-read',+ ...(outcome.unknownOutcome === undefined ? {} : { unknownOutcome: outcome.unknownOutcome }),+ };+}++export function refusedDespiteSuccess(outcome: WriteOutcome | undefined): boolean {+ return outcome?.outcome === 'refused';+}++export function refusedWriteResult(what: string, outcome: WriteOutcome | undefined) {+ return failedWriteResult(+ `Error: ${what} was not saved. The server answered without an error status but reported the write as refused.`,+ outcome,+ );+}++export function failedWriteResult(text: string, outcome: WriteOutcome | undefined) {+ const line = writeOutcomeLine(outcome);+ const full = line === null ? text : `${text}\n${line}`;+ return outcome === undefined+ ? textResult(full, true)+ : textPlusStructured(full, writeOutcomeFields(outcome), true);+}diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 283096a5b..96e40f3c1 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -88,6 +88,23 @@ import {TEMPLATE_CONTENT_DESCRIBE,TEMPLATE_PATH_DESCRIBE,} from './verb-schemas.ts';+import {+ failedWriteResult,+ landedLead,+ landedWithoutSuccess,+ leadFor,+ needsAttention,+ REFUSED_WITHOUT_ERROR_STATUS,+ refusedDespiteSuccess,+ refusedWriteResult,+ rereadAfterLanding,+ type WriteOutcome,+ weightierOutcome,+ writeOutcomeFields,+ writeOutcomeLine,+ writeOutcomeOf,+ writeOutcomeOutputShape,+} from './write-outcome.ts';const DESCRIPTION = ['Create/replace exactly one `document`, `folder`, `template`, `skill`, or `asset`; use `documents` for an ordered batch. Requires the Hocuspocus server.',@@ -97,7 +114,7 @@ const DESCRIPTION = ['`skill: {name, description, body, scope?}` writes agent guidance; lowercase letters/digits/hyphens name is identity, description is when to use it. New skills use the default skill home; existing ones keep their real folder. Use install for editors.','`asset: {path, content|source}` uploads binary image/file: base64 content or local source path. `documents` takes document specs and reports each result.','Optional summary: one-line outcome ≤80 chars, persisted to git history; avoid secrets or PII. Batches need per-entry summary; top-level is ignored.',- 'Read response warnings: content-divergence/disk-edit-reconciled means re-read; mermaid-parse-error means the write landed but fix the fence.',+ 'Follow nextStep: retry|re-read|none. Outcomes merged-first, both-kept, projection-held landed: never retry. mermaid-parse-error: fix the fence.',CANONICAL_COMPONENT_GUIDANCE,].join('\n');@@ -130,9 +147,11 @@ type WriteOneResult =extensionNote?: string;createdByPosition?: 'append' | 'prepend';templateHint?: readonly { name: string; description?: string }[];+ outcome?: WriteOutcome;+ frontmatterNote?: string;raw: WriteApiResult;}- | { docName: string; ok: false; error: string };+ | { docName: string; ok: false; error: string; outcome?: WriteOutcome };export function frontmatterIgnoredNote(position: string,@@ -329,7 +348,11 @@ async function writeOneDoc(...(spec.summary !== undefined ? { summary: spec.summary } : {}),...agentIdentityFields(identity),});- if (!result.ok) {+ const outcome = writeOutcomeOf(result);+ if (result.ok && refusedDespiteSuccess(outcome)) {+ return { docName, ok: false, error: REFUSED_WITHOUT_ERROR_STATUS, outcome };+ }+ if (!result.ok && !landedWithoutSuccess(outcome)) {const offsetBasis =result.type === 'urn:ok:error:invalid-request' && result.contentControlAdmission === true? spec.template !== undefined@@ -346,24 +369,32 @@ async function writeOneDoc(docName,ok: false,error: `${requestFailureText(result)}${offsetBasis}${recovery}`,+ ...(outcome ? { outcome } : {}),};}- if (spec.template !== undefined && hasFrontmatter) {+ const templateFrontmatterHeld =+ spec.template !== undefined && hasFrontmatter && !result.ok && outcome?.outcome !== 'both-kept';+ let entryOutcome = outcome;+ if (spec.template !== undefined && hasFrontmatter && !templateFrontmatterHeld) {const fmResult = await httpPost(url, '/api/frontmatter-patch', {docName,patch: spec.frontmatter,...agentIdentityFields(identity),});- if (!fmResult.ok) {+ const fmOutcome = writeOutcomeOf(fmResult);+ if ((!fmResult.ok && !landedWithoutSuccess(fmOutcome)) || refusedDespiteSuccess(fmOutcome)) {return {docName,ok: false,- error: frontmatterPatchAppliedNothing(fmResult)- ? `document created from template "${spec.template}", but its frontmatter patch was refused, so the document exists without that frontmatter: ${requestFailureText(fmResult)} Apply the frontmatter alone with edit({ document: { path: "${docName}", frontmatter } }); do not repeat the templated write.`- : `document created from template "${spec.template}", but its frontmatter patch failed, and this response does not show whether the frontmatter was applied: ${requestFailureText(fmResult)} Re-read the document before changing it; do not repeat the templated write.`,+ error:+ frontmatterPatchAppliedNothing(fmResult) || fmOutcome?.outcome === 'refused'+ ? `document created from template "${spec.template}"; its body landed, but its frontmatter patch was refused, so the frontmatter was not applied: ${requestFailureText(fmResult)} Re-read the document, then apply the frontmatter alone with edit({ document: { path: "${docName}", frontmatter } }); do not repeat the templated write.`+ : `document created from template "${spec.template}"; its body landed, but its frontmatter patch failed, and this response does not show whether the frontmatter was applied: ${requestFailureText(fmResult)} Re-read the document, then apply only the missing frontmatter with edit({ document: { path: "${docName}", frontmatter } }); do not repeat the templated write.`,+ ...(outcome ? { outcome: rereadAfterLanding(outcome) } : {}),};}+ entryOutcome = weightierOutcome(outcome, fmOutcome);}const extensionNote = extensionIgnoredNote(requestedExt, existingExt, docName);@@ -379,6 +410,12 @@ async function writeOneDoc(...(spec.template !== undefined ? { fromTemplate: spec.template } : {}),...(extensionNote ? { extensionNote } : {}),...(templateHint ? { templateHint } : {}),+ ...(entryOutcome ? { outcome: entryOutcome } : {}),+ ...(templateFrontmatterHeld+ ? {+ frontmatterNote: `The frontmatter you passed with the template was not applied, because the document's save is held. Re-read the document, then apply it with edit({ document: { path: "${docName}", frontmatter } }).`,+ }+ : {}),raw: result,};}@@ -461,17 +498,30 @@ async function handleTemplate(...(summary !== undefined ? { summary } : {}),...agentIdentityFields(deps.identityRef?.current),});+ const outcome = writeOutcomeOf(result);if (!result.ok) {- return textResult(+ return failedWriteResult(errorTextWithDetail(result, 'Any body offset refers to the full submitted template.content.'),- true,+ outcome,);}+ if (refusedDespiteSuccess(outcome)) {+ return refusedWriteResult(`The write of template "${name}"`, outcome);+ }const created = result.created === true;const path = typeof result.path === 'string' ? result.path : undefined;+ const outcomeLine = outcome?.outcome === 'applied' ? null : writeOutcomeLine(outcome);return textPlusStructured(- `${created ? 'Created' : 'Updated'} template "${name}" in ${folder || '(root)'}${path ? ` (${path})` : ''}.`,- { template: { ok: true, path, created } },+ [+ leadFor(+ outcome,+ `${created ? 'Created' : 'Updated'} template "${name}"`,+ `${created ? 'Created' : 'Updated'} template "${name}" in ${folder || '(root)'}${path ? ` (${path})` : ''}.`,+ ),+ ...(outcomeLine ? [outcomeLine] : []),+ ].join('\n'),+ { template: { ok: true, path, created }, ...writeOutcomeFields(outcome) },+ needsAttention(outcome),);}@@ -635,6 +685,10 @@ async function handleSkillWrite(kind?: string;created?: boolean;error?: string;+ outcome?: string;+ saved?: boolean;+ nextStep?: string;+ landedNote?: string;}> = [];let skillMdResult: Awaited<ReturnType<typeof writeSkill>> | null = null;@@ -648,7 +702,9 @@ async function handleSkillWrite(identity,lockDir,});- if (skillMdResult.isError) return skillMdResult;+ const skillMdStructured = (skillMdResult as { structuredContent?: Record<string, unknown> })+ .structuredContent;+ if (skillMdResult.isError && skillMdStructured?.skill === undefined) return skillMdResult;}for (const f of normalizedFiles) {@@ -660,23 +716,47 @@ async function handleSkillWrite(summary,identity,});- const struct = (r as { structuredContent?: { skill?: { file?: Record<string, unknown> } } })- .structuredContent;- if (r.isError) {- fileResults.push({ path: f.path, ok: false, error: r.content[0]?.text ?? 'write failed' });+ const struct = (+ r as {+ structuredContent?: { skill?: { file?: Record<string, unknown> } } & Record<+ string,+ unknown+ >;+ }+ ).structuredContent;+ const fileOutcome = writeOutcomeFields(struct ? writeOutcomeOf(struct) : undefined);+ const file = struct?.skill?.file;+ if (r.isError && file === undefined) {+ fileResults.push({+ path: f.path,+ ok: false,+ error: r.content[0]?.text ?? 'write failed',+ ...fileOutcome,+ });} else {- const file = struct?.skill?.file ?? {};+ const landedNote = landedWithoutSuccess(struct ? writeOutcomeOf(struct) : undefined)+ ? r.content[0]?.text+ : undefined;fileResults.push({path: f.path,ok: true,- ...(typeof file.kind === 'string' ? { kind: file.kind } : {}),- ...(typeof file.created === 'boolean' ? { created: file.created } : {}),+ ...(typeof file?.kind === 'string' ? { kind: file.kind } : {}),+ ...(typeof file?.created === 'boolean' ? { created: file.created } : {}),+ ...fileOutcome,+ ...(landedNote === undefined ? {} : { landedNote }),});}}const fileOk = fileResults.filter((r) => r.ok).length;- const anyFileFailed = fileResults.some((r) => !r.ok);+ const anyFileFailed = fileResults.some(+ (r) =>+ !r.ok ||+ r.outcome === 'refused' ||+ r.outcome === 'both-kept' ||+ r.outcome === 'projection-held',+ );+ const skillMdNeedsAttention = skillMdResult?.isError === true;const baseStructured =((skillMdResult as { structuredContent?: Record<string, unknown> } | null)?.structuredContent as| Record<string, unknown>@@ -685,7 +765,12 @@ async function handleSkillWrite(const { text: _skillMdOnlyText, ...baseWithoutText } = baseStructured;const structured: Record<string, unknown> = {...baseWithoutText,- skill: { ...baseSkill, ...(files.length > 0 ? { files: fileResults } : {}) },+ skill: {+ ...baseSkill,+ ...(files.length > 0+ ? { files: fileResults.map(({ landedNote: _landedNote, ...entry }) => entry) }+ : {}),+ },};const lines: string[] = [];@@ -693,10 +778,18 @@ async function handleSkillWrite(if (files.length > 0) {lines.push(`${fileOk}/${files.length} bundle file(s) written.`);for (const r of fileResults) {- lines.push(r.ok ? ` ${r.path} (${r.kind ?? 'file'})` : ` Failed ${r.path}: ${r.error}`);+ lines.push(+ r.ok+ ? ` ${r.path} (${r.kind ?? 'file'})${r.landedNote ? `: ${r.landedNote}` : ''}`+ : ` Failed ${r.path}: ${r.error}`,+ );}}- return textPlusStructured(lines.filter(Boolean).join('\n'), structured, anyFileFailed);+ return textPlusStructured(+ lines.filter(Boolean).join('\n'),+ structured,+ anyFileFailed || skillMdNeedsAttention,+ );}async function handleBatch(@@ -713,40 +806,59 @@ async function handleBatch(results.push(await writeOneDoc(spec, cwd, contentDir, url, deps));}const docOut = results.map((r) => {- if (!r.ok) return { docName: r.docName, ok: false as const, error: r.error };+ if (!r.ok) {+ return {+ docName: r.docName,+ ok: false as const,+ error: r.error,+ ...writeOutcomeFields(r.outcome),+ };+ }const preview = resolvePreviewUrl(r.docName, { lockDir });const warnings = parseAdvisoryWarnings(r.raw.warnings);- const brokenLinks = parseBrokenLinks(r.raw.brokenLinks);+ const linksChecked = r.outcome?.outcome !== 'projection-held';+ const brokenLinks = linksChecked ? parseBrokenLinks(r.raw.brokenLinks) : undefined;const brokenLinkSuppression = parseBrokenLinkSuppression(r.raw.brokenLinkSuppression);return {docName: r.docName,ok: true as const,position: r.position,+ ...writeOutcomeFields(r.outcome),...(preview ? { previewUrl: preview.url } : {}),...(warnings ? { warnings } : {}),...(r.templateHint ? { templateHint: r.templateHint } : {}),- brokenLinks,+ ...(brokenLinks ? { brokenLinks } : {}),...(brokenLinkSuppression ? { brokenLinkSuppression } : {}),};});const okCount = docOut.filter((d) => d.ok).length;- const allOk = okCount === docOut.length;+ const allOk = results.every((r) => r.ok && !needsAttention(r.outcome));const lines = documents.map((spec, i) => {const r = results[i];- if (!r?.ok) return `Failed ${spec.path}: ${r?.error ?? 'unknown error'}`;+ if (!r?.ok) {+ const outcomeLine = writeOutcomeLine(r?.outcome);+ return `Failed ${spec.path}: ${r?.error ?? 'unknown error'}${outcomeLine ? ` ${outcomeLine}` : ''}`;+ }if (emptyAppendNoOpNote(r.position, spec.content)) {return `No change to ${spec.path} — empty ${r.position}, document unchanged.`;}const d = docOut[i];const baseParts = [- r.createdByPosition- ? createdByPositionNote(r.docName, r.createdByPosition)- : `Wrote ${spec.path} (${r.position}).`,+ r.outcome && landedWithoutSuccess(r.outcome)+ ? landedLead(r.outcome, `Wrote ${spec.path} (${r.position})`)+ : r.createdByPosition+ ? createdByPositionNote(r.docName, r.createdByPosition)+ : `Wrote ${spec.path} (${r.position}).`,];+ if (r.outcome?.outcome === 'projection-held' && typeof r.raw.detail === 'string') {+ baseParts.push(r.raw.detail);+ }+ const entryOutcomeLine = r.outcome?.outcome === 'applied' ? null : writeOutcomeLine(r.outcome);+ if (entryOutcomeLine) baseParts.push(entryOutcomeLine);if (d?.ok && d.warnings) {baseParts.push(...formatAdvisoryBriefs(d.warnings));}- if (d?.ok) {+ if (d?.ok && d.brokenLinks) {const brokenBrief = formatBrokenLinkBrief(d.brokenLinks);if (brokenBrief) baseParts.push(brokenBrief);if (d.brokenLinkSuppression) {@@ -764,7 +876,11 @@ async function handleBatch(const r = results[i];if (!r?.ok) return [];const fmNote = frontmatterIgnoredNote(r.position, spec.content);- const notes = [...(fmNote ? [fmNote] : []), ...(r.extensionNote ? [r.extensionNote] : [])];+ const notes = [+ ...(fmNote ? [fmNote] : []),+ ...(r.frontmatterNote ? [r.frontmatterNote] : []),+ ...(r.extensionNote ? [r.extensionNote] : []),+ ];return notes.map((n) => `${spec.path} — ${n}`);});const text = [`${okCount}/${docOut.length} written.`, ...lines, ...perDocNotes].join('\n');@@ -787,9 +903,10 @@ async function handleSingleDoc(autoOpen: boolean,) {const w = await writeOneDoc(spec, cwd, contentDir, url, deps);- if (!w.ok) return textResult(`Error: ${w.error}`, true);+ if (!w.ok) return failedWriteResult(`Error: ${w.error}`, w.outcome);const result = w.raw;+ const landedOnly = w.outcome !== undefined && landedWithoutSuccess(w.outcome);const preview = resolvePreviewUrl(w.docName, { lockDir });const systemSubscriberCount =typeof result.systemSubscriberCount === 'number' ? result.systemSubscriberCount : undefined;@@ -806,15 +923,21 @@ async function handleSingleDoc(const noOpNote = emptyAppendNoOpNote(w.position, spec.content);const lines: string[] = [- w.createdByPosition- ? createdByPositionNote(w.docName, w.createdByPosition)- : (noOpNote ??- (w.fromTemplate !== undefined- ? `Written successfully (instantiated from template "${w.fromTemplate}").`- : `Written successfully (${w.position}).`)),+ w.outcome && landedOnly+ ? landedLead(w.outcome, `Written (${w.position})`)+ : w.createdByPosition+ ? createdByPositionNote(w.docName, w.createdByPosition)+ : (noOpNote ??+ (w.fromTemplate !== undefined+ ? `Written successfully (instantiated from template "${w.fromTemplate}").`+ : `Written successfully (${w.position}).`)),];+ if (w.outcome?.outcome === 'projection-held' && typeof result.detail === 'string') {+ lines.push(result.detail);+ }const fmNote = frontmatterIgnoredNote(w.position, spec.content);if (fmNote) lines.push(fmNote);+ if (w.frontmatterNote) lines.push(w.frontmatterNote);if (w.extensionNote) lines.push(w.extensionNote);if (noPreviewAnywhere && !preview) lines.push(startUiTextHint());if (summaryHint) lines.push(summaryHint);@@ -829,6 +952,8 @@ async function handleSingleDoc(lines.push(...formatBrokenLinkLines(brokenLinks));if (brokenLinkSuppression) lines.push(formatBrokenLinkSuppressionLine(brokenLinkSuppression));if (w.templateHint) lines.push(formatTemplateHintLine(w.templateHint));+ const outcomeLine = w.outcome?.outcome === 'applied' ? null : writeOutcomeLine(w.outcome);+ if (outcomeLine) lines.push(outcomeLine);const text = lines.join('\n');const document: Record<string, unknown> = {@@ -840,7 +965,14 @@ async function handleSingleDoc(if (advisoryWarnings) document.warnings = advisoryWarnings;if (w.templateHint) document.templateHint = w.templateHint;const warning = noPreviewAnywhere ? buildPreviewAttachWarning(preview, autoOpen) : undefined;- return textPlusStructured(text, nestDocResult(preview, warning, document));+ return textPlusStructured(+ text,+ {+ ...nestDocResult(preview, warning, w.outcome?.outcome === 'projection-held' ? {} : document),+ ...writeOutcomeFields(w.outcome),+ },+ needsAttention(w.outcome),+ );}export function register(server: ServerInstance, deps: WriteDeps): void {@@ -988,6 +1120,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),},outputSchema: outputSchemaWithText({+ ...writeOutcomeOutputShape,document: z.object({hints: looseObjectArray.optional().describe('Server-provided write hints, when any.'),@@ -995,7 +1128,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {}).optional().describe(- 'Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet.',+ 'Single-document write result. Present on every saved single-doc write (absent when the outcome is projection-held, whose links were not checked) — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet.',),folder: z.object({@@ -1064,7 +1197,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {documents: looseObjectArray.optional().describe(- 'Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy).',+ 'Batch write: per-doc result `{ docName, ok, outcome?, saved?, nextStep?, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`, each entry with its own outcome fields (the top-level ones are absent). `brokenLinks` (possibly `[]`) is present on each successful entry whose outcome is not projection-held (the links of a held entry were not checked, and its text carries the server detail instead), same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy).',),previewUrl: previewUrlOutputField.optional(),previewUrlSource: previewUrlSourceField,diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex ffe1a6fa3..446dff2ca 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -86,7 +86,9 @@ import {OK_STORE_REFUSED,type StoreFailure,type StoreFailureRemoval,+ type StoreIntakeMerge,type StorePublishOutcome,+ writtenThroughOf,} from './document-durability-state.ts';import { refuseStaleExternalWrite } from './external-change.ts';import { contentHash, registerWrite } from './file-watcher.ts';@@ -276,7 +278,7 @@ interface StoreRunControl {}type StoreIntakeResult =- | { readonly kind: 'taken-in' }+ | { readonly kind: 'taken-in'; readonly merge?: StoreIntakeMerge }| { readonly kind: 'conflict' }| { readonly kind: 'failed'; readonly error: unknown };@@ -1445,6 +1447,13 @@ export function createPersistenceExtension(options: PersistenceOptions): Persist}}+ function holdMeetsFileWithNoAgreedVersion(documentName: string): boolean {+ return (+ durabilityState.getReconciledBase(documentName) === undefined &&+ (docsWithFileObservedOnDisk.has(documentName) || frozenPathOccupied(documentName))+ );+ }+function frozenRemovalOf(document: Y.Doc,documentName: string,@@ -1486,13 +1495,9 @@ export function createPersistenceExtension(options: PersistenceOptions): PersistdocumentName: string,reason: StorePendingReason,cause?: unknown,+ noBase = holdMeetsFileWithNoAgreedVersion(documentName),): never {- const held = new StoreHeldPendingError(- documentName,- reason,- durabilityState.getReconciledBase(documentName) === undefined,- cause,- );+ const held = new StoreHeldPendingError(documentName, reason, noBase, cause);incrementStoreDiskCompare(reason);compareLog.warn({ documentName, reason, code: held.causeCode, err: cause },@@ -2096,6 +2101,13 @@ export function createPersistenceExtension(options: PersistenceOptions): Persistconst intake = await ingest(documentName, canonicalPath, compared.text);switch (intake.kind) {case 'taken-in':+ if (agentTriggeredStore && intake.merge !== undefined) {+ durabilityState.recordStoreIntake(+ documentName,+ intake.merge,+ writtenThroughOf(document),+ );+ }persistenceDeferCounts.delete(documentName);control.rerun = 'disk-changed';return;@@ -2108,6 +2120,7 @@ export function createPersistenceExtension(options: PersistenceOptions): Persist? 'pending-intake-failed-no-base': 'pending-intake-failed',intake.error,+ currentBase === undefined,);default:return assertNeverStoreIntake(intake);diff --git a/packages/server/src/project-skill-router-contract.test.ts b/packages/server/src/project-skill-router-contract.test.tsindex 9d837c581..84a20daab 100644--- a/packages/server/src/project-skill-router-contract.test.ts+++ b/packages/server/src/project-skill-router-contract.test.ts@@ -171,12 +171,13 @@ const routingRules = [required: ['write({ template })', 'Folder frontmatter does not cascade values into docs'],},{- name: 'tracked conflict recovery in the app',- anchor: 'For a conflict refusal,',+ name: 'write outcomes, with unchangeable refusals reported to the user',+ anchor: 'For every write result,',required: [- "follow the tool's recovery instructions",+ 'read `outcome` and follow `nextStep`','`references/conflict-resolution.md`',- 'ask the user to resolve tracked conflicts in the app',+ 'never repeat a write that landed',+ 'nothing you send changes it: tell the user which file',],},{diff --git a/packages/server/src/server-factory.conflict-authority.test.ts b/packages/server/src/server-factory.conflict-authority.test.tsindex cbe5cf33a..2dd20e55d 100644--- a/packages/server/src/server-factory.conflict-authority.test.ts+++ b/packages/server/src/server-factory.conflict-authority.test.ts@@ -90,19 +90,41 @@ async function listConflictFiles(port: number): Promise<string[]> {return data.conflicts.map((c) => c.file);}-async function writeDocProbe(port: number, docName: string, markdown: string): Promise<number> {+interface ProbeAnswer {+ status: number;+ outcome: unknown;+}++async function writeDocProbe(+ port: number,+ docName: string,+ markdown: string,+): Promise<ProbeAnswer> {const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ docName, markdown, position: 'replace', agentId: 'probe' }),});- return res.status;+ const body = (await res.json()) as { outcome?: unknown };+ return { status: res.status, outcome: body.outcome };}-async function writeProbe(port: number, markdown: string): Promise<number> {+async function writeProbe(port: number, markdown: string): Promise<ProbeAnswer> {return writeDocProbe(port, DOC_NAME, markdown);}+function expectAdmitted(answer: ProbeAnswer): void {+ expect(answer).toEqual(+ answer.status === 503+ ? { status: 503, outcome: 'projection-held' }+ : { status: 200, outcome: 'applied' },+ );+}++function expectRefusedByConflict(answer: ProbeAnswer): void {+ expect(answer).toEqual({ status: 409, outcome: 'refused' });+}+async function resolveConflictOverHttp(port: number,file: string,@@ -243,7 +265,7 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the20_000,'the seeded merge-native entry to be listed',);- expect(await writeProbe(held.port, '# blocked\n')).toBe(409);+ expectRefusedByConflict(await writeProbe(held.port, '# blocked\n'));const opts = { cwd: tmpDir };await checkoutOurs(held.port, replacement);@@ -266,7 +288,8 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the'the conflict ledger to empty after the external resolve',);- expect(await writeProbe(held.port, '# probe\n')).toBe(200);+ expectAdmitted(await writeProbe(held.port, '# probe\n'));+ expect(await held.readSource()).toContain('# probe');} finally {await held.release();await held.destroy();@@ -283,7 +306,7 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the20_000,'the seeded merge-native entry to be listed',);- expect(await writeProbe(held.port, '# blocked\n')).toBe(409);+ expectRefusedByConflict(await writeProbe(held.port, '# blocked\n'));writeFileSync(resolve(tmpDir, DOC_FILE), 'line1\nLOCAL\nline3\n', 'utf-8');@@ -304,7 +327,7 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the);expect(stillUnmerged.stdout).toContain(DOC_FILE);expect(await listConflictFiles(held.port)).toContain(DOC_FILE);- expect(await writeProbe(held.port, '# still blocked\n')).toBe(409);+ expectRefusedByConflict(await writeProbe(held.port, '# still blocked\n'));await execFileAsync('git', ['add', '--', DOC_FILE], opts);await execFileAsync('git', ['commit', '--no-edit'], opts);@@ -316,7 +339,8 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the);expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(false);- expect(await writeProbe(held.port, '# probe\n')).toBe(200);+ expectAdmitted(await writeProbe(held.port, '# probe\n'));+ expect(await held.readSource()).toContain('# probe');} finally {await held.release();await held.destroy();@@ -354,7 +378,8 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the);expect(existsSync(resolve(tmpDir, '.git', 'MERGE_HEAD'))).toBe(true);- expect(await writeProbe(held.port, '# probe\n')).toBe(200);+ expectAdmitted(await writeProbe(held.port, '# probe\n'));+ expect(await held.readSource()).toContain('# probe');} finally {await held.release();await held.destroy();@@ -480,7 +505,7 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the'the initial file-watcher scan to index the scratch doc',);- expect(await writeDocProbe(held.port, SCRATCH_DOC, `# ${CONTROL_MARKER}\n`)).toBe(200);+ expectAdmitted(await writeDocProbe(held.port, SCRATCH_DOC, `# ${CONTROL_MARKER}\n`));await pollUntil(() => readScratch().includes(CONTROL_MARKER),30_000,diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex a260ab35e..de3021dac 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -151,6 +151,7 @@ import { DocNoticeLedger, type NoticeFile } from './doc-notices.ts';import {DocumentDurabilityState,type StaleExternalWriteConflict,+ type StoreIntakeMerge,type WrittenThrough,writtenThroughOf,} from './document-durability-state.ts';@@ -2314,6 +2315,9 @@ export function createServer(options: ServerOptions): ServerInstance {}switch (outcome.kind) {case 'applied':+ return outcome.merge === undefined+ ? { kind: 'taken-in' }+ : { kind: 'taken-in', merge: outcome.merge };case 'nothing-to-take':return { kind: 'taken-in' };case 'conflict':@@ -3783,7 +3787,9 @@ export function createServer(options: ServerOptions): ServerInstance {`[reconcile] ${docName} base=${baseToken} reason=no-base result=${result} ours=${oursH} theirs=${theirsH} rescue=${rescue}`,);await recordUpsertAfterIntake(docName, theirs);- return { kind: 'applied' };+ return liveOnlyContentAtRisk+ ? { kind: 'applied', merge: 'disk-replaced' }+ : { kind: 'applied' };}return { kind: 'failed', error: applyError };};@@ -3800,7 +3806,7 @@ export function createServer(options: ServerOptions): ServerInstance {};type DiskIntakeOutcome =- | { readonly kind: 'applied' }+ | { readonly kind: 'applied'; readonly merge?: StoreIntakeMerge }| { readonly kind: 'nothing-to-take' }| { readonly kind: 'conflict' }| { readonly kind: 'failed'; readonly error: unknown };@@ -3930,7 +3936,7 @@ export function createServer(options: ServerOptions): ServerInstance {incrementReconcile();conflicts.dissolveReconcile(docName);await recordUpsertAfterIntake(docName, theirs);- return { kind: 'applied' };+ return { kind: 'applied', merge: 'clean' };case 'merged':try {@@ -3948,7 +3954,7 @@ export function createServer(options: ServerOptions): ServerInstance {incrementReconcile();conflicts.dissolveReconcile(docName);await recordUpsertAfterIntake(docName, theirs);- return { kind: 'applied' };+ return { kind: 'applied', merge: 'merged' };case 'both-kept': {try {@@ -3974,7 +3980,7 @@ export function createServer(options: ServerOptions): ServerInstance {reportReconcileBothKept(docName, result.kept, 'watcher');conflicts.dissolveReconcile(docName);await recordUpsertAfterIntake(docName, theirs);- return { kind: 'applied' };+ return { kind: 'applied', merge: 'both-kept' };}case 'refused': {@@ -3990,7 +3996,7 @@ export function createServer(options: ServerOptions): ServerInstance {reportReconcileKeptLive(docName, result.reason, 'watcher');conflicts.dissolveReconcile(docName);await recordUpsertAfterIntake(docName, theirs);- return { kind: 'applied' };+ return { kind: 'applied', merge: 'kept-live' };}}incrementConflict();@@ -4196,6 +4202,7 @@ export function createServer(options: ServerOptions): ServerInstance {bufferedRemovalScopes.delete(event);durabilityState.beginRenameCarry(oldDocName);let carriedThrough: WrittenThrough | null = null;+ let retiredResident = false;try {const document = removal.document;const residentBeforeRename = removal.residentCurrent() && document ? document : null;@@ -4266,6 +4273,7 @@ export function createServer(options: ServerOptions): ServerInstance {if (carried) carriedThrough = textBeforeRename;}const retired = removal.residentCurrent() && document ? document : lateResident;+ retiredResident = Boolean(retired);if (retired) {const closedConnections = retired.getConnectionsCount();/* WARN: the `delete` branch above and `captureAndCloseDocuments` pair their@@ -4307,6 +4315,7 @@ export function createServer(options: ServerOptions): ServerInstance {scheduleIndexRegenerationAfterRemoval(oldDocName);} finally {durabilityState.settleRenameCarry(oldDocName, carriedThrough);+ if (!retiredResident) durabilityState.endRenameCarry(oldDocName);removal.dispose();}break;