Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-7872 Prevent silent concurrent replace loss (#4430)

serafin-garcia87db543b196e
diff --git a/.changeset/concurrent-replace-honest-failure.md b/.changeset/concurrent-replace-honest-failure.md
new file mode 100644
index 000000000..7a960dd7c
--- /dev/null
+++ b/.changeset/concurrent-replace-honest-failure.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Refuse a whole-document replace, writing nothing, when an editor or a different agent just changed the document, including when the replace sends no `agentId`. Wait a few seconds and retry, or write with position `append` or `prepend`, which are not refused.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 4c3f023ba..7af512ce0 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -27,7 +27,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `palette` | Markdown-native authoring forms, themed `html preview` embed starters, and theme tokens. Pass `components` for the canonical components' full JSX prop schemas |
| `preview_url` | Resolve the browser-reachable preview URL. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
| `share_link` | Build a GitHub-substrate share URL for a doc or folder to send to a teammate (`kind` disambiguates; `path: ""` with `kind: "folder"` shares the content root). Responses carry a `freshness` verdict — `current`, `stale` (unpushed changes), or `absent` (never pushed), omitted when the probe can't run — and prepend a matching warning to relay with the link. Read-only against `.git/`; never publishes |
-| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
+| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) |
| `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |
| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything |
@@ -92,6 +92,8 @@ A write whose document path cannot be resolved inside the content directory retu
A write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. Retry only after the filesystem fault is repaired.
+A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so `conflicts()` and `resolve_conflict` do not apply to it. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). `POST /api/agent-write-batch` keeps its `200` success envelope; each refused entry carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which are never refused. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.
+
### Resolving a conflict
1. `conflicts({ kind: "list" })` returns every tracked conflict as `{ file, detectedAt, conflict, reason?, conflictKind?, docName }`. Call it to detect conflicts without waiting for a 409.
diff --git a/packages/app/tests/integration/agent-write-batch.test.ts b/packages/app/tests/integration/agent-write-batch.test.ts
index 45e7f4b78..66a9343ca 100644
--- a/packages/app/tests/integration/agent-write-batch.test.ts
+++ b/packages/app/tests/integration/agent-write-batch.test.ts
@@ -47,6 +47,12 @@ async function postBatch(
});
}
+async function readConcurrentOverwriteRefusedCount(port: number): Promise<number> {
+ const res = await fetch(`http://127.0.0.1:${port}/api/metrics/reconciliation`);
+ const body = (await res.json()) as { concurrentOverwriteRefused?: number };
+ return body.concurrentOverwriteRefused ?? -1;
+}
+
function listWipRefs(contentDir: string): string[] {
const shadowDir = resolveShadowDir(contentDir);
const raw = execFileSync('git', ['for-each-ref', '--format=%(refname)', 'refs/wip/'], {
@@ -153,6 +159,47 @@ describe('agent-write-batch', () => {
);
}, 30_000);
+ test('a concurrent replace fails only its batch entry', async () => {
+ server = await createTestServer();
+ const first = await fetch(`${server.baseUrl}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: 'batch-race/contended',
+ markdown: '# First writer\n',
+ position: 'replace',
+ agentId: 'agent-a',
+ }),
+ });
+ expect(first.status).toBe(200);
+ const refusalsBefore = await readConcurrentOverwriteRefusedCount(server.port);
+
+ const response = await postBatch(server.port, {
+ agentId: 'agent-b',
+ docs: [
+ {
+ docName: 'batch-race/contended',
+ markdown: '# Second writer\n',
+ position: 'replace',
+ },
+ { docName: 'batch-race/quiet', markdown: '# Quiet\n', position: 'replace' },
+ ],
+ });
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as BatchResponseBody;
+ expect(body.written).toBe(1);
+ expect(body.failed).toBe(1);
+ expect(body.results[0].error).toEqual({
+ type: 'urn:ok:error:concurrent-overwrite-refused',
+ title: 'Concurrent overwrite refused.',
+ detail:
+ 'Another writer changed this document recently. Wait a few seconds and retry. A write with position append or prepend is not refused.',
+ retryAfterSeconds: 3,
+ });
+ expect(body.results[1].status).toBe('written');
+ expect(await readConcurrentOverwriteRefusedCount(server.port)).toBe(refusalsBefore + 1);
+ });
+
test('broken-link validation admits sibling batch docs and reports dead links', async () => {
server = await createTestServer();
diff --git a/packages/app/tests/integration/concurrent-replace-refusal.test.ts b/packages/app/tests/integration/concurrent-replace-refusal.test.ts
new file mode 100644
index 000000000..ffb8a8455
--- /dev/null
+++ b/packages/app/tests/integration/concurrent-replace-refusal.test.ts
@@ -0,0 +1,421 @@
+import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import {
+ createTestClient,
+ createTestServer,
+ pollUntil,
+ type TestClient,
+ type TestServer,
+} from './test-harness';
+
+interface WriteBody {
+ docName: string;
+ markdown: string;
+ position: 'append' | 'prepend' | 'replace';
+ agentId?: string;
+}
+
+async function setupDoc(server: TestServer, docName: string): Promise<void> {
+ const response = await fetch(`${server.baseUrl}/api/create-page`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path: `${docName}.md` }),
+ });
+ expect(response.status).toBe(200);
+}
+
+function write(server: TestServer, body: WriteBody): Promise<Response> {
+ return fetch(`${server.baseUrl}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+function addWysiwygParagraph(client: TestClient, text: string): void {
+ const paragraph = new Y.XmlElement('paragraph');
+ const leaf = new Y.XmlText();
+ leaf.insert(0, text);
+ paragraph.insert(0, [leaf]);
+ client.fragment.push([paragraph]);
+}
+
+async function expectHumanWriteRefused(
+ server: TestServer,
+ docName: string,
+ edit: (client: TestClient) => void,
+ agentId: string | undefined = 'agent-after-human',
+): Promise<void> {
+ await setupDoc(server, docName);
+ const client = await createTestClient(server.port, docName);
+ try {
+ edit(client);
+ await pollUntil(() => {
+ const document = server.instance.hocuspocus.documents.get(docName);
+ return document?.getText('source').toString().includes('Human edit') ?? false;
+ });
+ const before = server.instance.hocuspocus.documents.get(docName)?.getText('source').toString();
+ const response = await write(server, {
+ docName,
+ markdown: '# Agent replacement\n',
+ position: 'replace',
+ agentId,
+ });
+ expect(response.status).toBe(409);
+ expect(server.instance.hocuspocus.documents.get(docName)?.getText('source').toString()).toBe(
+ before,
+ );
+ } finally {
+ await client.cleanup();
+ }
+}
+
+describe('concurrent whole-document replace refusal', () => {
+ test('two identified agents cannot replace the same document concurrently', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `agent-race-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ const [first, second] = await Promise.all([
+ write(server, {
+ docName,
+ markdown: '# From A\n\nAlpha.\n',
+ position: 'replace',
+ agentId: 'agent-a',
+ }),
+ write(server, {
+ docName,
+ markdown: '# From B\n\nBeta.\n',
+ position: 'replace',
+ agentId: 'agent-b',
+ }),
+ ]);
+ expect([first.status, second.status].sort()).toEqual([200, 409]);
+ const refused = first.status === 409 ? first : second;
+ const problem = (await refused.json()) as Record<string, unknown>;
+ expect(problem.type).toBe('urn:ok:error:concurrent-overwrite-refused');
+ expect(problem.title).toBe('Concurrent overwrite refused.');
+ expect(problem.status).toBe(409);
+ expect(problem.file).toBe(`${docName}.md`);
+ expect(problem.retryAfterSeconds).toBe(3);
+ expect(refused.headers.get('Retry-After')).toBe('3');
+ expect(Object.keys(problem).sort()).toEqual([
+ 'detail',
+ 'file',
+ 'instance',
+ 'retryAfterSeconds',
+ 'status',
+ 'title',
+ 'type',
+ ]);
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('an identified agent can replace its own recent write', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `same-agent-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# First\n',
+ position: 'replace',
+ agentId: 'agent-solo',
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# Second\n',
+ position: 'replace',
+ agentId: 'agent-solo',
+ })
+ ).status,
+ ).toBe(200);
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('an identified patch arms the refusal against a different writer', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `patch-seed-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# Patch target\n\nOriginal body.\n',
+ position: 'replace',
+ })
+ ).status,
+ ).toBe(200);
+
+ const patch = await fetch(`${server.baseUrl}/api/agent-patch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName,
+ find: 'Original body.',
+ replace: 'Patched body.',
+ agentId: 'patch-writer',
+ }),
+ });
+ expect(patch.status).toBe(200);
+
+ const before = server.instance.hocuspocus.documents
+ .get(docName)
+ ?.getText('source')
+ .toString();
+ const response = await write(server, {
+ docName,
+ markdown: '# Peer replacement\n\nReplaced.\n',
+ position: 'replace',
+ agentId: 'peer-writer',
+ });
+ expect(response.status).toBe(409);
+ expect(((await response.json()) as Record<string, unknown>).type).toBe(
+ 'urn:ok:error:concurrent-overwrite-refused',
+ );
+ expect(server.instance.hocuspocus.documents.get(docName)?.getText('source').toString()).toBe(
+ before,
+ );
+ expect(before).toContain('Patched body.');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('a write that supplies no agentId does not arm the refusal against an identified agent', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `unattributed-seed-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# Unattributed seed\n\nSeeded.\n',
+ position: 'replace',
+ })
+ ).status,
+ ).toBe(200);
+ const response = await write(server, {
+ docName,
+ markdown: '# Identified replacement\n\nReplaced.\n',
+ position: 'replace',
+ agentId: 'agent-after-unattributed',
+ });
+ expect(response.status).toBe(200);
+ expect(
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),
+ ).toContain('Identified replacement');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('a write that supplies no agentId is refused against a recent identified agent', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `identified-seed-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# Identified seed\n\nSeeded.\n',
+ position: 'replace',
+ agentId: 'agent-before-unattributed',
+ })
+ ).status,
+ ).toBe(200);
+ const response = await write(server, {
+ docName,
+ markdown: '# Unattributed replacement\n\nReplaced.\n',
+ position: 'replace',
+ });
+ expect(response.status).toBe(409);
+ expect(
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),
+ ).toContain('Identified seed');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('two writes that both supply no agentId are not refused against each other', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `unattributed-pair-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ expect(
+ (
+ await write(server, {
+ docName,
+ markdown: '# First unattributed\n\nAlpha.\n',
+ position: 'replace',
+ })
+ ).status,
+ ).toBe(200);
+ const second = await write(server, {
+ docName,
+ markdown: '# Second unattributed\n\nBeta.\n',
+ position: 'replace',
+ });
+ expect(second.status).toBe(200);
+ expect(
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),
+ ).toContain('Second unattributed');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('an anonymous lint fix does not arm the refusal against an anonymous replace', async () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-anonymous-lint-')));
+ mkdirSync(join(root, '.ok', 'local', 'principal.json'), { recursive: true });
+ writeFileSync(
+ join(root, '.ok', 'config.yml'),
+ 'contentRules:\n markdownlint:\n enabled: true\n',
+ 'utf-8',
+ );
+ const docName = `anonymous-lint-${crypto.randomUUID()}`;
+ writeFileSync(join(root, `${docName}.md`), '# Doc\n\n\tindented with a hard tab\n', 'utf-8');
+ const server = await createTestServer({
+ contentDir: root,
+ projectDir: root,
+ debounce: 50,
+ maxDebounce: 200,
+ });
+ try {
+ const fix = await fetch(`${server.baseUrl}/api/lint/fix`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName }),
+ });
+ expect(fix.status).toBe(200);
+ expect(((await fix.json()) as { fixedCount: number }).fixedCount).toBeGreaterThanOrEqual(1);
+ expect(
+ server.instance.sessionManager.getLiveSession(docName, 'principal-anonymous'),
+ ).toBeDefined();
+
+ const response = await write(server, {
+ docName,
+ markdown: '# Anonymous replacement\n\nReplaced.\n',
+ position: 'replace',
+ });
+ expect(response.status).toBe(200);
+ expect(
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),
+ ).toContain('Anonymous replacement');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('an identified lint fix arms the refusal against an unattributed replace', async () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-identified-lint-')));
+ mkdirSync(join(root, '.ok'), { recursive: true });
+ writeFileSync(
+ join(root, '.ok', 'config.yml'),
+ 'contentRules:\n markdownlint:\n enabled: true\n',
+ 'utf-8',
+ );
+ const docName = `identified-lint-${crypto.randomUUID()}`;
+ writeFileSync(join(root, `${docName}.md`), '# Doc\n\n\tindented with a hard tab\n', 'utf-8');
+ const server = await createTestServer({
+ contentDir: root,
+ projectDir: root,
+ debounce: 50,
+ maxDebounce: 200,
+ });
+ try {
+ const fix = await fetch(`${server.baseUrl}/api/lint/fix`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, agentId: 'lint-writer' }),
+ });
+ expect(fix.status).toBe(200);
+ expect(((await fix.json()) as { fixedCount: number }).fixedCount).toBeGreaterThanOrEqual(1);
+ expect(
+ server.instance.sessionManager.getLiveSession(docName, 'agent-lint-writer'),
+ ).toBeDefined();
+
+ const response = await write(server, {
+ docName,
+ markdown: '# Identified lint replacement\n\nReplaced.\n',
+ position: 'replace',
+ });
+ expect(response.status).toBe(409);
+ expect(((await response.json()) as Record<string, unknown>).type).toBe(
+ 'urn:ok:error:concurrent-overwrite-refused',
+ );
+ expect(
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString(),
+ ).not.toContain('Identified lint replacement');
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('a connected client that made no edit does not arm the refusal', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ const docName = `idle-client-${crypto.randomUUID()}`;
+ await setupDoc(server, docName);
+ const client = await createTestClient(server.port, docName);
+ try {
+ const response = await write(server, {
+ docName,
+ markdown: '# Agent seed\n',
+ position: 'replace',
+ agentId: 'agent-after-idle-connect',
+ });
+ expect(response.status).toBe(200);
+ } finally {
+ await client.cleanup();
+ }
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('recent source and rich-text edits are protected', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ await expectHumanWriteRefused(server, `source-human-${crypto.randomUUID()}`, (client) =>
+ client.ytext.insert(client.ytext.length, '\nHuman edit in source.\n'),
+ );
+ await expectHumanWriteRefused(server, `wysiwyg-human-${crypto.randomUUID()}`, (client) =>
+ addWysiwygParagraph(client, 'Human edit in rich text.'),
+ );
+ } finally {
+ await server.cleanup();
+ }
+ });
+
+ test('a write that supplies no agentId is still refused by a recent editor change', async () => {
+ const server = await createTestServer({ debounce: 50, maxDebounce: 200 });
+ try {
+ await expectHumanWriteRefused(
+ server,
+ `source-human-unattributed-${crypto.randomUUID()}`,
+ (client) => client.ytext.insert(client.ytext.length, '\nHuman edit in source.\n'),
+ undefined,
+ );
+ } finally {
+ await server.cleanup();
+ }
+ });
+});
diff --git a/packages/app/tests/integration/conflict-authority-reconcile.test.ts b/packages/app/tests/integration/conflict-authority-reconcile.test.ts
index 86dfb4348..616c6145b 100644
--- a/packages/app/tests/integration/conflict-authority-reconcile.test.ts
+++ b/packages/app/tests/integration/conflict-authority-reconcile.test.ts
@@ -1,6 +1,7 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { CONCURRENT_REPLACE_WINDOW_MS } from '@inkeep/open-knowledge-server';
import { afterEach, describe, expect, test } from 'vitest';
import {
createSyncWiredTestServer,
@@ -165,7 +166,12 @@ async function assertReconcileConflictIsResolvable(
`the conflict entry for ${file} to clear`,
);
- expect(await writeProbe(server.port, docName, '# after\n')).toBe(200);
+ await pollUntil(
+ async () => (await writeProbe(server.port, docName, '# after\n')) === 200,
+ CONCURRENT_REPLACE_WINDOW_MS * 2,
+ 100,
+ `the post-resolution write for ${file} to clear its overlap window`,
+ );
}
describe('PRD-7947: a reconcile-born conflict is tracked, inspectable and resolvable', () => {
diff --git a/packages/app/tests/integration/doc-edge-blank-runs.test.ts b/packages/app/tests/integration/doc-edge-blank-runs.test.ts
index 2969502ed..e8b4429f8 100644
--- a/packages/app/tests/integration/doc-edge-blank-runs.test.ts
+++ b/packages/app/tests/integration/doc-edge-blank-runs.test.ts
@@ -1,4 +1,5 @@
import { setTimeout as wait } from 'node:timers/promises';
+import { CONCURRENT_REPLACE_WINDOW_MS } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
@@ -200,7 +201,7 @@ describe('doc-edge blank runs on the CRDT path', () => {
await mergeSeam(1, 'Above.\n\n\n\nBelow.!\n', 'Above.\n\n\n\nBelow.!\n');
});
- test('an external write that carries a trailing run lands it in every fragment', async () => {
+ test('an external write that carries a trailing run survives an agent replace after the guard window', async () => {
const clients = await seedDocument('Alpha.\n\nOmega.\n');
try {
const a = clients[0];
@@ -210,7 +211,19 @@ describe('doc-edge blank runs on the CRDT path', () => {
await settle(() => a.ytext.toString() === 'Alpha.\n\nOmega.\n\n\n', 4000);
const expected = 'Alpha edited.\n\nOmega.\n\n\n';
- await agentWriteMd(server.port, expected, { docName: a.docName, position: 'replace' });
+ await pollUntil(
+ () =>
+ agentWriteMd(server.port, expected, { docName: a.docName, position: 'replace' }).then(
+ () => true,
+ (err: Error & { status?: number }) => {
+ if (err.status === 409) return false;
+ throw err;
+ },
+ ),
+ CONCURRENT_REPLACE_WINDOW_MS * 2,
+ 100,
+ `the replace of ${a.docName} to clear the concurrent-overwrite guard window`,
+ );
await settle(() => clients.every((c) => c.ytext.toString() === expected), 6000);
await expectEverywhereExactly(clients, expected, 2, 8000);
diff --git a/packages/app/tests/meta/concurrent-overwrite-refusal-predicate.test.ts b/packages/app/tests/meta/concurrent-overwrite-refusal-predicate.test.ts
new file mode 100644
index 000000000..d0a6a0556
--- /dev/null
+++ b/packages/app/tests/meta/concurrent-overwrite-refusal-predicate.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import { isConcurrentOverwriteRefusal } from '../stress/_helpers/fixtures.ts';
+
+function problemError(status: number, type?: string): Error {
+ const err: Error & { status?: number; type?: string } = new Error(
+ `agent-write-md failed: ${status}`,
+ );
+ err.status = status;
+ if (type !== undefined) err.type = type;
+ return err;
+}
+
+describe('isConcurrentOverwriteRefusal', () => {
+ it('retries a 409 carrying the concurrent-overwrite-refused problem type', () => {
+ expect(
+ isConcurrentOverwriteRefusal(problemError(409, 'urn:ok:error:concurrent-overwrite-refused')),
+ ).toBe(true);
+ });
+
+ it('refuses to retry a 409 carrying the doc-in-conflict problem type', () => {
+ expect(isConcurrentOverwriteRefusal(problemError(409, 'urn:ok:error:doc-in-conflict'))).toBe(
+ false,
+ );
+ });
+
+ it('refuses to retry a 409 whose problem type never reached the error', () => {
+ expect(isConcurrentOverwriteRefusal(problemError(409))).toBe(false);
+ });
+
+ it('refuses to retry a non-409 carrying the refusal problem type', () => {
+ expect(
+ isConcurrentOverwriteRefusal(problemError(500, 'urn:ok:error:concurrent-overwrite-refused')),
+ ).toBe(false);
+ });
+
+ it('refuses to retry a plain object that is not an Error', () => {
+ expect(
+ isConcurrentOverwriteRefusal({
+ status: 409,
+ type: 'urn:ok:error:concurrent-overwrite-refused',
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.ts
index fd7e35a5f..570475db1 100644
--- a/packages/app/tests/stress/_helpers/fixtures.ts
+++ b/packages/app/tests/stress/_helpers/fixtures.ts
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import type { ProblemType } from '@inkeep/open-knowledge-core';
import { test as base } from '@playwright/test';
import { resetContentToFixtureBaseline } from './content-reset.ts';
import {
@@ -17,6 +18,34 @@ import {
} from './server-process.ts';
import { removeAllDuringTeardown } from './teardown-fs.ts';
+interface ProblemError extends Error {
+ status?: number;
+ type?: string;
+}
+
+const CONCURRENT_OVERWRITE_REFUSED_TYPE: ProblemType = 'urn:ok:error:concurrent-overwrite-refused';
+
+export function isConcurrentOverwriteRefusal(error: unknown): boolean {
+ if (!(error instanceof Error)) return false;
+ const { status, type } = error as ProblemError;
+ return status === 409 && type === CONCURRENT_OVERWRITE_REFUSED_TYPE;
+}
+
+async function problemError(res: Response, message: string): Promise<ProblemError> {
+ let body: { type?: unknown } | null = null;
+ let parseFailure: unknown;
+ try {
+ body = (await res.json()) as { type?: unknown };
+ } catch (error) {
+ parseFailure = error;
+ }
+ const err: ProblemError =
+ parseFailure === undefined ? new Error(message) : new Error(message, { cause: parseFailure });
+ err.status = res.status;
+ if (typeof body?.type === 'string') err.type = body.type;
+ return err;
+}
+
export interface WorkerServer {
port: number;
baseURL: string;
@@ -267,7 +296,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
async replaceDoc(docName: string, markdown: string): Promise<void> {
const res = await post('/api/agent-write-md', { docName, markdown, position: 'replace' });
if (!res.ok) {
- throw new Error(`agent-write-md failed for ${docName}: ${res.status}`);
+ throw await problemError(res, `agent-write-md failed for ${docName}: ${res.status}`);
}
},
async writeAsAgent(docName: string, markdown: string, identity): Promise<void> {
@@ -281,7 +310,8 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
colorSeed: identity.colorSeed,
});
if (!res.ok) {
- throw new Error(
+ throw await problemError(
+ res,
`writeAsAgent failed for ${docName} / ${identity.agentId}: ${res.status}`,
);
}
diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.ts
index 6780f0684..c9c3912d2 100644
--- a/packages/app/tests/stress/_helpers/index.ts
+++ b/packages/app/tests/stress/_helpers/index.ts
@@ -12,6 +12,7 @@ export {
type AgentIdentity,
type ApiHelpers,
expect,
+ isConcurrentOverwriteRefusal,
REQUIRED_FIXTURE_ENTRY_NAMES,
test,
type WorkerServer,
diff --git a/packages/app/tests/stress/asset-click-dispatch.e2e.ts b/packages/app/tests/stress/asset-click-dispatch.e2e.ts
index 4c4e15b73..3d124a949 100644
--- a/packages/app/tests/stress/asset-click-dispatch.e2e.ts
+++ b/packages/app/tests/stress/asset-click-dispatch.e2e.ts
@@ -90,7 +90,7 @@ test.describe('asset-click dispatcher — P9 E2E scenarios (SPEC 2026-04-23)', (
await page.goto(`/#/${docName}`);
await waitForProvider(page);
await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
- await page.click('.ProseMirror:not(.composer-prosemirror)');
+ await page.click('.ProseMirror:not(.composer-prosemirror) h1');
});
test('P9.1: post-reload `![[file.pdf]]` renders as a File row via WikiEmbedFile (no link chip)', async ({
diff --git a/packages/app/tests/stress/jsx-unregistered-ime-concurrent.e2e.ts b/packages/app/tests/stress/jsx-unregistered-ime-concurrent.e2e.ts
index 5a53ab7ad..0c8f9c214 100644
--- a/packages/app/tests/stress/jsx-unregistered-ime-concurrent.e2e.ts
+++ b/packages/app/tests/stress/jsx-unregistered-ime-concurrent.e2e.ts
@@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
+import { CONCURRENT_REPLACE_WINDOW_MS } from '@inkeep/open-knowledge-server';
import type { CDPSession, Page } from '@playwright/test';
import type { ApiHelpers } from './_helpers';
-import { expect, test } from './_helpers';
+import { expect, isConcurrentOverwriteRefusal, test } from './_helpers';
interface FallbackNode {
type: { name: string };
@@ -182,7 +183,20 @@ test('FR-B3 agent write mid-composition: no glyph drop/dup, concurrent survives
await beginComposition(cdp);
expect(await composing(page)).toBe(true);
- await api.replaceDoc(docName, `<CustomWidget>\n\nAAA ${MARKER}\n\n</CustomWidget>\n`);
+ await expect
+ .poll(
+ async () => {
+ try {
+ await api.replaceDoc(docName, `<CustomWidget>\n\nAAA ${MARKER}\n\n</CustomWidget>\n`);
+ return true;
+ } catch (error) {
+ if (isConcurrentOverwriteRefusal(error)) return false;
+ throw error;
+ }
+ },
+ { timeout: CONCURRENT_REPLACE_WINDOW_MS * 2, intervals: [100, 250, 500] },
+ )
+ .toBe(true);
await page.waitForFunction(
(m) => window.__activeProvider?.document?.getText('source')?.toString()?.includes(m),
MARKER,
diff --git a/packages/app/tests/stress/multi-agent-presence.e2e.ts b/packages/app/tests/stress/multi-agent-presence.e2e.ts
index f32ec3a5e..95d5d556f 100644
--- a/packages/app/tests/stress/multi-agent-presence.e2e.ts
+++ b/packages/app/tests/stress/multi-agent-presence.e2e.ts
@@ -1,4 +1,10 @@
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
+import { CONCURRENT_REPLACE_WINDOW_MS } from '@inkeep/open-knowledge-server';
+import {
+ expect,
+ isConcurrentOverwriteRefusal,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
function agentId(label: string): string {
return `${label}-${crypto.randomUUID().slice(0, 8)}`;
@@ -18,18 +24,29 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
const claudeId = agentId('claude');
const cursorId = agentId('cursor');
- await Promise.all([
- api.writeAsAgent(docFoo, '# Claude was here', {
- agentId: claudeId,
- agentName: 'Claude',
- clientName: 'claude-code',
- }),
- api.writeAsAgent(docFoo, '# Cursor was here', {
- agentId: cursorId,
- agentName: 'Cursor',
- clientName: 'cursor',
- }),
- ]);
+ await api.writeAsAgent(docFoo, '# Claude was here', {
+ agentId: claudeId,
+ agentName: 'Claude',
+ clientName: 'claude-code',
+ });
+ await expect
+ .poll(
+ async () => {
+ try {
+ await api.writeAsAgent(docFoo, '# Cursor was here', {
+ agentId: cursorId,
+ agentName: 'Cursor',
+ clientName: 'cursor',
+ });
+ return true;
+ } catch (error) {
+ if (isConcurrentOverwriteRefusal(error)) return false;
+ throw error;
+ }
+ },
+ { timeout: CONCURRENT_REPLACE_WINDOW_MS * 2, intervals: [100, 250, 500] },
+ )
+ .toBe(true);
const currentSection = bar.locator('[data-presence-section="current"]');
await expect
@@ -98,6 +115,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
}) => {
const docFoo = 'doc-mp-nav-foo';
const docBar = 'doc-mp-nav-bar';
+ const cursorBarId = agentId('cursor-nav-bar');
await api.seedDocs([
{ name: docFoo, markdown: '# foo' },
{ name: docBar, markdown: '# bar body' },
@@ -112,7 +130,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
clientName: 'claude-code',
});
await api.writeAsAgent(docBar, '# Cursor on bar', {
- agentId: agentId('cursor-nav-bar'),
+ agentId: cursorBarId,
agentName: 'Cursor',
clientName: 'cursor',
});
@@ -123,7 +141,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
);
await expect(crossDocAvatar.first()).toBeVisible({ timeout: 10_000 });
await api.writeAsAgent(docBar, '# Cursor on bar', {
- agentId: agentId('cursor-nav-bar'),
+ agentId: cursorBarId,
agentName: 'Cursor',
clientName: 'cursor',
});
@@ -140,6 +158,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
api,
}) => {
const docBar = 'doc-mp-nodoc-bar';
+ const cursorBarId = agentId('cursor-nodoc-bar');
await api.seedDocs([{ name: docBar, markdown: '# bar body' }]);
await page.goto('/');
@@ -150,7 +169,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
await expect(panel).toBeHidden();
await api.writeAsAgent(docBar, '# Cursor on bar', {
- agentId: agentId('cursor-nodoc-bar'),
+ agentId: cursorBarId,
agentName: 'Cursor',
clientName: 'cursor',
});
@@ -160,7 +179,7 @@ test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {
);
await expect(crossDocAvatar.first()).toBeVisible({ timeout: 10_000 });
await api.writeAsAgent(docBar, '# Cursor on bar', {
- agentId: agentId('cursor-nodoc-bar'),
+ agentId: cursorBarId,
agentName: 'Cursor',
clientName: 'cursor',
});
diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.ts
index a33b12812..26a6f5ab2 100644
--- a/packages/core/src/handoff/urn-ipc-registry.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.ts
@@ -26,6 +26,7 @@ type Registry = {
export const URN_IPC_REGISTRY: Registry = RAW_REGISTRY;
export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>([
+ 'urn:ok:error:concurrent-overwrite-refused',
'urn:ok:error:malformed-upload',
'urn:ok:error:collision-exhaustion',
'urn:ok:error:storage-full',
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index 4ec9c098a..786fa0f10 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -96,6 +96,7 @@ export const ProblemTypeSchema = z.enum([
'urn:ok:error:no-project-dir',
'urn:ok:error:server-open-failed',
'urn:ok:error:doc-in-conflict',
+ 'urn:ok:error:concurrent-overwrite-refused',
'urn:ok:error:unresolved-conflict-markers',
'urn:ok:error:no-conflict-tracked',
'urn:ok:error:no-blocking-changes',
diff --git a/packages/core/src/schemas/api/agent-write.test.ts b/packages/core/src/schemas/api/agent-write.test.ts
index 5ae869906..ac08c1c50 100644
--- a/packages/core/src/schemas/api/agent-write.test.ts
+++ b/packages/core/src/schemas/api/agent-write.test.ts
@@ -22,6 +22,7 @@ describe('ProblemTypeSchema cluster A URN tokens', () => {
'urn:ok:error:reserved-doc-name',
'urn:ok:error:target-not-found',
'urn:ok:error:stale-target',
+ 'urn:ok:error:concurrent-overwrite-refused',
'urn:ok:error:no-active-session',
])('%s parses', (token) => {
const result = ProblemTypeSchema.safeParse(token);
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index f3c0d26a0..1b379fb46 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -91,7 +91,7 @@ Every `.md` / `.mdx` needs YAML frontmatter — `title` + `description` required
## Conflict-aware writes
-A 409 `doc-in-conflict` freezes writes and carries `conflict.kind` + `resolutionOptions`. A flush-time `stale-external-write` 409 means the edit reached collaborative recovery but not disk; resolve and re-read before retrying. Detect with `conflicts`, not `exec`; kinds and full flow in `references/conflict-resolution.md`.
+`doc-in-conflict` freezes writes; `stale-external-write` means recovery missed disk. Detect both with `conflicts`, not `exec`; see `references/conflict-resolution.md`. `concurrent-overwrite-refused` is not conflict state: wait its bound and retry or use `append`/`prepend`/`edit`.
## Anti-patterns — the top offenders
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index 669f2d26c..0d0a6ebb3 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -1719,6 +1719,55 @@ describe('handleFsWrite exclusion gate', () => {
});
});
+describe('handleFsWrite concurrent replace guard', () => {
+ test('returns one small ACP error and keeps the peer content', async () => {
+ const contentDir = tmp();
+ const docs = new Map<string, Y.Doc>();
+ const sessionManager = {
+ getSession: async (docName: string, agentId: string) => {
+ let document = docs.get(docName);
+ if (document === undefined) {
+ document = new Y.Doc();
+ Object.assign(document, { name: docName });
+ docs.set(docName, document);
+ }
+ return { dc: { document }, origin: { agentId }, agentId, docName };
+ },
+ closeAllForAgent: async () => {},
+ } as unknown as AgentSessionManager;
+ const manager = makeManager(contentDir, tmp(), { sessionManager });
+ const fsWrite = (
+ manager as unknown as {
+ handleFsWrite: (record: unknown, path: string, content: string) => Promise<void>;
+ }
+ ).handleFsWrite.bind(manager);
+ const path = join(contentDir, 'notes', 'shared.md');
+ const record = (agentSessionId: string) => ({
+ agentSessionId,
+ info: { lastActivityAt: 0, agent: { id: 'codex', name: agentSessionId } },
+ });
+
+ await fsWrite(record('agent-a'), path, '# From A\n');
+ const before = docs.get('notes/shared')?.getText('source').toString();
+ const error = await fsWrite(record('agent-b'), path, '# From B\n').then(
+ () => undefined,
+ (reason: unknown) => reason as { code?: number; message?: string; data?: unknown },
+ );
+
+ expect(error?.code).toBe(-32009);
+ expect(error?.message).toBe(
+ 'Another writer changed this document recently. Wait a few seconds and retry.',
+ );
+ expect(error?.data).toEqual({
+ type: 'urn:ok:error:concurrent-overwrite-refused',
+ file: 'notes/shared.md',
+ retryable: true,
+ retryAfterSeconds: 3,
+ });
+ expect(docs.get('notes/shared')?.getText('source').toString()).toBe(before);
+ });
+});
+
function writeRequestingAgentEntry(localDir: string, id: string, promptBody: string): void {
const agentPath = join(localDir, `${id}.mjs`);
writeFileSync(
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index 18bcbf385..0abfc3503 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -17,6 +17,7 @@ import {
ndJsonStream,
type PermissionOption,
PROTOCOL_VERSION,
+ RequestError,
type RequestPermissionResponse,
type SessionConfigOption,
type SessionNotification,
@@ -51,7 +52,7 @@ import type {
ThreadStatus,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { THREAD_REOPEN_OP_TIMEOUT_MS } from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { toBroadcasterKey } from '../agent-id.ts';
+import { sessionWriterId, toBroadcasterKey } from '../agent-id.ts';
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import { observeReadiness } from '../agent-registry-gate.ts';
import {
@@ -61,6 +62,13 @@ import {
snapshotBlocks,
} from '../agent-sessions.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
+import {
+ CONCURRENT_OVERWRITE_REFUSED_DETAIL,
+ CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+ ConcurrentOverwriteRefusedError,
+ logConcurrentOverwriteRefusal,
+} from '../concurrent-overwrite-refused-error.ts';
import { resolveOnPath } from '../git-preflight.ts';
import type { PinoLogger } from '../logger.ts';
import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';
@@ -146,6 +154,7 @@ const SIGN_IN_OUTPUT_LINES = 6;
const RESUME_REPLAY_QUIESCENCE_MS = 300;
const RESUME_REPLAY_MAX_WAIT_MS = 3_000;
const AUTH_REQUIRED_CODE = -32000;
+const CONCURRENT_OVERWRITE_REFUSED_CODE = -32009;
export const ACP_ENVIRONMENT_NOTE =
'Note on your environment: you are running inside the OpenKnowledge app, ' +
@@ -2678,27 +2687,46 @@ export class AcpThreadManager {
this.opts.resolveEmbed !== undefined
? { resolveEmbed: this.opts.resolveEmbed, sourcePath: target.rel }
: undefined;
- session.dc.document.transact(() => {
- const beforeBlocks = snapshotBlocks(session.dc.document);
- applyAgentMarkdownWrite(
- session.dc.document,
- content,
- 'replace',
- embedResolver,
- undefined,
- agentWriteLossDetect(session),
- );
- const changedBlocks =
- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
- const activityMap = session.dc.document.getMap('agent-flash');
- activityMap.set(record.agentSessionId, {
- agentId: record.agentSessionId,
- timestamp: Date.now(),
- type: 'insert',
- description: `Added (${record.info.agent.name}): ${content.slice(0, 50)}`,
- ...(changedBlocks !== undefined ? { changedBlocks } : {}),
- });
- }, session.origin);
+ const suppliedWriterId = sessionWriterId(session);
+ try {
+ session.dc.document.transact(() => {
+ const beforeBlocks = snapshotBlocks(session.dc.document);
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ content,
+ 'replace',
+ embedResolver,
+ undefined,
+ agentWriteLossDetect(session),
+ suppliedWriterId,
+ );
+ const changedBlocks =
+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
+ const activityMap = session.dc.document.getMap('agent-flash');
+ activityMap.set(record.agentSessionId, {
+ agentId: record.agentSessionId,
+ timestamp: Date.now(),
+ type: 'insert',
+ description: `Added (${record.info.agent.name}): ${content.slice(0, 50)}`,
+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),
+ });
+ }, session.origin);
+ } catch (error) {
+ if (error instanceof ConcurrentOverwriteRefusedError) {
+ logConcurrentOverwriteRefusal(error, 'acp-fs-write');
+ throw new RequestError(
+ CONCURRENT_OVERWRITE_REFUSED_CODE,
+ CONCURRENT_OVERWRITE_REFUSED_DETAIL,
+ {
+ type: CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ file: error.file,
+ retryable: true,
+ retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+ },
+ );
+ }
+ throw error;
+ }
this.setPresence(record, target.docName);
} else {
if (this.opts.isIgnoredPath(target.rel)) {
diff --git a/packages/server/src/agent-id.test.ts b/packages/server/src/agent-id.test.ts
index e27972d23..59ff3ad36 100644
--- a/packages/server/src/agent-id.test.ts
+++ b/packages/server/src/agent-id.test.ts
@@ -1,13 +1,17 @@
-import { describe, expect, test } from 'vitest';
+import { describe, expect, test, vi } from 'vitest';
import {
AGENT_ID_MAX_LEN,
AGENT_ID_RE,
AGENT_NAME_MAX_LEN,
+ ANONYMOUS_WRITER_ID,
parseAgentBodyFields,
resolveAgentType,
+ sessionWriterId,
toBroadcasterKey,
+ UNIDENTIFIED_WRITER_ID,
validateAgentId,
} from './agent-id.ts';
+import { getLogger } from './logger.ts';
describe('AGENT_ID_RE', () => {
test('accepts alphanumeric / underscore / hyphen', () => {
@@ -50,6 +54,33 @@ describe('toBroadcasterKey', () => {
});
});
+describe('sessionWriterId', () => {
+ test.each([
+ { label: 'the anonymous principal', agentId: ANONYMOUS_WRITER_ID },
+ { label: 'the stand-in for a caller that supplied none', agentId: UNIDENTIFIED_WRITER_ID },
+ ])('$label is not a writer identity, so it cannot be recorded as a peer', ({ agentId }) => {
+ expect(sessionWriterId({ agentId })).toBeUndefined();
+ });
+
+ test('an agent writer brands', () => {
+ expect(sessionWriterId({ agentId: 'agent-claude-7' })).toBe('agent-claude-7');
+ });
+
+ test('a principal writer brands — a local human is a legitimate peer', () => {
+ const principalWriter = 'principal-3f8c1b4e-9a21-4d6f-8e15-2c7b0a9d5431';
+ expect(sessionWriterId({ agentId: principalWriter })).toBe(principalWriter);
+ });
+
+ test('a caller that deliberately supplies the stand-in id still brands, under its broadcaster key', () => {
+ const deliberate = toBroadcasterKey(UNIDENTIFIED_WRITER_ID);
+ expect(deliberate).toBe('agent-claude-1');
+ expect(parseAgentBodyFields({ agentId: UNIDENTIFIED_WRITER_ID }).suppliedWriterId).toBe(
+ deliberate,
+ );
+ expect(sessionWriterId({ agentId: deliberate })).toBe(deliberate);
+ });
+});
+
describe('resolveAgentType', () => {
test('classifies known clients; unknown → bot', () => {
expect(resolveAgentType('claude-code')).toBe('claude');
@@ -65,40 +96,41 @@ describe('resolveAgentType', () => {
});
describe('parseAgentBodyFields', () => {
- test('valid agentId → rawAgentId + writerId populated', () => {
+ test('valid agentId → rawAgentId + suppliedWriterId populated', () => {
const fields = parseAgentBodyFields({ agentId: 'claude-7' });
expect(fields.rawAgentId).toBe('claude-7');
- expect(fields.writerId).toBe('agent-claude-7');
+ expect(fields.suppliedWriterId).toBe('agent-claude-7');
});
- test('absent agentId → rawAgentId + writerId both undefined (caller decides default)', () => {
+ test('absent agentId → rawAgentId + suppliedWriterId both undefined (caller decides default)', () => {
const fields = parseAgentBodyFields({});
expect(fields.rawAgentId).toBeUndefined();
- expect(fields.writerId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
});
- test('invalid agentId (regex fail) → rawAgentId undefined, no writerId', () => {
+ test('invalid agentId (regex fail) → rawAgentId undefined, no suppliedWriterId', () => {
const fields = parseAgentBodyFields({ agentId: 'has space' });
expect(fields.rawAgentId).toBeUndefined();
- expect(fields.writerId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
});
- test('empty-string agentId is treated as absent', () => {
+ test('empty-string agentId yields no rawAgentId and no suppliedWriterId', () => {
const fields = parseAgentBodyFields({ agentId: '' });
expect(fields.rawAgentId).toBeUndefined();
- expect(fields.writerId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
});
- test('non-string agentId is treated as absent', () => {
+ test('non-string agentId yields no rawAgentId and no suppliedWriterId', () => {
const fields = parseAgentBodyFields({ agentId: 42 });
expect(fields.rawAgentId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
});
- test('overlong agentId is treated as absent (DoS bound on session map)', () => {
+ test('overlong agentId yields no suppliedWriterId (DoS bound on session map)', () => {
const overLimit = 'a'.repeat(AGENT_ID_MAX_LEN + 1);
const fields = parseAgentBodyFields({ agentId: overLimit });
expect(fields.rawAgentId).toBeUndefined();
- expect(fields.writerId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
});
test('agentName sanitized; missing defaults to "Claude"', () => {
@@ -133,3 +165,106 @@ describe('parseAgentBodyFields', () => {
expect(parseAgentBodyFields({ colorSeed: 'team-purple' }).colorSeed).toBe('team-purple');
});
});
+
+describe('parseAgentBodyFields agentId validation signal', () => {
+ function captureWarnings(): {
+ warned: { data: Record<string, unknown>; msg: string }[];
+ restore: () => void;
+ } {
+ const logger = getLogger('agent-write');
+ const warned: { data: Record<string, unknown>; msg: string }[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown, msg?: string) => {
+ warned.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '' });
+ }) as never);
+ return { warned, restore: () => spy.mockRestore() };
+ }
+
+ test('a malformed agentId warns instead of silently demoting to the default writer', () => {
+ const { warned, restore } = captureWarnings();
+ try {
+ const fields = parseAgentBodyFields({ agentId: 'has space' });
+ expect(fields.rawAgentId).toBeUndefined();
+ expect(fields.suppliedWriterId).toBeUndefined();
+ expect(warned).toHaveLength(1);
+ expect(warned[0]?.data.event).toBe('agent-id-validation-failed');
+ expect(warned[0]?.data.reason).toBe('charset');
+ expect(warned[0]?.data.agentIdType).toBe('string');
+ } finally {
+ restore();
+ }
+ });
+
+ test('an over-long agentId warns and names the bound it exceeded', () => {
+ const { warned, restore } = captureWarnings();
+ try {
+ const tooLong = 'a'.repeat(AGENT_ID_MAX_LEN + 1);
+ expect(parseAgentBodyFields({ agentId: tooLong }).suppliedWriterId).toBeUndefined();
+ expect(warned).toHaveLength(1);
+ expect(warned[0]?.data.reason).toBe('too-long');
+ expect(warned[0]?.data.agentIdMaxLen).toBe(AGENT_ID_MAX_LEN);
+ } finally {
+ restore();
+ }
+ });
+
+ test.each([
+ { label: 'empty string', agentId: '', reason: 'empty', agentIdType: 'string' },
+ { label: 'number', agentId: 42, reason: 'not-a-string', agentIdType: 'number' },
+ { label: 'boolean', agentId: true, reason: 'not-a-string', agentIdType: 'boolean' },
+ { label: 'null', agentId: null, reason: 'not-a-string', agentIdType: 'object' },
+ { label: 'array', agentId: ['claude-1'], reason: 'not-a-string', agentIdType: 'object' },
+ { label: 'object', agentId: { id: 'claude-1' }, reason: 'not-a-string', agentIdType: 'object' },
+ ])(
+ 'a supplied but unusable agentId ($label) warns like a rejected string',
+ ({ agentId, reason, agentIdType }) => {
+ const { warned, restore } = captureWarnings();
+ try {
+ expect(parseAgentBodyFields({ agentId }).suppliedWriterId).toBeUndefined();
+ expect(warned).toHaveLength(1);
+ expect(warned[0]?.data.event).toBe('agent-id-validation-failed');
+ expect(warned[0]?.data.reason).toBe(reason);
+ expect(warned[0]?.data.agentIdType).toBe(agentIdType);
+ } finally {
+ restore();
+ }
+ },
+ );
+
+ test('the warning never carries the rejected agentId itself', () => {
+ const { warned, restore } = captureWarnings();
+ try {
+ const secretish = 'tenant/[email protected]';
+ parseAgentBodyFields({ agentId: secretish });
+ parseAgentBodyFields({ agentId: { tenant: secretish } });
+ expect(warned).toHaveLength(2);
+ expect(JSON.stringify(warned)).not.toContain(secretish);
+ expect(JSON.stringify(warned)).not.toContain('example.com');
+ } finally {
+ restore();
+ }
+ });
+
+ test('the warning claims only the discard, not a caller-specific writer fallback', () => {
+ const { warned, restore } = captureWarnings();
+ try {
+ parseAgentBodyFields({ agentId: 'has space' });
+ expect(warned).toHaveLength(1);
+ expect(warned[0]?.msg).toContain('was discarded');
+ expect(warned[0]?.msg).not.toContain('default writer');
+ } finally {
+ restore();
+ }
+ });
+
+ test('a valid or absent agentId stays silent', () => {
+ const { warned, restore } = captureWarnings();
+ try {
+ expect(parseAgentBodyFields({ agentId: 'claude-7' }).suppliedWriterId).toBe('agent-claude-7');
+ parseAgentBodyFields({});
+ parseAgentBodyFields({ agentName: 'Bob' });
+ expect(warned).toEqual([]);
+ } finally {
+ restore();
+ }
+ });
+});
diff --git a/packages/server/src/agent-id.ts b/packages/server/src/agent-id.ts
index ee6971791..18b282d52 100644
--- a/packages/server/src/agent-id.ts
+++ b/packages/server/src/agent-id.ts
@@ -1,14 +1,23 @@
import { sanitizeGitIdentity } from './git-identity-sanitize.ts';
+import { getLogger } from './logger.ts';
export const AGENT_ID_RE = /^[a-zA-Z0-9_-]+$/;
export const AGENT_ID_MAX_LEN = 64;
+type AgentIdRejection = 'not-a-string' | 'empty' | 'too-long' | 'charset';
+
+function classifyAgentIdRejection(suppliedAgentId: unknown): AgentIdRejection | null {
+ if (typeof suppliedAgentId !== 'string') return 'not-a-string';
+ if (suppliedAgentId.length === 0) return 'empty';
+ if (suppliedAgentId.length > AGENT_ID_MAX_LEN) return 'too-long';
+ if (!AGENT_ID_RE.test(suppliedAgentId)) return 'charset';
+ return null;
+}
+
export function validateAgentId(rawAgentId: string | undefined | null): string | null {
- if (typeof rawAgentId !== 'string' || rawAgentId.length === 0) return null;
- if (rawAgentId.length > AGENT_ID_MAX_LEN) return null;
- if (!AGENT_ID_RE.test(rawAgentId)) return null;
- return rawAgentId;
+ if (typeof rawAgentId !== 'string') return null;
+ return classifyAgentIdRejection(rawAgentId) === null ? rawAgentId : null;
}
export function toBroadcasterKey(rawAgentId: string): string {
@@ -38,9 +47,29 @@ export function resolveAgentType(clientName: string | undefined): string {
export const AGENT_NAME_MAX_LEN = 128;
+export const ANONYMOUS_WRITER_ID = 'principal-anonymous';
+
+export const UNIDENTIFIED_WRITER_ID = 'claude-1';
+
+const IDENTITY_ABSENT_WRITER_IDS: ReadonlySet<string> = new Set([
+ ANONYMOUS_WRITER_ID,
+ UNIDENTIFIED_WRITER_ID,
+]);
+
+export type RawWriterId = string & { readonly __brand: 'RawWriterId' };
+
+function brandWriterId(writerId: string): RawWriterId {
+ return writerId as RawWriterId;
+}
+
+export function sessionWriterId(session: { agentId: string }): RawWriterId | undefined {
+ if (IDENTITY_ABSENT_WRITER_IDS.has(session.agentId)) return undefined;
+ return brandWriterId(session.agentId);
+}
+
interface AgentBodyFields {
rawAgentId: string | undefined;
- writerId: string | undefined;
+ suppliedWriterId: RawWriterId | undefined;
displayName: string;
clientName: string | undefined;
clientVersion: string | undefined;
@@ -49,10 +78,25 @@ interface AgentBodyFields {
}
export function parseAgentBodyFields(body: Record<string, unknown>): AgentBodyFields {
- const validated = validateAgentId(typeof body.agentId === 'string' ? body.agentId : null);
- const rawAgentId = validated ?? undefined;
+ const suppliedAgentId = body.agentId;
+ const rejection =
+ suppliedAgentId === undefined ? null : classifyAgentIdRejection(suppliedAgentId);
+ const rawAgentId =
+ rejection === null && typeof suppliedAgentId === 'string' ? suppliedAgentId : undefined;
+ if (rejection !== null) {
+ getLogger('agent-write').warn(
+ {
+ event: 'agent-id-validation-failed',
+ reason: rejection,
+ agentIdType: typeof suppliedAgentId,
+ agentIdMaxLen: AGENT_ID_MAX_LEN,
+ },
+ 'request agentId failed validation and was discarded before writer-identity resolution',
+ );
+ }
- const writerId = rawAgentId !== undefined ? toBroadcasterKey(rawAgentId) : undefined;
+ const suppliedWriterId =
+ rawAgentId !== undefined ? brandWriterId(toBroadcasterKey(rawAgentId)) : undefined;
const displayName =
typeof body.agentName === 'string' ? sanitizeGitIdentity(body.agentName) : 'Claude';
@@ -68,5 +112,13 @@ export function parseAgentBodyFields(body: Record<string, unknown>): AgentBodyFi
? body.colorSeed.slice(0, AGENT_NAME_MAX_LEN)
: undefined;
- return { rawAgentId, writerId, displayName, clientName, clientVersion, label, colorSeed };
+ return {
+ rawAgentId,
+ suppliedWriterId,
+ displayName,
+ clientName,
+ clientVersion,
+ label,
+ colorSeed,
+ };
}
diff --git a/packages/server/src/agent-sessions.test.ts b/packages/server/src/agent-sessions.test.ts
index 9256a5afa..b9d8a20ee 100644
--- a/packages/server/src/agent-sessions.test.ts
+++ b/packages/server/src/agent-sessions.test.ts
@@ -1,19 +1,30 @@
import type { Document } from '@hocuspocus/server';
import { sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { metrics } from '@opentelemetry/api';
+import {
+ AggregationTemporality,
+ InMemoryMetricExporter,
+ MeterProvider,
+ PeriodicExportingMetricReader,
+} from '@opentelemetry/sdk-metrics';
import { getSchema } from '@tiptap/core';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
+import { sessionWriterId } from './agent-id.ts';
import {
type AgentDirectConnection,
AgentSessionCapacityError,
AgentSessionManager,
applyAgentMarkdownWrite,
applyAgentUndo,
+ CONCURRENT_REPLACE_WINDOW_MS,
} from './agent-sessions.ts';
+import { ConcurrentOverwriteRefusedError } from './concurrent-overwrite-refused-error.ts';
import { bindConflictAuthority } from './conflict-authority.ts';
import { DocInConflictError } from './conflict-errors.ts';
import { _resetDocExtensionsForTests, registerDocExtension } from './doc-extensions.ts';
+import { __resetFrontmatterTelemetryForTests } from './frontmatter-telemetry.ts';
function createMockHocuspocus() {
const openedDocs: string[] = [];
@@ -753,6 +764,47 @@ describe('conflict-aware write gate (FR9 a, d)', () => {
});
describe('applyAgentMarkdownWrite — position: "replace" atomic-overwrite contract (PRD-6667)', () => {
+ test('starts peer protection after a slow replace finishes', async () => {
+ const first = await manager.getSession('slow-replace.md', 'agent-a');
+ const clock = vi
+ .spyOn(Date, 'now')
+ .mockReturnValueOnce(1_000)
+ .mockReturnValueOnce(4_000)
+ .mockReturnValueOnce(4_000)
+ .mockReturnValue(4_001);
+ try {
+ first.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# First replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId(first),
+ );
+ }, first.origin);
+ expect(() =>
+ first.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# Peer replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).toThrow(ConcurrentOverwriteRefusedError);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
test('replace overwrites prior bytes atomically — full delete + full insert, not DMP-incremental merge', async () => {
const session = await manager.getSession('doc-replace-shape.md', 'agent-shape');
const ytext = session.dc.document.getText('source');
@@ -942,4 +994,241 @@ describe('applyAgentMarkdownWrite — position: "replace" atomic-overwrite contr
expect(undone).toBe(true);
expect(ytext.toString()).toBe(seed);
});
+
+ test('refuses a peer replace when a backward clock step future-dates the peer stamp', async () => {
+ const first = await manager.getSession('backward-clock-step.md', 'agent-a');
+ let nowMs = 4_000;
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => nowMs);
+ try {
+ first.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# First replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId(first),
+ );
+ }, first.origin);
+
+ nowMs = 3_999;
+ expect(() =>
+ first.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# Peer replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).toThrow(ConcurrentOverwriteRefusedError);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ test('admits a peer replace when the backward clock step reaches the guard window', async () => {
+ const first = await manager.getSession('backward-clock-step-beyond-window.md', 'agent-a');
+ let nowMs = 10_000;
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => nowMs);
+ try {
+ first.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# First replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId(first),
+ );
+ }, first.origin);
+
+ nowMs = 10_000 - CONCURRENT_REPLACE_WINDOW_MS;
+ expect(() =>
+ first.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# Peer replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).not.toThrow();
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ test('a refused frontmatter-carrying replace leaves the edit-surface counter unchanged', async () => {
+ const exporter = new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE);
+ const reader = new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: 60_000 });
+ const meterProvider = new MeterProvider({ readers: [reader] });
+ metrics.disable();
+ metrics.setGlobalMeterProvider(meterProvider);
+ __resetFrontmatterTelemetryForTests();
+
+ const readMcpWriteTotal = async (): Promise<number> => {
+ await reader.forceFlush();
+ return exporter
+ .getMetrics()
+ .flatMap((rm) => rm.scopeMetrics)
+ .flatMap((sm) => sm.metrics)
+ .filter((m) => m.descriptor.name === 'ok.frontmatter.edit_surface_total')
+ .flatMap((m) => m.dataPoints)
+ .filter((dp) => dp.attributes.source === 'mcp-write')
+ .reduce((total, dp) => total + (dp.value as number), 0);
+ };
+
+ const session = await manager.getSession('refused-fm-telemetry.md', 'agent-a');
+ let nowMs = 4_000;
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => nowMs);
+ try {
+ session.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ 'Body without frontmatter.\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId(session),
+ );
+ }, session.origin);
+
+ const peerPayload = '---\ntitle: Peer\n---\nPeer body.\n';
+ nowMs = 4_500;
+ expect(() =>
+ session.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ peerPayload,
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).toThrow(ConcurrentOverwriteRefusedError);
+ expect(await readMcpWriteTotal()).toBe(0);
+
+ exporter.reset();
+ nowMs = 10_000;
+ session.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ peerPayload,
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ );
+ expect(await readMcpWriteTotal()).toBe(1);
+ } finally {
+ clock.mockRestore();
+ await meterProvider.shutdown();
+ metrics.disable();
+ __resetFrontmatterTelemetryForTests();
+ }
+ });
+
+ test.each([
+ {
+ position: 'append',
+ payload: 'Peer appended line.\n',
+ expected: '# First replacement\n\nPeer appended line.\n',
+ },
+ {
+ position: 'prepend',
+ payload: 'Peer prepended line.\n',
+ expected: 'Peer prepended line.\n\n# First replacement\n',
+ },
+ {
+ position: 'patch',
+ payload: '# First replacement\n\nPeer patched line.\n',
+ expected: '# First replacement\n\nPeer patched line.\n',
+ },
+ ] as const)(
+ 'admits a peer $position in the same window that refuses a peer replace',
+ async ({ position, payload, expected }) => {
+ const first = await manager.getSession(`peer-${position}.md`, 'agent-a');
+ const ytext = first.dc.document.getText('source');
+ let nowMs = 4_000;
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => nowMs);
+ try {
+ first.dc.document.transact(() => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# First replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId(first),
+ );
+ }, first.origin);
+
+ nowMs = 4_500;
+ expect(() =>
+ first.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ '# Peer replacement\n',
+ 'replace',
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).toThrow(ConcurrentOverwriteRefusedError);
+ expect(ytext.toString()).toBe('# First replacement\n');
+
+ expect(() =>
+ first.dc.document.transact(
+ () => {
+ applyAgentMarkdownWrite(
+ first.dc.document,
+ payload,
+ position,
+ undefined,
+ undefined,
+ undefined,
+ sessionWriterId({ agentId: 'agent-b' }),
+ );
+ },
+ { agentId: 'agent-b' },
+ ),
+ ).not.toThrow();
+ expect(ytext.toString()).toBe(expected);
+ } finally {
+ clock.mockRestore();
+ }
+ },
+ );
});
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index 90fb344e1..1c8aa33ed 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -14,6 +14,7 @@ export { colorFromSeed } from '@inkeep/open-knowledge-core';
import * as Y from 'yjs';
import type { YjsStackItemShape } from './agent-activity.ts';
+import { type RawWriterId, UNIDENTIFIED_WRITER_ID } from './agent-id.ts';
import {
composeAndWriteRawBody,
deriveFragmentFromYtext,
@@ -27,6 +28,7 @@ import {
} from './bridge-loss-detector.ts';
import { shouldRunPairedIntakeDetection } from './bridge-loss-suppression.ts';
import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { ConcurrentOverwriteRefusedError } from './concurrent-overwrite-refused-error.ts';
import { isDocInConflict } from './conflict-authority.ts';
import { DocInConflictError } from './conflict-errors.ts';
import {
@@ -39,7 +41,11 @@ import { recordFrontmatterEditSurface } from './frontmatter-telemetry.ts';
import { getLogger } from './logger.ts';
import { incrementAgentSessionEvictions } from './metrics.ts';
import { precomputeParse } from './parse-pool.ts';
-import { getPreDrainController, type PairedWriteOrigin } from './server-observers.ts';
+import {
+ getLastExternalEditorChangeMs,
+ getPreDrainController,
+ type PairedWriteOrigin,
+} from './server-observers.ts';
import { getMeter, setActiveSpanAttributes, withSpanSync } from './telemetry.ts';
export type { AgentWriteContentDivergence };
@@ -105,6 +111,58 @@ export interface AgentWriteLossDetect {
writerId: string | null;
}
+export const CONCURRENT_REPLACE_WINDOW_MS = 2_000;
+
+class AgentWriteRecency {
+ private readonly writes = new WeakMap<Document, Map<RawWriterId, number>>();
+
+ record(document: Document, agentId: RawWriterId, nowMs: number): void {
+ const byAgent = this.writes.get(document) ?? new Map<RawWriterId, number>();
+ for (const [writerId, writtenAtMs] of byAgent) {
+ if (!isRecent(writtenAtMs, nowMs)) byAgent.delete(writerId);
+ }
+ byAgent.set(agentId, nowMs);
+ this.writes.set(document, byAgent);
+ }
+
+ hasRecentPeer(document: Document, agentId: RawWriterId | undefined, nowMs: number): boolean {
+ const byAgent = this.writes.get(document);
+ if (byAgent === undefined) return false;
+ for (const [writerId, writtenAtMs] of byAgent) {
+ const ageMs = nowMs - writtenAtMs;
+ if (Math.abs(ageMs) >= CONCURRENT_REPLACE_WINDOW_MS) {
+ byAgent.delete(writerId);
+ continue;
+ }
+ if (writerId !== agentId) return true;
+ }
+ return false;
+ }
+}
+
+const agentWriteRecency = new AgentWriteRecency();
+
+function isRecent(timestampMs: number | undefined, nowMs: number): boolean {
+ if (timestampMs === undefined) return false;
+ return Math.abs(nowMs - timestampMs) < CONCURRENT_REPLACE_WINDOW_MS;
+}
+
+function assertConcurrentReplaceAllowed(
+ document: Document,
+ position: 'append' | 'prepend' | 'replace' | 'patch',
+ suppliedWriterId: RawWriterId | undefined,
+ nowMs: number,
+): void {
+ if (position !== 'replace') return;
+ const recentAgentWrite = agentWriteRecency.hasRecentPeer(document, suppliedWriterId, nowMs);
+ const recentEditorWrite = isRecent(
+ getLastExternalEditorChangeMs(document as unknown as Y.Doc),
+ nowMs,
+ );
+ if (!recentAgentWrite && !recentEditorWrite) return;
+ throw new ConcurrentOverwriteRefusedError(docNameToFile(document.name));
+}
+
export function agentWriteLossDetect(session: {
bridgeLossReporter?: BridgeDeriveLossReporter;
agentId: string;
@@ -137,6 +195,7 @@ export function applyAgentMarkdownWrite(
},
precomputed?: PrecomputedParse,
lossDetect?: AgentWriteLossDetect,
+ suppliedWriterId?: RawWriterId,
): AgentWriteContentDivergence | undefined {
if (isDocInConflict(document)) {
throw new DocInConflictError({ file: docNameToFile(document.name) });
@@ -158,6 +217,7 @@ export function applyAgentMarkdownWrite(
embedResolver,
precomputed,
lossDetect,
+ suppliedWriterId,
);
if (divergence !== undefined) {
setActiveSpanAttributes({
@@ -245,6 +305,7 @@ function applyAgentMarkdownWriteInner(
},
precomputed?: PrecomputedParse,
lossDetect?: AgentWriteLossDetect,
+ suppliedWriterId?: RawWriterId,
): AgentWriteContentDivergence | undefined {
try {
const ytext = document.getText('source');
@@ -269,6 +330,7 @@ function applyAgentMarkdownWriteInner(
}
: undefined;
+ let frontmatterEdited = false;
if (finalFm !== existingFm) {
const parsed = parseFrontmatterYaml(unwrapFrontmatterFences(finalFm));
if (parsed.map === null) {
@@ -277,7 +339,7 @@ function applyAgentMarkdownWriteInner(
parseError: parsed.parseError ?? 'unknown YAML parse error',
});
}
- recordFrontmatterEditSurface('mcp-write');
+ frontmatterEdited = true;
} else if (finalFm === '' && stripFrontmatter(newContent).frontmatter !== '') {
throw new FrontmatterMalformedError({
file: docNameToFile(document.name),
@@ -288,6 +350,9 @@ function applyAgentMarkdownWriteInner(
});
}
+ assertConcurrentReplaceAllowed(document, position, suppliedWriterId, Date.now());
+ if (frontmatterEdited) recordFrontmatterEditSurface('mcp-write');
+
if (position === 'replace') {
replaceRawBody(document, newContent, embedResolver, precomputed, detect);
} else {
@@ -295,6 +360,9 @@ function applyAgentMarkdownWriteInner(
}
const actualYText = document.getText('source').toString();
+ if (suppliedWriterId !== undefined && actualYText !== currentYText) {
+ agentWriteRecency.record(document, suppliedWriterId, Date.now());
+ }
const divergence = evaluateContentDivergence(actualYText, newContent, position);
log.debug(
{
@@ -307,7 +375,10 @@ function applyAgentMarkdownWriteInner(
);
return divergence;
} catch (err) {
- if (!(err instanceof FrontmatterMalformedError)) {
+ if (
+ !(err instanceof FrontmatterMalformedError) &&
+ !(err instanceof ConcurrentOverwriteRefusedError)
+ ) {
log.error(
{ err, docName: document.name, position, markdownLen: markdown.length },
`[applyAgentMarkdownWrite] failed for '${document.name}'`,
@@ -557,7 +628,7 @@ export class AgentSessionManager {
*/
async getSession(
docName: string,
- agentId = 'claude-1',
+ agentId = UNIDENTIFIED_WRITER_ID,
identity?: AgentSessionIdentity,
): Promise<SessionRecord> {
if (isSystemDoc(docName) || isConfigDoc(docName)) {
@@ -687,7 +758,7 @@ export class AgentSessionManager {
return key;
}
- hasSession(docName: string, agentId = 'claude-1'): boolean {
+ hasSession(docName: string, agentId = UNIDENTIFIED_WRITER_ID): boolean {
return this.sessions.has(this.sessionKey(docName, agentId));
}
@@ -716,7 +787,7 @@ export class AgentSessionManager {
}
}
- async closeSession(docName: string, agentId = 'claude-1'): Promise<void> {
+ async closeSession(docName: string, agentId = UNIDENTIFIED_WRITER_ID): Promise<void> {
const key = this.sessionKey(docName, agentId);
const session = this.sessions.get(key);
if (!session) return;
diff --git a/packages/server/src/agent-write-agent-id-coverage.test.ts b/packages/server/src/agent-write-agent-id-coverage.test.ts
new file mode 100644
index 000000000..0e3234c91
--- /dev/null
+++ b/packages/server/src/agent-write-agent-id-coverage.test.ts
@@ -0,0 +1,151 @@
+import { basename, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Node, Project, SyntaxKind } from 'ts-morph';
+import { describe, expect, it } from 'vitest';
+import { listAgentWriteSpineFiles } from './agent-write-spine-files.test-helper.ts';
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+function newProject(): Project {
+ return new Project({
+ skipFileDependencyResolution: true,
+ skipLoadingLibFiles: true,
+ skipAddingFilesFromTsConfig: true,
+ compilerOptions: { noLib: true, allowJs: false },
+ });
+}
+
+function calleeName(call: Node): string | null {
+ if (!Node.isCallExpression(call)) return null;
+ const expr = call.getExpression();
+ if (Node.isIdentifier(expr)) return expr.getText();
+ if (Node.isPropertyAccessExpression(expr)) return expr.getName();
+ return null;
+}
+
+function threadsWriterIdentity(call: Node): boolean {
+ if (!Node.isCallExpression(call)) return false;
+ return call
+ .getArguments()
+ .some((arg) => Node.isIdentifier(arg) && arg.getText() === 'suppliedWriterId');
+}
+
+describe('agent-write writer-identity coverage', () => {
+ it('every applyAgentMarkdownWrite spine call threads its writer identity', () => {
+ const project = newProject();
+ const spineFiles = listAgentWriteSpineFiles(here);
+ expect(spineFiles.length).toBeGreaterThan(0);
+ const spineCalls = spineFiles.flatMap((path) =>
+ project
+ .addSourceFileAtPath(join(here, path))
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .filter((c) => calleeName(c) === 'applyAgentMarkdownWrite'),
+ );
+ expect(spineCalls.length).toBeGreaterThanOrEqual(6);
+ const missing = spineCalls
+ .filter((c) => !threadsWriterIdentity(c))
+ .map((c) => `${basename(c.getSourceFile().getFilePath())}:${c.getStartLineNumber()}`);
+ expect(missing).toEqual([]);
+ });
+
+ it('flags a spine call that omits the writer identity (planted positive)', () => {
+ const project = newProject();
+ const sf = project.createSourceFile(
+ 'planted-missing-agent-id.ts',
+ `declare function applyAgentMarkdownWrite(...a: unknown[]): void;
+ declare function agentWriteLossDetect(s: unknown): unknown;
+ function h(session: { dc: { document: unknown } }) {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ 'x',
+ 'append',
+ undefined,
+ undefined,
+ agentWriteLossDetect(session),
+ );
+ }`,
+ );
+ const call = sf
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .find((c) => calleeName(c) === 'applyAgentMarkdownWrite');
+ expect(call).toBeDefined();
+ expect(call && threadsWriterIdentity(call)).toBe(false);
+ });
+
+ it('flags a spine call that threads the defaulted attribution id (planted positive)', () => {
+ const project = newProject();
+ const sf = project.createSourceFile(
+ 'planted-with-agent-id.ts',
+ `declare function applyAgentMarkdownWrite(...a: unknown[]): void;
+ declare function agentWriteLossDetect(s: unknown): unknown;
+ function h(session: { dc: { document: unknown }; agentId: string }) {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ 'x',
+ 'append',
+ undefined,
+ undefined,
+ agentWriteLossDetect(session),
+ session.agentId,
+ );
+ }`,
+ );
+ const call = sf
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .find((c) => calleeName(c) === 'applyAgentMarkdownWrite');
+ expect(call).toBeDefined();
+ expect(call && threadsWriterIdentity(call)).toBe(false);
+ });
+
+ it('flags a spine call that threads the loss-detect writerId (planted positive)', () => {
+ const project = newProject();
+ const sf = project.createSourceFile(
+ 'planted-with-loss-detect-writer-id.ts',
+ `declare function applyAgentMarkdownWrite(...a: unknown[]): void;
+ declare function agentWriteLossDetect(s: unknown): { writerId: string | null };
+ function h(session: { dc: { document: unknown } }) {
+ const lossDetect = agentWriteLossDetect(session);
+ const { writerId } = lossDetect;
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ 'x',
+ 'append',
+ undefined,
+ undefined,
+ lossDetect,
+ writerId,
+ );
+ }`,
+ );
+ const call = sf
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .find((c) => calleeName(c) === 'applyAgentMarkdownWrite');
+ expect(call).toBeDefined();
+ expect(call && threadsWriterIdentity(call)).toBe(false);
+ });
+
+ it('recognizes the presence-bearing suppliedWriterId form (positive control)', () => {
+ const project = newProject();
+ const sf = project.createSourceFile(
+ 'planted-with-supplied-writer-id.ts',
+ `declare function applyAgentMarkdownWrite(...a: unknown[]): void;
+ declare function agentWriteLossDetect(s: unknown): unknown;
+ function h(session: { dc: { document: unknown } }, suppliedWriterId: string | undefined) {
+ applyAgentMarkdownWrite(
+ session.dc.document,
+ 'x',
+ 'append',
+ undefined,
+ undefined,
+ agentWriteLossDetect(session),
+ suppliedWriterId,
+ );
+ }`,
+ );
+ const call = sf
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .find((c) => calleeName(c) === 'applyAgentMarkdownWrite');
+ expect(call).toBeDefined();
+ expect(call && threadsWriterIdentity(call)).toBe(true);
+ });
+});
diff --git a/packages/server/src/agent-write-spine-files.test-helper.ts b/packages/server/src/agent-write-spine-files.test-helper.ts
index ff7a1fe6d..959dfa114 100644
--- a/packages/server/src/agent-write-spine-files.test-helper.ts
+++ b/packages/server/src/agent-write-spine-files.test-helper.ts
@@ -6,9 +6,11 @@ export function listAgentWriteSpineFiles(serverSrcRoot: string): string[] {
.filter(
(entry) =>
entry.isFile() &&
- entry.name.endsWith('.ts') &&
+ (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) &&
!entry.name.endsWith('.test.ts') &&
- !entry.name.endsWith('.test-helper.ts'),
+ !entry.name.endsWith('.test.tsx') &&
+ !entry.name.endsWith('.test-helper.ts') &&
+ !entry.name.endsWith('.test-helper.tsx'),
)
.map((entry) => join(entry.parentPath, entry.name))
.filter((path) => readFileSync(path, 'utf8').includes('applyAgentMarkdownWrite'))
diff --git a/packages/server/src/agent-write-spine-walk-root-coverage-contract.test.ts b/packages/server/src/agent-write-spine-walk-root-coverage-contract.test.ts
new file mode 100644
index 000000000..9ae9c9540
--- /dev/null
+++ b/packages/server/src/agent-write-spine-walk-root-coverage-contract.test.ts
@@ -0,0 +1,121 @@
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Node, Project, SyntaxKind } from 'ts-morph';
+import { describe, expect, it } from 'vitest';
+import { listAgentWriteSpineFiles } from './agent-write-spine-files.test-helper.ts';
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+const monorepoRoot = join(here, '..', '..', '..');
+
+const SERVER_PACKAGE_NAME = '@inkeep/open-knowledge-server';
+
+const SPINE_HELPER_SPECIFIER = './agent-write-spine-files.test-helper.ts';
+
+function listWorkspaceManifests(dir: string, depth: number): string[] {
+ if (depth === 0) return [];
+ const found: string[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isFile() && entry.name === 'package.json') found.push(join(dir, entry.name));
+ if (!entry.isDirectory()) continue;
+ if (entry.name.startsWith('.')) continue;
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'out') continue;
+ found.push(...listWorkspaceManifests(join(dir, entry.name), depth - 1));
+ }
+ return found;
+}
+
+function declaresServerDependency(manifestPath: string): boolean {
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+ peerDependencies?: Record<string, string>;
+ optionalDependencies?: Record<string, string>;
+ };
+ return [
+ manifest.dependencies,
+ manifest.devDependencies,
+ manifest.peerDependencies,
+ manifest.optionalDependencies,
+ ].some((deps) => deps !== undefined && Object.hasOwn(deps, SERVER_PACKAGE_NAME));
+}
+
+function listServerConsumerSrcRoots(): string[] {
+ return listWorkspaceManifests(monorepoRoot, 4)
+ .filter(declaresServerDependency)
+ .map((manifestPath) => join(dirname(manifestPath), 'src'))
+ .filter((srcRoot) => existsSync(srcRoot))
+ .sort();
+}
+
+function listCensusFiles(): string[] {
+ return readdirSync(here, { withFileTypes: true })
+ .filter(
+ (entry) =>
+ entry.isFile() &&
+ entry.name.endsWith('-coverage.test.ts') &&
+ readFileSync(join(here, entry.name), 'utf8').includes(SPINE_HELPER_SPECIFIER),
+ )
+ .map((entry) => entry.name)
+ .sort();
+}
+
+function spineWalkRootArguments(censusFile: string): string[] {
+ const project = new Project({
+ skipFileDependencyResolution: true,
+ skipLoadingLibFiles: true,
+ skipAddingFilesFromTsConfig: true,
+ compilerOptions: { noLib: true, allowJs: false },
+ });
+ return project
+ .addSourceFileAtPath(join(here, censusFile))
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
+ .filter((call) => {
+ const expr = call.getExpression();
+ return Node.isIdentifier(expr) && expr.getText() === 'listAgentWriteSpineFiles';
+ })
+ .map((call) => call.getArguments()[0]?.getText() ?? '(no argument)');
+}
+
+describe('agent-write spine walk root coverage contract', () => {
+ it('keeps every applyAgentMarkdownWrite call site inside the walk root both censuses use', () => {
+ const consumerSrcRoots = listServerConsumerSrcRoots();
+ expect(
+ consumerSrcRoots.length,
+ `no ${SERVER_PACKAGE_NAME} consumer src roots derived from the workspace manifests`,
+ ).toBeGreaterThan(0);
+ const outsideCensus = consumerSrcRoots
+ .flatMap((srcRoot) =>
+ listAgentWriteSpineFiles(srcRoot).map((path) =>
+ relative(monorepoRoot, join(srcRoot, path)),
+ ),
+ )
+ .sort();
+ expect(outsideCensus).toEqual([]);
+ });
+
+ it('holds every spine census to that one walk root', () => {
+ const censusFiles = listCensusFiles();
+ expect(censusFiles.length).toBeGreaterThanOrEqual(2);
+ const offRoot = censusFiles
+ .flatMap((file) => spineWalkRootArguments(file).map((arg) => `${file}: ${arg}`))
+ .filter((entry) => !entry.endsWith(': here'));
+ expect(offRoot).toEqual([]);
+ });
+
+ it('flags a spine call site planted outside the walk root, and ignores its neighbour', () => {
+ const plantedRoot = mkdtempSync(join(tmpdir(), 'ok-agent-write-census-'));
+ try {
+ writeFileSync(
+ join(plantedRoot, 'stray-handler.ts'),
+ "applyAgentMarkdownWrite(session.dc.document, 'x', 'append');\n",
+ );
+ writeFileSync(join(plantedRoot, 'unrelated.ts'), 'export const unrelated = 1;\n');
+ expect(listAgentWriteSpineFiles(plantedRoot)).toEqual(['stray-handler.ts']);
+ } finally {
+ rmSync(plantedRoot, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 66905ba17..47648f52c 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -96,6 +96,14 @@ import { resolveBundledSkillDir } from './build-skill-zip.ts';
import { CommentIndex } from './comments/comment-index.ts';
import { CommentService } from './comments/comment-service.ts';
import { CommentThreadStore } from './comments/thread-store.ts';
+import {
+ CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,
+ CONCURRENT_OVERWRITE_REFUSED_TITLE,
+ CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+ ConcurrentOverwriteRefusedError,
+ logConcurrentOverwriteRefusal,
+} from './concurrent-overwrite-refused-error.ts';
import type { ConflictAuthority } from './conflict-authority.ts';
import {
DocInConflictError,
@@ -163,7 +171,12 @@ import { createSkillsCatalogCache } from './skills-catalog-cache.ts';
export { extractPageTitle } from './page-identity.ts';
import simpleGit from 'simple-git';
-import { parseAgentBodyFields, resolveAgentType } from './agent-id.ts';
+import {
+ parseAgentBodyFields,
+ type RawWriterId,
+ resolveAgentType,
+ UNIDENTIFIED_WRITER_ID,
+} from './agent-id.ts';
import {
applyRenameMap,
BacklinkIndexRequiredError,
@@ -3029,6 +3042,7 @@ export function createApiExtension(
*/
function extractAgentIdentity(body: Record<string, unknown>): {
rawAgentId: string | undefined;
+ suppliedWriterId: RawWriterId | undefined;
agentId: string;
agentName: string;
colorSeed: string;
@@ -3037,9 +3051,10 @@ export function createApiExtension(
label: string | undefined;
} {
const fields = parseAgentBodyFields(body);
- const agentId = fields.writerId ?? 'claude-1';
+ const agentId = fields.suppliedWriterId ?? UNIDENTIFIED_WRITER_ID;
return {
rawAgentId: fields.rawAgentId,
+ suppliedWriterId: fields.suppliedWriterId,
agentId,
agentName: fields.displayName,
colorSeed: fields.colorSeed ?? fields.rawAgentId ?? agentId,
@@ -3261,8 +3276,15 @@ export function createApiExtension(
const docName = resolveAlias(rawDocName);
// Identity extraction precedes every semantic error emission below (precedent #24).
- const { agentId, agentName, colorSeed, clientName, clientVersion, label } =
- extractAgentIdentity(body);
+ const {
+ agentId,
+ suppliedWriterId,
+ agentName,
+ colorSeed,
+ clientName,
+ clientVersion,
+ label,
+ } = extractAgentIdentity(body);
if (isSystemDoc(docName) || isConfigDoc(docName)) {
errorResponse(
@@ -3329,6 +3351,7 @@ export function createApiExtension(
: undefined,
undefined,
agentWriteLossDetect(session),
+ suppliedWriterId,
);
const changedBlocks =
@@ -3425,8 +3448,15 @@ export function createApiExtension(
async (_req, res, body) => {
try {
const linkPolicy = getLinkAdvisoryPolicy();
- const { agentId, agentName, colorSeed, clientName, clientVersion, label } =
- extractAgentIdentity(body);
+ const {
+ agentId,
+ suppliedWriterId,
+ agentName,
+ colorSeed,
+ clientName,
+ clientVersion,
+ label,
+ } = extractAgentIdentity(body);
const timestamp = new Date().toISOString();
@@ -3448,13 +3478,24 @@ export function createApiExtension(
type: BatchEntryError['type'],
title: string,
detail?: string,
+ extensions?: Record<string, unknown>,
): BatchErrorResult => ({
status: 'error',
docName,
- error: { type, title, ...(detail !== undefined ? { detail } : {}) },
+ error: { type, title, ...(detail !== undefined ? { detail } : {}), ...extensions },
});
const classifyEntryFailure = (docName: string, e: unknown): BatchErrorResult => {
+ if (e instanceof ConcurrentOverwriteRefusedError) {
+ logConcurrentOverwriteRefusal(e, 'agent-write-batch');
+ return entryError(
+ docName,
+ CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ CONCURRENT_OVERWRITE_REFUSED_TITLE,
+ CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,
+ { retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS },
+ );
+ }
if (e instanceof DocInConflictError) {
console.warn(
JSON.stringify({
@@ -3594,6 +3635,7 @@ export function createApiExtension(
entryEmbedResolver,
entryPrecomputed,
agentWriteLossDetect(session),
+ suppliedWriterId,
);
const changedBlocks =
diff --git a/packages/server/src/concurrent-overwrite-refused-error.test.ts b/packages/server/src/concurrent-overwrite-refused-error.test.ts
new file mode 100644
index 000000000..9adaf6554
--- /dev/null
+++ b/packages/server/src/concurrent-overwrite-refused-error.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, test } from 'vitest';
+import { CONCURRENT_REPLACE_WINDOW_MS } from './agent-sessions.ts';
+import { CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS } from './concurrent-overwrite-refused-error.ts';
+
+describe('the advertised retry bound', () => {
+ test('covers the guard window that decides when the refusal clears', () => {
+ expect(CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS * 1000).toBeGreaterThanOrEqual(
+ CONCURRENT_REPLACE_WINDOW_MS,
+ );
+ });
+});
diff --git a/packages/server/src/concurrent-overwrite-refused-error.ts b/packages/server/src/concurrent-overwrite-refused-error.ts
new file mode 100644
index 000000000..c1c450eac
--- /dev/null
+++ b/packages/server/src/concurrent-overwrite-refused-error.ts
@@ -0,0 +1,55 @@
+import type { ServerResponse } from 'node:http';
+import { stripDocExtension } from './doc-extensions.ts';
+import { errorResponse } from './http/error-response.ts';
+import { getLogger } from './logger.ts';
+import { incrementConcurrentOverwriteRefused } from './metrics.ts';
+
+export const CONCURRENT_OVERWRITE_REFUSED_TYPE = 'urn:ok:error:concurrent-overwrite-refused';
+export const CONCURRENT_OVERWRITE_REFUSED_TITLE = 'Concurrent overwrite refused.';
+export const CONCURRENT_OVERWRITE_REFUSED_DETAIL =
+ 'Another writer changed this document recently. Wait a few seconds and retry.';
+export const CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS = `${CONCURRENT_OVERWRITE_REFUSED_DETAIL} A write with position append or prepend is not refused.`;
+
+export const CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS = 3;
+
+export class ConcurrentOverwriteRefusedError extends Error {
+ readonly file: string;
+ override readonly name = 'ConcurrentOverwriteRefusedError' as const;
+
+ constructor(file: string) {
+ super(`Concurrent overwrite refused for ${file}`);
+ this.file = file;
+ }
+}
+
+export function logConcurrentOverwriteRefusal(
+ error: ConcurrentOverwriteRefusedError,
+ handler: string,
+): void {
+ incrementConcurrentOverwriteRefused();
+ getLogger('agent-write').warn(
+ {
+ event: 'concurrent-overwrite-write-refused',
+ handler,
+ 'doc.name': stripDocExtension(error.file),
+ },
+ 'concurrent replace refused before mutation',
+ );
+}
+
+export function respondConcurrentOverwriteRefused(
+ res: ServerResponse,
+ error: ConcurrentOverwriteRefusedError,
+ handler: string,
+): void {
+ logConcurrentOverwriteRefusal(error, handler);
+ errorResponse(res, 409, CONCURRENT_OVERWRITE_REFUSED_TYPE, CONCURRENT_OVERWRITE_REFUSED_TITLE, {
+ handler,
+ detail: CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,
+ extensions: {
+ file: error.file,
+ retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+ },
+ extraHeaders: { 'Retry-After': String(CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS) },
+ });
+}
diff --git a/packages/server/src/extract-actor-identity.ts b/packages/server/src/extract-actor-identity.ts
index 8e351d665..6d68dca4c 100644
--- a/packages/server/src/extract-actor-identity.ts
+++ b/packages/server/src/extract-actor-identity.ts
@@ -48,10 +48,10 @@ export function extractActorIdentity(
const fields = parseAgentBodyFields(body);
const principal = getPrincipal?.() ?? null;
- if (fields.rawAgentId !== undefined && fields.writerId !== undefined) {
+ if (fields.rawAgentId !== undefined && fields.suppliedWriterId !== undefined) {
return {
kind: 'agent',
- writerId: fields.writerId,
+ writerId: fields.suppliedWriterId,
displayName: fields.displayName,
colorSeed: fields.colorSeed ?? fields.rawAgentId,
clientName: fields.clientName,
diff --git a/packages/server/src/http/agent-write-routes.test.ts b/packages/server/src/http/agent-write-routes.test.ts
index b02fb9da4..5416dc972 100644
--- a/packages/server/src/http/agent-write-routes.test.ts
+++ b/packages/server/src/http/agent-write-routes.test.ts
@@ -2,6 +2,7 @@ import type { IncomingMessage } from 'node:http';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import { describe, expect, test } from 'vitest';
+import { sessionWriterId } from '../agent-id.ts';
import { AgentSessionManager } from '../agent-sessions.ts';
import { makeCaptureRes } from '../composition-rig.test-helper.ts';
import type { DocumentDurabilityState } from '../document-durability-state.ts';
@@ -22,6 +23,7 @@ function buildGroup(overrides: Partial<Deps> = {}) {
resolveAlias: (docName) => docName,
extractAgentIdentity: () => ({
rawAgentId: 'writer',
+ suppliedWriterId: sessionWriterId({ agentId: 'agent-writer' }),
agentId: 'agent-writer',
agentName: 'Writer',
colorSeed: 'writer',
diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.ts
index 5ba83829b..7cdbc8fc3 100644
--- a/packages/server/src/http/agent-write-routes.ts
+++ b/packages/server/src/http/agent-write-routes.ts
@@ -32,7 +32,7 @@ import { formatRollbackSubject } from '@inkeep/open-knowledge-core/shadow-repo-l
import { captureEffect } from '../activity-log.ts';
import { listAgentActivity, synthesizeVersionDiff } from '../agent-activity.ts';
import type { AgentFocusBroadcaster } from '../agent-focus.ts';
-import { resolveAgentType, validateAgentId } from '../agent-id.ts';
+import { type RawWriterId, resolveAgentType, validateAgentId } from '../agent-id.ts';
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import {
AgentSessionCapacityError,
@@ -55,6 +55,10 @@ import {
import { composeAndWriteRawBody, type PrecomputedParse, replaceRawBody } from '../bridge-intake.ts';
import type { BridgeDeriveLossReporter } from '../bridge-loss-detector.ts';
import { isConfigDoc, isSystemDoc, SYSTEM_DOC_NAME } from '../cc1-broadcast.ts';
+import {
+ ConcurrentOverwriteRefusedError,
+ respondConcurrentOverwriteRefused,
+} from '../concurrent-overwrite-refused-error.ts';
import type { ConflictAuthority } from '../conflict-authority.ts';
import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import {
@@ -142,6 +146,7 @@ export interface AgentWriteRouteDeps {
resolveAlias: (docName: string) => string;
extractAgentIdentity: (body: Record<string, unknown>) => {
rawAgentId: string | undefined;
+ suppliedWriterId: RawWriterId | undefined;
agentId: string;
agentName: string;
colorSeed: string;
@@ -296,8 +301,15 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
const effectiveDocName = requireNonEmptyDocName(body.docName, res, 'agent-write-md');
if (effectiveDocName === null) return;
const resolvedDocName = canonicalDocName(resolveAlias(effectiveDocName));
- const { agentId, agentName, colorSeed, clientName, clientVersion, label } =
- extractAgentIdentity(body);
+ const {
+ agentId,
+ suppliedWriterId,
+ agentName,
+ colorSeed,
+ clientName,
+ clientVersion,
+ label,
+ } = extractAgentIdentity(body);
if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {
errorResponse(
res,
@@ -371,6 +383,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
writeMdEmbedResolver,
writeMdPrecomputed,
agentWriteLossDetect(session),
+ suppliedWriterId,
);
const changedBlocks =
changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
@@ -497,6 +510,10 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
);
return;
}
+ if (e instanceof ConcurrentOverwriteRefusedError) {
+ respondConcurrentOverwriteRefused(res, e, 'agent-write-md');
+ return;
+ }
if (e instanceof FrontmatterMalformedError) {
respondFrontmatterMalformed(res, e, 'agent-write-md');
return;
@@ -781,8 +798,15 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
const effectivePatchDocName = requireNonEmptyDocName(body.docName, res, 'agent-patch');
if (effectivePatchDocName === null) return;
const docName = resolveAlias(effectivePatchDocName);
- const { agentId, agentName, colorSeed, clientName, clientVersion, label } =
- extractAgentIdentity(body);
+ const {
+ agentId,
+ suppliedWriterId,
+ agentName,
+ colorSeed,
+ clientName,
+ clientVersion,
+ label,
+ } = extractAgentIdentity(body);
if (isSystemDoc(docName) || isConfigDoc(docName)) {
errorResponse(
res,
@@ -910,6 +934,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroup
patchEmbedResolver,
patchPrecomputed,
agentWriteLossDetect(session),
+ suppliedWriterId,
);
const changedBlocks =
changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
diff --git a/packages/server/src/http/lint-write-routes.ts b/packages/server/src/http/lint-write-routes.ts
index e39035635..efd606075 100644
--- a/packages/server/src/http/lint-write-routes.ts
+++ b/packages/server/src/http/lint-write-routes.ts
@@ -16,6 +16,7 @@ import {
type ReLintFailure,
summarizeLintPluginFailures,
} from '@inkeep/open-knowledge-core';
+import { ANONYMOUS_WRITER_ID, sessionWriterId } from '../agent-id.ts';
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import {
AgentSessionCapacityError,
@@ -290,7 +291,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {
});
return;
}
- const agentId = actor.kind === 'anonymous' ? 'principal-anonymous' : actor.writerId;
+ const agentId = actor.kind === 'anonymous' ? ANONYMOUS_WRITER_ID : actor.writerId;
const agentName = actor.kind === 'anonymous' ? 'Anonymous' : actor.displayName;
const colorSeed = actor.kind === 'anonymous' ? agentId : actor.colorSeed;
const clientName = actor.kind === 'agent' ? actor.clientName : undefined;
@@ -349,6 +350,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {
mode: 'writing',
ts: Date.now(),
});
+ const suppliedWriterId = sessionWriterId(session);
session.dc.document.transact(() => {
applyAgentMarkdownWrite(
session.dc.document,
@@ -359,6 +361,7 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {
: undefined,
undefined,
agentWriteLossDetect(session),
+ suppliedWriterId,
);
}, session.origin);
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index e042b8038..db6fed53d 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -32,6 +32,7 @@ export {
type AgentSessionIdentity,
AgentSessionManager,
applyAgentMarkdownWrite,
+ CONCURRENT_REPLACE_WINDOW_MS,
colorFromSeed,
iconFromClientName,
MAX_AGENT_SESSIONS,
diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.ts
index de610f854..9f51184e7 100644
--- a/packages/server/src/mcp/tools/write.test.ts
+++ b/packages/server/src/mcp/tools/write.test.ts
@@ -3,6 +3,12 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { stripFrontmatter } from '@inkeep/open-knowledge-core';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import {
+ CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,
+ CONCURRENT_OVERWRITE_REFUSED_TITLE,
+ CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+} from '../../concurrent-overwrite-refused-error.ts';
import { ConfigSchema } from '../../config/schema.ts';
import { splitPayloadFrontmatter } from '../../payload-frontmatter.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
@@ -214,6 +220,88 @@ describe('write({ skill }) with bundle files — the per-file report reaches bot
});
});
+describe('write({ document }) relaying a concurrent-overwrite refusal', () => {
+ interface ToolResult {
+ content: Array<{ type: 'text'; text: string }>;
+ structuredContent?: Record<string, unknown>;
+ isError?: true;
+ }
+ type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;
+
+ let testServer: FetchTestServer;
+ let cwd: string;
+ let handler: Handler;
+
+ beforeAll(async () => {
+ testServer = await startFetchTestServer({
+ hostname: '127.0.0.1',
+ fetch(request) {
+ const { pathname } = new URL(request.url);
+ if (pathname === '/api/agent-write-md') {
+ return Response.json(
+ {
+ type: CONCURRENT_OVERWRITE_REFUSED_TYPE,
+ title: CONCURRENT_OVERWRITE_REFUSED_TITLE,
+ status: 409,
+ instance: 'urn:uuid:11111111-2222-4333-8444-555555555555',
+ detail: CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS,
+ file: 'notes/contended.md',
+ retryAfterSeconds: CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS,
+ },
+ {
+ status: 409,
+ headers: { 'Retry-After': String(CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS) },
+ },
+ );
+ }
+ return Response.json({ error: `unexpected route ${pathname}` }, { status: 500 });
+ },
+ });
+ cwd = mkdtempSync(join(tmpdir(), 'ok-write-concurrent-refusal-'));
+ mkdirSync(join(cwd, '.ok'), { recursive: true });
+
+ let captured: Handler | null = null;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, toolHandler: Handler) {
+ captured = toolHandler;
+ },
+ } as unknown as ServerInstance;
+ registerWrite(server, {
+ serverUrl: `http://127.0.0.1:${testServer.port}`,
+ config: ConfigSchema.parse({}),
+ resolveCwd: async () => cwd,
+ });
+ if (captured === null) throw new Error('write tool did not register');
+ handler = captured;
+ });
+
+ afterAll(() => {
+ testServer.stop();
+ rmSync(cwd, { recursive: true, force: true });
+ });
+
+ it('carries the retry bound into the single-doc error text', async () => {
+ const result = await handler({
+ document: { path: 'notes/contended', content: '# From B\n', position: 'replace' },
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toBe(
+ `Error: ${CONCURRENT_OVERWRITE_REFUSED_TITLE} (${CONCURRENT_OVERWRITE_REFUSED_DETAIL_WITH_POSITIONS}) Retry after ${CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS}s.`,
+ );
+ });
+
+ it('carries the retry bound into the batch per-entry error text', async () => {
+ const result = await handler({
+ documents: [{ path: 'notes/contended', content: '# From B\n', position: 'replace' }],
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain(
+ `Retry after ${CONCURRENT_OVERWRITE_RETRY_AFTER_SECONDS}s.`,
+ );
+ });
+});
describe('write — an asset upload whose request to the server fails', () => {
type AssetHandler = (args: Record<string, unknown>) => Promise<{
isError?: boolean;
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 6f414bd11..7f2b7b69d 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -85,7 +85,7 @@ import {
const BASE_DESCRIPTION = [
'Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).',
'',
- '- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.',
+ '- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. A replace is refused when another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which are never refused. Peers are told apart per MCP connection. Writers sharing one connection are not refused against each other; there is no `agentId` to send. The MCP connection records you as a peer, while your own recent write does not arm the refusal against your follow-up `replace`. A recent change from a connected editor refuses a `replace` too. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.',
'- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.',
'- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.',
'- `skill` — Create or overwrite an agent SKILL: reusable agent guidance you author in OK and `install` into your editors. A NEW skill lands at the project\'s default skill home (e.g. `.agents/skills/<name>/`); an existing one is edited at its real folder. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.',
@@ -315,10 +315,14 @@ async function writeOneDoc(
if (!result.ok) {
const detail =
typeof result.detail === 'string' && result.detail.length > 0 ? result.detail : '';
+ const retryAfter =
+ typeof result.retryAfterSeconds === 'number'
+ ? ` Retry after ${result.retryAfterSeconds}s.`
+ : '';
return {
docName,
ok: false,
- error: detail ? `${String(result.error)} (${detail})` : String(result.error),
+ error: `${detail ? `${String(result.error)} (${detail})` : String(result.error)}${retryAfter}`,
};
}
diff --git a/packages/server/src/metrics.test.ts b/packages/server/src/metrics.test.ts
index 354f338e8..dd6e05db0 100644
--- a/packages/server/src/metrics.test.ts
+++ b/packages/server/src/metrics.test.ts
@@ -7,6 +7,7 @@ import {
incrementBridgeMergeCheckpointCreated,
incrementBridgeMergeContentLoss,
incrementCollabSocketFilteredError,
+ incrementConcurrentOverwriteRefused,
incrementConflict,
incrementMapDrivenSpliceApplied,
incrementMapDrivenSpliceFallback,
@@ -83,6 +84,18 @@ describe('reconciliation metrics', () => {
expect(getMetrics().staleExternalWriteRefused).toBe(0);
});
+ test('concurrent-overwrite refusal counts on its own axis and resets', () => {
+ resetMetrics();
+ incrementConcurrentOverwriteRefused();
+ incrementConcurrentOverwriteRefused();
+ const metrics = getMetrics();
+ expect(metrics.concurrentOverwriteRefused).toBe(2);
+ expect(metrics.staleExternalWriteRefused).toBe(0);
+ expect(metrics.conflictCount).toBe(0);
+ resetMetrics();
+ expect(getMetrics().concurrentOverwriteRefused).toBe(0);
+ });
+
test('map-driven splice counters: applied increments and fallback is keyed by reason', () => {
resetMetrics();
incrementMapDrivenSpliceApplied();
diff --git a/packages/server/src/metrics.ts b/packages/server/src/metrics.ts
index b86224c96..246464c5e 100644
--- a/packages/server/src/metrics.ts
+++ b/packages/server/src/metrics.ts
@@ -18,6 +18,7 @@ export interface ReconciliationMetrics {
conflictCount: number;
reconcileInsertDedupSkipped: number;
staleExternalWriteRefused: number;
+ concurrentOverwriteRefused: number;
batchCount: number;
upstreamImportCount: number;
persistenceStoreRemovedDocCount: number;
@@ -132,6 +133,7 @@ const counters: ReconciliationMetrics = {
conflictCount: 0,
reconcileInsertDedupSkipped: 0,
staleExternalWriteRefused: 0,
+ concurrentOverwriteRefused: 0,
batchCount: 0,
upstreamImportCount: 0,
persistenceStoreRemovedDocCount: 0,
@@ -247,6 +249,10 @@ export function incrementStaleExternalWriteRefused(): void {
counters.staleExternalWriteRefused++;
}
+export function incrementConcurrentOverwriteRefused(): void {
+ counters.concurrentOverwriteRefused++;
+}
+
export function incrementBatch(): void {
counters.batchCount++;
}
@@ -654,6 +660,7 @@ export function resetMetrics(): void {
counters.conflictCount = 0;
counters.reconcileInsertDedupSkipped = 0;
counters.staleExternalWriteRefused = 0;
+ counters.concurrentOverwriteRefused = 0;
counters.batchCount = 0;
counters.upstreamImportCount = 0;
counters.persistenceStoreRemovedDocCount = 0;
diff --git a/packages/server/src/server-observers.ts b/packages/server/src/server-observers.ts
index 846b9b1e4..3cc444364 100644
--- a/packages/server/src/server-observers.ts
+++ b/packages/server/src/server-observers.ts
@@ -126,6 +126,11 @@ export const isPairedWriteOrigin = (origin: unknown): origin is PairedWriteOrigi
return ctx?.paired === true;
};
+const isConnectionOrigin = (origin: unknown): boolean =>
+ origin != null &&
+ typeof origin === 'object' &&
+ (origin as { source?: unknown }).source === 'connection';
+
export function shouldRethrowBridgeMergeLoss(env: NodeJS.ProcessEnv = process.env): boolean {
return env.NODE_ENV === 'test' || env.OK_RETHROW_BRIDGE_LOSS === '1';
}
@@ -281,6 +286,12 @@ export function getConvergedFragmentWitness(doc: Y.Doc): string | undefined {
return convergedFragmentWitnesses.get(doc)?.();
}
+const externalEditorRecencies = new WeakMap<Y.Doc, () => number | undefined>();
+
+export function getLastExternalEditorChangeMs(doc: Y.Doc): number | undefined {
+ return externalEditorRecencies.get(doc)?.();
+}
+
type ShadowAccessor = () => ShadowHandle | undefined;
type BranchAccessor = () => string;
@@ -782,6 +793,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
let xmlDirty = false;
let textDirty = false;
let lastExternalYtextChangeMs = 0;
+ let lastExternalEditorChangeMs = 0;
const deferGuardEnabled = opts.deferGuardEnabled !== false;
let lastConvergedFragmentMd = '';
@@ -1252,6 +1264,8 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
return;
}
+ if (isConnectionOrigin(transaction.origin)) lastExternalEditorChangeMs = Date.now();
+
xmlDirty = true;
fragmentMutatedSinceConverge = true;
};
@@ -1422,6 +1436,8 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
return;
}
+ if (isConnectionOrigin(transaction.origin)) lastExternalEditorChangeMs = Date.now();
+
lastExternalYtextChangeMs = Date.now();
textDirty = true;
};
@@ -1552,12 +1568,16 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
};
preDrainControllers.set(doc, preDrainController);
convergedFragmentWitnesses.set(doc, () => lastConvergedFragmentMd);
+ externalEditorRecencies.set(doc, () =>
+ lastExternalEditorChangeMs > 0 ? lastExternalEditorChangeMs : undefined,
+ );
return () => {
unregisterDirtyProbe();
detachQuiescence();
preDrainControllers.delete(doc);
convergedFragmentWitnesses.delete(doc);
+ externalEditorRecencies.delete(doc);
doc.off('afterAllTransactions', afterAll);
xmlFragment.unobserveDeep(observerA);
ytext.unobserve(observerB);