Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Keep agent writes made during a branch switch (PRD-9338) (#6203)

Andrew Mikofalvy6c7b5d911c4f
diff --git a/.changeset/prd-9338-agent-writes-during-branch-switch.md b/.changeset/prd-9338-agent-writes-during-branch-switch.md
new file mode 100644
index 000000000..0983d3499
--- /dev/null
+++ b/.changeset/prd-9338-agent-writes-during-branch-switch.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Agent edits made during a Git branch switch now wait up to 20 seconds for it to finish before applying. An edit whose save the switch drops within that wait returns a `branch-switched` error instead of reporting success.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 0670e8f5b..38e0651f1 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -128,6 +128,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 write that arrives while Git is updating the project's `HEAD` or index waits for that to finish and then applies to the checked-out content. That covers a branch switch, a commit, a merge or a reset, and also index-only activity such as `git add` or a `git status` that refreshes the index. Fetching from the remote during sync does not hold writes back; a disk save that sync deferred completes when sync finishes. A request waits at most 20 seconds in total, however many documents it writes. If a branch switch replaces a document whose disk save was still pending, the write returns `urn:ok:error:branch-switched` (409) and the edit was not saved. `POST /api/agent-write-batch` reports this per entry inside its `200` envelope. `restore_version` skips the wait before applying, but its confirmation of the disk save can still wait under the same cap, and it can return the same error. Re-read the document, then repeat the edit if it is still needed. If any of that Git activity is still running when the 20 seconds run out, the write applies anyway and its success response can arrive before the disk save, so that response does not confirm the edit is on disk.
+
A whole-document replace attempted while another writer changed the same document in the last few seconds returns `urn:ok:error:concurrent-overwrite-refused` (409): nothing was written, so there is no partial edit to undo. This is not tracked conflict state, so there is nothing to resolve. A single-document HTTP response carries `retryAfterSeconds` alongside a matching `Retry-After` header, and the `write` tool appends the same bound to its error text (`Retry after 3s.`). After whole-request schema validation succeeds, `POST /api/agent-write-batch` keeps its `200` success envelope; each concurrent-overwrite refusal carries the problem type and `retryAfterSeconds`, while sibling entries are unaffected. Invalid input instead rejects the whole request before processing. Wait that long and repeat the write, or use `position: "append"` or `"prepend"`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. Peer writers are distinguished by identity. Anyone supplying an `agentId` or `x-ok-connection-id` must use a stable value unique to one writer, containing only ASCII `[A-Za-z0-9_-]` characters and 1–64 characters long. A nonconforming `agentId` is discarded: `POST /api/agent-write-md` and `POST /api/agent-write-batch` then treat the caller as unidentified, while `POST /api/lint/fix` falls back to the project [principal](./what-open-knowledge-writes.mdx) when available. A nonconforming `x-ok-connection-id` is silently replaced with a minted identity. A `POST /api/agent-write-md` caller sends its `agentId` on every write. The MCP write tools declare no `agentId` field. OpenKnowledge mints an identity per MCP connection unless an MCP Streamable HTTP client forwards a valid `x-ok-connection-id` while creating the protocol session. Writers that share or reuse an identity share [writer attribution](./core-concepts.md#attribution-and-collaboration), the server-side write session, and undo history, and are not refused against each other; the server does not detect identity collisions. Having an identity records you as a peer, so a `replace` carrying a different identity is refused for the next few seconds, while your own recent write does not arm the refusal against your follow-up `replace`. A writer that has no identity of its own is never recorded as a peer, so it never arms the refusal against a later writer. That covers a `POST /api/agent-write-md` that omits `agentId`, and a `lint` fix that both omits `agentId` and runs on a project with no principal. A caller that sent no `agentId` is still refused its own `replace` when a writer that did send one changed the document in the last few seconds, because that caller cannot be shown to be the recorded writer. Two `POST /api/agent-write-md` callers that both omit `agentId` are never refused against each other, though a recent change from a connected editor still refuses both of them.
A body or frontmatter edit addressed to a path with no document returns `urn:ok:error:doc-not-found` (404) from `POST /api/agent-patch` and `POST /api/frontmatter-patch`: nothing was written or created, and the body carries `committed: false`. Paths are relative to the content root. The problem body lists up to three likely targets in `candidates` (a folder's hub document, or documents whose trailing path segments match), and the title names them. A find that misses inside an existing document is a different error, `urn:ok:error:target-not-found`.
diff --git a/knip.config.ts b/knip.config.ts
index 0004a763a..69344114d 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -149,15 +149,11 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: [
- 'yjs',
- ],
+ ignoreDependencies: ['yjs'],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/branch-switch-agent-write.test.ts b/packages/app/tests/integration/branch-switch-agent-write.test.ts
new file mode 100644
index 000000000..21d34e461
--- /dev/null
+++ b/packages/app/tests/integration/branch-switch-agent-write.test.ts
@@ -0,0 +1,229 @@
+import { execSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { ensureProjectGit } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { configureTestGitRepository } from '../../../../test-support/configure-git-fixture.test-helper.ts';
+import {
+ DerivedDocumentIndex,
+ type DerivedDocumentIndexBranchTransition,
+} from '../../../server/src/derived-document-index.ts';
+import { post } from './rename-rebinding.test-helper.ts';
+import {
+ createInspectableServer,
+ createTestClient,
+ type InspectableServer,
+ pollUntil,
+} from './test-harness';
+
+const RESPONSE_GRACE_MS = 3000;
+
+const cleanups: Array<() => Promise<void> | void> = [];
+
+afterEach(async () => {
+ while (cleanups.length > 0) {
+ await cleanups.pop()?.();
+ }
+});
+
+function git(cwd: string, args: string): string {
+ return execSync(`git ${args}`, {
+ cwd,
+ env: {
+ ...process.env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_AUTHOR_NAME: 'test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ },
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+}
+
+async function bootOnMainWithFeatureBranch(): Promise<{
+ contentDir: string;
+ server: InspectableServer;
+}> {
+ const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-branch-switch-agent-write-')));
+ cleanups.push(() => rmSync(contentDir, { recursive: true, force: true }));
+ await ensureProjectGit(contentDir);
+ configureTestGitRepository(contentDir);
+ git(contentDir, 'config user.name test');
+ git(contentDir, 'config user.email [email protected]');
+ writeFileSync(join(contentDir, 'notes.md'), '# Notes\n\nOn main.\n', 'utf-8');
+ writeFileSync(join(contentDir, 'other.md'), '# Other\n\nOn main.\n', 'utf-8');
+ git(contentDir, 'add notes.md other.md');
+ git(contentDir, 'commit -m main');
+ git(contentDir, 'checkout -b feature');
+ writeFileSync(join(contentDir, 'notes.md'), '# Notes\n\nOn feature.\n', 'utf-8');
+ writeFileSync(join(contentDir, 'other.md'), '# Other\n\nOn feature.\n', 'utf-8');
+ git(contentDir, 'add notes.md other.md');
+ git(contentDir, 'commit -m feature');
+ git(contentDir, 'checkout main');
+
+ const server = await createInspectableServer({
+ contentDir,
+ keepContentDir: true,
+ gitEnabled: true,
+ commitDebounceMs: 500,
+ });
+ cleanups.push(() => server.shutdown());
+
+ for (const docName of ['notes', 'other']) {
+ const client = await createTestClient(server.port, docName, { skipInvariantWatcher: true });
+ cleanups.push(() => client.cleanup());
+ await pollUntil(() => client.ytext.toString().includes('On main.'), 15_000, 50);
+ }
+ return { contentDir, server };
+}
+
+function serverText(server: InspectableServer, docName: string): string {
+ return server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';
+}
+
+function readNotes(contentDir: string): string {
+ return readFileSync(join(contentDir, 'notes.md'), 'utf-8');
+}
+
+async function settledWithin<T>(promise: Promise<T>, ms: number): Promise<boolean> {
+ return Promise.race([promise.then(() => true), wait(ms).then(() => false)]);
+}
+
+describe('agent writes during a git branch switch', () => {
+ test.runIf(process.platform !== 'win32')(
+ 'a patch sent after the reset but before the switch settles is written to the new branch',
+ async () => {
+ let releaseSettle: () => void = () => {};
+ const settleHeld = new Promise<void>((resolve) => {
+ releaseSettle = resolve;
+ });
+ const settleBranchFromDisk = DerivedDocumentIndex.prototype.settleBranchFromDisk;
+ const settleSpy = vi
+ .spyOn(DerivedDocumentIndex.prototype, 'settleBranchFromDisk')
+ .mockImplementation(async function (
+ this: DerivedDocumentIndex,
+ transition: DerivedDocumentIndexBranchTransition,
+ ) {
+ await settleHeld;
+ return settleBranchFromDisk.call(this, transition);
+ });
+ cleanups.push(() => {
+ releaseSettle();
+ settleSpy.mockRestore();
+ });
+
+ const { contentDir, server } = await bootOnMainWithFeatureBranch();
+
+ git(contentDir, 'checkout feature');
+ await pollUntil(
+ () =>
+ settleSpy.mock.calls.length > 0 && serverText(server, 'notes').includes('On feature.'),
+ 20_000,
+ 50,
+ 'the branch switch to reset the open document and reach the held settle',
+ );
+ expect(server.instance.durabilityState.isBatchInProgress()).toBe(true);
+
+ const patch = post(server.port, '/api/agent-patch', {
+ docName: 'notes',
+ find: 'On feature.',
+ replace: 'Edited on feature.',
+ agentId: 'branch-switch-probe',
+ });
+ const ackedWhileSwitching = await settledWithin(patch, RESPONSE_GRACE_MS);
+
+ releaseSettle();
+ const response = await patch;
+ expect(response.status).toBe(200);
+ await pollUntil(
+ () => !server.instance.durabilityState.isBatchInProgress(),
+ 20_000,
+ 50,
+ 'the branch switch batch to end',
+ );
+ await pollUntil(
+ () => !server.instance.durabilityState.isWriteAdmissionHeld(),
+ 5_000,
+ 50,
+ 'the branch switch to release write admission',
+ );
+ await pollUntil(
+ () => readNotes(contentDir).includes('Edited on feature.'),
+ 15_000,
+ 100,
+ ).catch(() => {});
+
+ expect(readNotes(contentDir)).toContain('Edited on feature.');
+ expect(ackedWhileSwitching).toBe(false);
+
+ const holds = vi.spyOn(server.instance.durabilityState, 'holdWriteAdmission');
+ cleanups.push(() => holds.mockRestore());
+ writeFileSync(join(contentDir, 'staged.txt'), 'staged\n', 'utf-8');
+ git(contentDir, 'add staged.txt');
+ await pollUntil(
+ () => holds.mock.calls.length > 0,
+ 15_000,
+ 20,
+ 'the index change to start a batch',
+ );
+ await pollUntil(
+ () => !server.instance.durabilityState.isWriteAdmissionHeld(),
+ 10_000,
+ 50,
+ 'the index-change batch to release write admission',
+ );
+ },
+ 90_000,
+ );
+
+ test.runIf(process.platform !== 'win32')(
+ 'a write whose deferred store is discarded by the switch is not acknowledged as saved',
+ async () => {
+ const { contentDir, server } = await bootOnMainWithFeatureBranch();
+ const durability = server.instance.durabilityState;
+ const notes = server.instance.hocuspocus.documents.get('notes');
+ if (!notes) throw new Error('notes was not loaded');
+ const source = notes.getText('source');
+ let holding = false;
+ const holdBatchOnceWritten = (): void => {
+ if (holding || !source.toString().includes('Appended before the switch.')) return;
+ holding = true;
+ durability.setBatchInProgress(true);
+ cleanups.push(durability.holdWriteAdmission());
+ };
+ source.observe(holdBatchOnceWritten);
+ cleanups.push(() => source.unobserve(holdBatchOnceWritten));
+
+ const write = post(server.port, '/api/agent-write-md', {
+ docName: 'notes',
+ markdown: 'Appended before the switch.\n',
+ position: 'append',
+ agentId: 'branch-switch-probe',
+ });
+ await pollUntil(() => durability.isBatchInProgress(), 15_000, 20, 'the write to land');
+ const ackedBeforeSwitch = await settledWithin(write, RESPONSE_GRACE_MS);
+
+ git(contentDir, 'checkout feature');
+ const response = await write;
+ await pollUntil(
+ () =>
+ !durability.isBatchInProgress() && serverText(server, 'notes').includes('On feature.'),
+ 20_000,
+ 50,
+ 'the branch switch to finish',
+ );
+
+ expect(response.status).toBe(409);
+ expect((response.body as { type?: string } | null)?.type).toBe(
+ 'urn:ok:error:branch-switched',
+ );
+ expect(ackedBeforeSwitch).toBe(false);
+ expect(readNotes(contentDir)).not.toContain('Appended before the switch.');
+ },
+ 90_000,
+ );
+});
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 4549c74b3..a50b00123 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 4fc2c11f9..6fcdc23f2 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 9f2f6feb6..40b5cdfd6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 2a085742b..93666af70 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 878d5196b..867598d34 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 4ada3cf26..0970ac12f 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index cbe2b705f..b632185e1 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,4 +1,3 @@
-
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index 89bc9b4d9..c530ce4ba 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index a78aeb0e4..d3767adc9 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,4 +1,3 @@
-
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index e7cc69c3f..b076f955c 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 9ddcd0730..7935e35f8 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index ffd8fce06..e7e63f43d 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.ts
index 07cf920ce..e45c45ea5 100644
--- a/packages/core/src/handoff/urn-ipc-registry.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.ts
@@ -61,6 +61,7 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>([
'urn:ok:error:stale-external-write',
'urn:ok:error:store-refused',
'urn:ok:error:doc-removed',
+ 'urn:ok:error:branch-switched',
'urn:ok:error:doc-in-conflict',
'urn:ok:error:no-conflict-tracked',
'urn:ok:error:unresolved-conflict-markers',
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fb0ba5a7c..fc267cbea 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index 92b126044..6d446a981 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -85,6 +85,7 @@ export const ProblemTypeSchema = z.enum([
'urn:ok:error:stale-external-write',
'urn:ok:error:store-refused',
'urn:ok:error:doc-removed',
+ 'urn:ok:error:branch-switched',
'urn:ok:error:doc-not-found',
'urn:ok:error:doc-already-exists',
'urn:ok:error:doc-not-open',
diff --git a/packages/server/src/agent-sessions.test.ts b/packages/server/src/agent-sessions.test.ts
index 0814b8309..18b879aae 100644
--- a/packages/server/src/agent-sessions.test.ts
+++ b/packages/server/src/agent-sessions.test.ts
@@ -24,7 +24,9 @@ import { ConcurrentOverwriteRefusedError } from './concurrent-overwrite-refused-
import { bindConflictAuthority } from './conflict-authority.ts';
import { DocInConflictError } from './conflict-errors.ts';
import { _resetDocExtensionsForTests, registerDocExtension } from './doc-extensions.ts';
+import { DocumentDurabilityState, WRITE_WAIT_BUDGET_MS } from './document-durability-state.ts';
import { __resetFrontmatterTelemetryForTests } from './frontmatter-telemetry.ts';
+import { getLogger } from './logger.ts';
function createMockHocuspocus() {
const openedDocs: string[] = [];
@@ -85,6 +87,7 @@ beforeEach(() => {
});
afterEach(async () => {
+ vi.useRealTimers();
await manager.closeAll();
});
@@ -108,6 +111,76 @@ describe('getSession — composite key (docName + agentId)', () => {
expect(mockHocuspocus.openedDocs).toEqual(['doc.md']);
});
+ test('holds new and cached sessions until write admission opens', async () => {
+ let admissions = 0;
+ let open: () => void = () => {};
+ let gate = Promise.resolve(true);
+ manager = new AgentSessionManager(mockHocuspocus as never, {
+ awaitWriteAdmission: () => {
+ admissions++;
+ return gate;
+ },
+ });
+ const first = await manager.getSession('doc.md', 'agent-alice');
+ gate = new Promise<boolean>((resolve) => {
+ open = () => resolve(true);
+ });
+
+ const settled: string[] = [];
+ const cached = manager.getSession('doc.md', 'agent-alice').then((session) => {
+ settled.push('cached');
+ return session;
+ });
+ const fresh = manager.getSession('other.md', 'agent-alice').then(() => {
+ settled.push('fresh');
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(settled).toEqual([]);
+ expect(mockHocuspocus.openedDocs).toEqual(['doc.md']);
+
+ open();
+ expect(await cached).toBe(first);
+ await fresh;
+ expect(settled.sort()).toEqual(['cached', 'fresh']);
+ expect(mockHocuspocus.openedDocs).toEqual(['doc.md', 'other.md']);
+ expect(admissions).toBe(3);
+ });
+
+ test('admits the write once the bound elapses while admission is still held, with a warning', async () => {
+ vi.useFakeTimers();
+ const warn = vi.spyOn(getLogger('agent-sessions'), 'warn');
+ try {
+ const durabilityState = new DocumentDurabilityState();
+ durabilityState.holdWriteAdmission();
+ manager = new AgentSessionManager(mockHocuspocus as never, {
+ awaitWriteAdmission: () => durabilityState.whenWriteAdmitted(),
+ });
+
+ let opened = false;
+ const pending = manager.getSession('doc.md', 'agent-alice').then((session) => {
+ opened = true;
+ return session;
+ });
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(opened).toBe(false);
+ expect(mockHocuspocus.openedDocs).toEqual([]);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const session = await pending;
+
+ expect(session.docName).toBe('doc.md');
+ expect(mockHocuspocus.openedDocs).toEqual(['doc.md']);
+ expect(durabilityState.isWriteAdmissionHeld()).toBe(true);
+ expect(warn).toHaveBeenCalledWith(
+ { docName: 'doc.md', waitedMs: WRITE_WAIT_BUDGET_MS },
+ expect.stringContaining('admission wait'),
+ );
+ } finally {
+ warn.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
test('creates a session on first call', async () => {
await manager.getSession('doc.md', 'agent-alice');
expect(manager.hasSession('doc.md', 'agent-alice')).toBe(true);
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index 9ce3289e1..c96dad69f 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -568,6 +568,7 @@ export class AgentSessionManager {
private readonly minEvictableIdleMs: number;
private bridgeLossReporter?: BridgeDeriveLossReporter;
private readonly assertDocumentScope?: (docName: string) => void;
+ private readonly awaitWriteAdmission?: () => Promise<boolean>;
private evictions = 0;
constructor(
@@ -577,6 +578,7 @@ export class AgentSessionManager {
minEvictableIdleMs?: number;
bridgeLossReporter?: BridgeDeriveLossReporter;
assertDocumentScope?: (docName: string) => void;
+ awaitWriteAdmission?: () => Promise<boolean>;
} = {},
) {
this.hocuspocus = hocuspocus;
@@ -584,6 +586,7 @@ export class AgentSessionManager {
this.minEvictableIdleMs = options.minEvictableIdleMs ?? MIN_EVICTABLE_IDLE_MS;
this.bridgeLossReporter = options.bridgeLossReporter;
this.assertDocumentScope = options.assertDocumentScope;
+ this.awaitWriteAdmission = options.awaitWriteAdmission;
}
public attachBridgeLossReporter(reporter: BridgeDeriveLossReporter): void {
@@ -673,6 +676,15 @@ export class AgentSessionManager {
throw new Error(`Cannot create agent session for reserved doc: ${docName}`);
}
this.assertDocumentScope?.(docName);
+ if (this.awaitWriteAdmission) {
+ const waitStarted = Date.now();
+ if (!(await this.awaitWriteAdmission())) {
+ log.warn(
+ { docName, waitedMs: Date.now() - waitStarted },
+ '[agent-session] git batch still in progress after the admission wait; admitting the write',
+ );
+ }
+ }
const key = this.sessionKey(docName, agentId);
const existing = this.sessions.get(key);
diff --git a/packages/server/src/api-agent-write-batch-persistence-failure.test.ts b/packages/server/src/api-agent-write-batch-persistence-failure.test.ts
index bd723372c..0c696128b 100644
--- a/packages/server/src/api-agent-write-batch-persistence-failure.test.ts
+++ b/packages/server/src/api-agent-write-batch-persistence-failure.test.ts
@@ -19,6 +19,7 @@ import { createApiExtension } from './api-extension.ts';
import {
DocumentDurabilityState,
OK_DOC_REMOVED,
+ OK_STORE_DISCARDED,
OK_STORE_REFUSED,
} from './document-durability-state.ts';
@@ -157,4 +158,26 @@ describe('agent-write-batch — store-refused flush failure rendering', () => {
expect(results[0]?.status).toBe('error');
expect(results[0]?.error?.type).toBe('urn:ok:error:doc-removed');
});
+
+ test('a store discarded by a branch switch reports branch-switched on the batch endpoint', async () => {
+ const docName = 'batch-branch-switched';
+ durabilityState.recordStoreFailure(docName, {
+ code: OK_STORE_DISCARDED,
+ message: `A Git branch switch discarded the pending save of ${docName}`,
+ });
+
+ const response = await postBatch({
+ docs: [{ docName, markdown: '# Batch branch switched\n\nBody.\n', position: 'replace' }],
+ agentId: 'claude-1',
+ agentName: 'Claude',
+ });
+
+ expect(response.status).toBe(200);
+ const { results } = JSON.parse(response.body) as {
+ results: Array<{ status: string; error?: { type: string; detail?: string } }>;
+ };
+ expect(results[0]?.status).toBe('error');
+ expect(results[0]?.error?.type).toBe('urn:ok:error:branch-switched');
+ expect(results[0]?.error?.detail).toContain('Re-read');
+ });
});
diff --git a/packages/server/src/api-agent-write-deferred-store-wait.test.ts b/packages/server/src/api-agent-write-deferred-store-wait.test.ts
new file mode 100644
index 000000000..4fdc4cb17
--- /dev/null
+++ b/packages/server/src/api-agent-write-deferred-store-wait.test.ts
@@ -0,0 +1,264 @@
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import { Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { AgentSessionManager } from './agent-sessions.ts';
+import {
+ createApiExtension,
+ createDerivedDocumentIndexApiPortStub,
+} from './api-extension.test-helper.ts';
+import { DocumentDurabilityState, WRITE_WAIT_BUDGET_MS } from './document-durability-state.ts';
+
+interface CapturedResponse {
+ status: number;
+ body: string;
+}
+
+function makeJsonPostReq(url: string, body: unknown): IncomingMessage {
+ const readable = Readable.from(Buffer.from(JSON.stringify(body))) as unknown as IncomingMessage;
+ readable.method = 'POST';
+ readable.url = url;
+ readable.headers = { host: 'localhost', 'content-type': 'application/json' };
+ return readable;
+}
+
+function makeRes(): { res: ServerResponse; captured: CapturedResponse } {
+ const captured: CapturedResponse = { status: 0, body: '' };
+ const res = {
+ writeHead(status: number) {
+ captured.status = status;
+ },
+ end(body?: string) {
+ captured.body = body ?? '';
+ },
+ } as unknown as ServerResponse;
+ return { res, captured };
+}
+
+let projectDir: string;
+let contentDir: string;
+let hocuspocus: Hocuspocus;
+let sessionManager: AgentSessionManager;
+let durabilityState: DocumentDurabilityState;
+
+beforeEach(() => {
+ projectDir = mkdtempSync(join(tmpdir(), 'ok-deferred-store-wait-'));
+ contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ hocuspocus = new Hocuspocus({ quiet: true });
+ sessionManager = new AgentSessionManager(hocuspocus);
+ durabilityState = new DocumentDurabilityState();
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ await sessionManager.closeAll();
+ rmSync(projectDir, { recursive: true, force: true });
+});
+
+async function postAgentWrite(docName: string): Promise<CapturedResponse> {
+ return post('/api/agent-write', {
+ docName,
+ content: 'Edited during the switch.',
+ agentId: 'claude-1',
+ agentName: 'Claude',
+ });
+}
+
+async function postAgentWriteBatch(docNames: string[]): Promise<CapturedResponse> {
+ return post('/api/agent-write-batch', {
+ docs: docNames.map((docName) => ({
+ docName,
+ markdown: '# Edited during the switch\n',
+ position: 'replace',
+ })),
+ agentId: 'claude-1',
+ agentName: 'Claude',
+ });
+}
+
+async function post(url: string, body: unknown): Promise<CapturedResponse> {
+ const ext = createApiExtension({
+ hocuspocus,
+ durabilityState,
+ sessionManager,
+ contentDir,
+ serverInstanceId: 'test-instance',
+ getFileIndex: () => new Map(),
+ derivedDocumentIndex: createDerivedDocumentIndexApiPortStub(),
+ });
+ const req = makeJsonPostReq(url, body);
+ const { res, captured } = makeRes();
+ await (
+ ext as unknown as {
+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
+ }
+ ).onRequest({ request: req, response: res });
+ return captured;
+}
+
+function whenFlushStartsWaiting(): Promise<void> {
+ const started = Promise.withResolvers<void>();
+ const awaitOutcome = durabilityState.awaitDeferredStoreOutcome.bind(durabilityState);
+ vi.spyOn(durabilityState, 'awaitDeferredStoreOutcome').mockImplementation(
+ (docName, timeoutMs) => {
+ const outcome = awaitOutcome(docName, timeoutMs);
+ started.resolve();
+ return outcome;
+ },
+ );
+ return started.promise;
+}
+
+function unsettledEvents(warn: { mock: { calls: unknown[][] } }): Array<Record<string, unknown>> {
+ return warn.mock.calls.flatMap(([line]) => {
+ if (typeof line !== 'string' || !line.startsWith('{')) return [];
+ const parsed = JSON.parse(line) as Record<string, unknown>;
+ return parsed.event === 'agent-write-deferred-store-unsettled' ? [parsed] : [];
+ });
+}
+
+describe('agent-write flush: bounded wait for a deferred store', () => {
+ test('acknowledges once the bound elapses with the store still deferred, and reports it', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const docName = 'held-store';
+ durabilityState.holdWriteAdmission();
+ durabilityState.openDeferredStore(docName);
+ const flushWaiting = whenFlushStartsWaiting();
+
+ let answered = false;
+ const responding = postAgentWrite(docName).then((response) => {
+ answered = true;
+ return response;
+ });
+ await flushWaiting;
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(answered).toBe(false);
+ expect(unsettledEvents(warn)).toEqual([]);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const response = await responding;
+
+ expect(response.status).toBe(200);
+ expect(unsettledEvents(warn)).toEqual([
+ expect.objectContaining({
+ event: 'agent-write-deferred-store-unsettled',
+ 'doc.name': docName,
+ }),
+ ]);
+ });
+
+ test('answers a batch write within one budget when a branch switch outlives it', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await sessionManager.closeAll();
+ sessionManager = new AgentSessionManager(hocuspocus, {
+ awaitWriteAdmission: () => durabilityState.whenWriteAdmitted(),
+ });
+ durabilityState.holdWriteAdmission();
+ const docNames = ['held-a', 'held-b', 'held-c'];
+ for (const docName of docNames) durabilityState.openDeferredStore(docName);
+
+ let answered = false;
+ const responding = postAgentWriteBatch(docNames).then((response) => {
+ answered = true;
+ return response;
+ });
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(answered).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const response = await responding;
+
+ expect(response.status).toBe(200);
+ const { results } = JSON.parse(response.body) as { results: Array<{ status: string }> };
+ expect(results.map((result) => result.status)).toEqual(['written', 'written', 'written']);
+ });
+
+ test('answers a native-route write within one budget when a branch switch outlives it', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await sessionManager.closeAll();
+ sessionManager = new AgentSessionManager(hocuspocus, {
+ awaitWriteAdmission: () => durabilityState.whenWriteAdmitted(),
+ });
+ durabilityState.holdWriteAdmission();
+ const docName = 'held-native';
+ durabilityState.openDeferredStore(docName);
+
+ let answered = false;
+ const responding = post('/api/agent-write-md', {
+ docName,
+ markdown: '# Edited during the switch\n',
+ position: 'replace',
+ agentId: 'claude-1',
+ }).then((response) => {
+ answered = true;
+ return response;
+ });
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(answered).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const response = await responding;
+
+ expect(response.status).toBe(200);
+ });
+
+ test('does not hold a write behind a Git operation that cannot discard it', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await sessionManager.closeAll();
+ sessionManager = new AgentSessionManager(hocuspocus, {
+ awaitWriteAdmission: () => durabilityState.whenWriteAdmitted(),
+ });
+ const docName = 'synced-store';
+ durabilityState.setBatchInProgress(true);
+ durabilityState.openDeferredStore(docName);
+
+ const response = await postAgentWrite(docName);
+
+ expect(response.status).toBe(200);
+ expect(unsettledEvents(warn)).toEqual([]);
+ });
+
+ test('reports a deferred store that failed instead of acknowledging it', async () => {
+ const docName = 'failed-store';
+ durabilityState.holdWriteAdmission();
+ const deferral = durabilityState.openDeferredStore(docName);
+ const flushWaiting = whenFlushStartsWaiting();
+
+ const responding = postAgentWrite(docName);
+ await flushWaiting;
+ deferral.settle({ kind: 'failed', failure: { code: 'EACCES', message: 'permission denied' } });
+ const response = await responding;
+
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(response.body).toContain('failed to persist to disk (EACCES): permission denied');
+ });
+
+ test('still refuses with branch-switched when the discard lands within the bound', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const docName = 'discarded-store';
+ durabilityState.holdWriteAdmission();
+ const deferral = durabilityState.openDeferredStore(docName);
+ const flushWaiting = whenFlushStartsWaiting();
+
+ const responding = postAgentWrite(docName);
+ await flushWaiting;
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ deferral.settle({ kind: 'discarded' });
+ const response = await responding;
+
+ expect(response.status).toBe(409);
+ expect((JSON.parse(response.body) as { type: string }).type).toBe(
+ 'urn:ok:error:branch-switched',
+ );
+ expect(unsettledEvents(warn)).toEqual([]);
+ });
+});
diff --git a/packages/server/src/api-extension.persistence-failure.test.ts b/packages/server/src/api-extension.persistence-failure.test.ts
index a36bb79cf..59506af6a 100644
--- a/packages/server/src/api-extension.persistence-failure.test.ts
+++ b/packages/server/src/api-extension.persistence-failure.test.ts
@@ -1,7 +1,11 @@
import type { ServerResponse } from 'node:http';
import { describe, expect, test } from 'vitest';
import { respondPersistenceFailure } from './api-extension.ts';
-import { OK_STORE_REFUSED, type StoreFailure } from './document-durability-state.ts';
+import {
+ OK_STORE_DISCARDED,
+ OK_STORE_REFUSED,
+ type StoreFailure,
+} from './document-durability-state.ts';
function makeMockRes() {
const writeHeadCalls: Array<{ status: number; headers: Record<string, string> }> = [];
@@ -60,3 +64,21 @@ describe('respondPersistenceFailure — store-refused', () => {
expect(body.type).not.toBe('urn:ok:error:store-refused');
});
});
+
+describe('respondPersistenceFailure: store discarded by a branch switch', () => {
+ test('an OK_STORE_DISCARDED failure renders a 409 telling the agent the edit was not saved', () => {
+ const { res, writeHeadCalls, endCalls } = makeMockRes();
+ const failure: StoreFailure = {
+ code: OK_STORE_DISCARDED,
+ message: 'A Git branch switch discarded the pending save of notes',
+ };
+
+ respondPersistenceFailure(res, failure, 'agent-patch');
+
+ expect(writeHeadCalls[0]?.status).toBe(409);
+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;
+ expect(body.type).toBe('urn:ok:error:branch-switched');
+ expect(String(body.title)).toContain('not saved');
+ expect(String(body.detail)).toContain('Re-read');
+ });
+});
diff --git a/packages/server/src/api-extension.test-helper.ts b/packages/server/src/api-extension.test-helper.ts
index 66a3f0303..725909503 100644
--- a/packages/server/src/api-extension.test-helper.ts
+++ b/packages/server/src/api-extension.test-helper.ts
@@ -255,6 +255,7 @@ export function createApiExtension(
> &
LegacyIndexOptions & {
conflicts?: ApiExtensionOptions['conflicts'];
+ durabilityState?: DocumentDurabilityState;
derivedDocumentIndex?: DerivedDocumentIndexApiPort;
signalChannel?: LegacySignalChannel;
getProjectConfigEpoch?: () => number;
@@ -265,6 +266,7 @@ export function createApiExtension(
backlinkIndex,
tagIndex,
derivedDocumentIndex,
+ durabilityState = new DocumentDurabilityState(),
getProjectConfigEpoch = () => 0,
getLinkAdvisoryPolicy = () => ({
links: DEFAULT_LINKS_VALIDATION,
@@ -280,7 +282,7 @@ export function createApiExtension(
conflicts:
options.conflicts ??
createTestConflictAuthority(options.projectDir ?? options.contentDir, options.contentDir),
- durabilityState: new DocumentDurabilityState(),
+ durabilityState,
derivedDocumentIndex:
derivedDocumentIndex ??
createLegacyDerivedIndexPort(
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 5cf92b54a..9f134cd06 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -224,9 +224,11 @@ import {
stripDocExtension,
} from './doc-extensions.ts';
import {
+ assertNeverDeferredStoreWait,
type DocumentDurabilityState,
OK_DOC_REMOVED,
OK_PATH_UNRESOLVABLE,
+ OK_STORE_DISCARDED,
OK_STORE_REFUSED,
type StoreFailure,
} from './document-durability-state.ts';
@@ -1441,6 +1443,14 @@ function pathFaultProblem(failure: StoreFailure) {
} satisfies BatchEntryError;
}
+function discardedStoreProblem(failure: StoreFailure) {
+ return {
+ type: 'urn:ok:error:branch-switched' as const,
+ title: 'Edit not saved: the Git branch changed before it reached disk.',
+ detail: `${failure.message}. The document now shows the checked-out branch. Re-read it, then repeat the edit if it is still needed.`,
+ } satisfies BatchEntryError;
+}
+
function refusedStoreProblem(failure: StoreFailure) {
return {
type: 'urn:ok:error:store-refused' as const,
@@ -1465,6 +1475,11 @@ export function respondPersistenceFailure(
errorResponse(res, 409, type, title, { handler, detail });
return;
}
+ if (failure.code === OK_STORE_DISCARDED) {
+ const { type, title, detail } = discardedStoreProblem(failure);
+ errorResponse(res, 409, type, title, { handler, detail });
+ return;
+ }
if (failure.code === OK_PATH_UNRESOLVABLE) {
const { type, title, detail } = pathFaultProblem(failure);
errorResponse(res, 400, type, title, { handler, detail });
@@ -1491,7 +1506,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
async function dispatchMutation(operation: () => Promise<void>, pathname: string): Promise<void> {
if (closingMutations)
throw new ServerMutationShuttingDownError(pathname.startsWith('/api/local-op/'));
- const task = operation();
+ const task = durabilityState.runWithinWriteWaitBudget(operation);
pendingMutations.add(task);
try {
await task;
@@ -1899,6 +1914,44 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
durabilityState.markAgentWriteStore(docName);
await hocuspocus.debouncer.executeNow(debounceId);
}
+ const deferredWaitStarted = Date.now();
+ const deferredWait = await durabilityState.awaitDeferredStoreOutcome(docName);
+ switch (deferredWait?.kind) {
+ case undefined:
+ case 'completed':
+ break;
+ case 'discarded':
+ return {
+ kind: 'failure',
+ failure: {
+ code: OK_STORE_DISCARDED,
+ message: `A Git branch switch discarded the pending save of ${docName}`,
+ },
+ };
+ case 'failed':
+ return {
+ kind: 'failure',
+ failure: durabilityState.takeStoreFailure(docName) ?? deferredWait.failure,
+ };
+ case 'unsettled': {
+ const waitedMs = Date.now() - deferredWaitStarted;
+ console.warn(
+ JSON.stringify({
+ event: 'agent-write-deferred-store-unsettled',
+ 'doc.name': docName,
+ waitedMs,
+ timestamp: new Date().toISOString(),
+ }),
+ );
+ log.warn(
+ { docName, waitedMs },
+ '[agent-write] deferred store still pending after the wait; acknowledging before it reaches disk',
+ );
+ break;
+ }
+ default:
+ assertNeverDeferredStoreWait(deferredWait);
+ }
const failure = durabilityState.takeStoreFailure(docName);
if (failure) return { kind: 'failure', failure };
if (durabilityState.takeStaleExternalWriteFreeze(docName)) {
@@ -3959,6 +4012,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
flushErrors.set(p.docName, pathFaultProblem(flushOutcome.failure));
} else if (flushOutcome.failure.code === OK_STORE_REFUSED) {
flushErrors.set(p.docName, refusedStoreProblem(flushOutcome.failure));
+ } else if (flushOutcome.failure.code === OK_STORE_DISCARDED) {
+ flushErrors.set(p.docName, discardedStoreProblem(flushOutcome.failure));
} else {
const reason = classifyUploadErrno({
code: flushOutcome.failure.code,
diff --git a/packages/server/src/document-durability-state.test.ts b/packages/server/src/document-durability-state.test.ts
index 196aab7bc..f06982fb4 100644
--- a/packages/server/src/document-durability-state.test.ts
+++ b/packages/server/src/document-durability-state.test.ts
@@ -25,6 +25,7 @@ import {
DocumentDurabilityState,
DocumentDurabilityStateError,
type StorePublishOutcome,
+ WRITE_WAIT_BUDGET_MS,
} from './document-durability-state.ts';
import * as tracedFs from './fs-traced.ts';
import { getLogger } from './logger.ts';
@@ -67,7 +68,7 @@ describe('DocumentDurabilityState', () => {
expect(state.getReconciledBase('doc')).toBe('feature bytes');
});
- test('isolates every owned coordination channel between instances', () => {
+ test('isolates every owned coordination channel between instances', async () => {
const first = new DocumentDurabilityState();
const second = new DocumentDurabilityState();
first.setReconciledBase('doc', 'first');
@@ -76,6 +77,7 @@ describe('DocumentDurabilityState', () => {
first.markAgentWriteStore('doc');
first.recordStoreFailure('doc', { code: 'ENOSPC', message: 'full' });
first.recordStoreDivergence('doc');
+ first.openDeferredStore('doc');
expect(second.getReconciledBase('doc')).toBeUndefined();
expect(second.isBatchInProgress()).toBe(false);
@@ -83,6 +85,155 @@ describe('DocumentDurabilityState', () => {
expect(second.consumeAgentWriteStore('doc')).toBe(false);
expect(second.takeStoreFailure('doc')).toBeNull();
expect(second.takeStoreDivergence('doc')).toBe(false);
+ await expect(second.awaitDeferredStoreOutcome('doc')).resolves.toBeUndefined();
+ });
+
+ test('holds writes until every admission hold is released', async () => {
+ const state = new DocumentDurabilityState();
+ await expect(state.whenWriteAdmitted()).resolves.toBe(true);
+
+ state.setBatchInProgress(true);
+ await expect(state.whenWriteAdmitted()).resolves.toBe(true);
+
+ const releaseBranchSwitch = state.holdWriteAdmission();
+ const releaseOverlapping = state.holdWriteAdmission();
+ let settled = false;
+ const waiting = state.whenWriteAdmitted().then((result) => {
+ settled = true;
+ return result;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(settled).toBe(false);
+
+ releaseOverlapping();
+ releaseOverlapping();
+ state.setBatchInProgress(false);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(settled).toBe(false);
+
+ releaseBranchSwitch();
+ await expect(waiting).resolves.toBe(true);
+ expect(state.isWriteAdmissionHeld()).toBe(false);
+ });
+
+ test('stops waiting for admission once the bound elapses', async () => {
+ vi.useFakeTimers();
+ try {
+ const state = new DocumentDurabilityState();
+ state.holdWriteAdmission();
+ let result: boolean | undefined;
+ const waiting = state.whenWriteAdmitted().then((admitted) => {
+ result = admitted;
+ });
+
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(result).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(1);
+ await waiting;
+
+ expect(result).toBe(false);
+ expect(state.isWriteAdmissionHeld()).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('bounds every wait inside one write budget by that budget together', async () => {
+ vi.useFakeTimers();
+ try {
+ const state = new DocumentDurabilityState();
+ state.holdWriteAdmission();
+ state.openDeferredStore('doc');
+ let finishedAt: number | undefined;
+ const started = Date.now();
+ const waits = state.runWithinWriteWaitBudget(async () => {
+ const admitted = await state.whenWriteAdmitted();
+ const outcome = await state.awaitDeferredStoreOutcome('doc');
+ const admittedAgain = await state.whenWriteAdmitted();
+ finishedAt = Date.now();
+ return { admitted, outcome, admittedAgain };
+ });
+
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(finishedAt).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(1);
+
+ await expect(waits).resolves.toEqual({
+ admitted: false,
+ outcome: { kind: 'unsettled' },
+ admittedAgain: false,
+ });
+ expect(finishedAt).toBe(started + WRITE_WAIT_BUDGET_MS);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('does not wait for a deferred store while no admission hold is active', async () => {
+ const state = new DocumentDurabilityState();
+ state.setBatchInProgress(true);
+ state.openDeferredStore('doc');
+ await expect(state.awaitDeferredStoreOutcome('doc')).resolves.toBeUndefined();
+ });
+
+ test('reports the outcome of the latest deferred store for a document', async () => {
+ const state = new DocumentDurabilityState();
+ state.holdWriteAdmission();
+ await expect(state.awaitDeferredStoreOutcome('doc')).resolves.toBeUndefined();
+
+ const earlier = state.openDeferredStore('doc');
+ const earlierOutcome = state.awaitDeferredStoreOutcome('doc');
+ const later = state.openDeferredStore('doc');
+ const laterOutcome = state.awaitDeferredStoreOutcome('doc');
+
+ earlier.settle({ kind: 'completed' });
+ await expect(earlierOutcome).resolves.toEqual({ kind: 'completed' });
+ const stillPending = state.awaitDeferredStoreOutcome('doc');
+
+ later.settle({ kind: 'discarded' });
+ await expect(laterOutcome).resolves.toEqual({ kind: 'discarded' });
+ await expect(stillPending).resolves.toEqual({ kind: 'discarded' });
+ await expect(state.awaitDeferredStoreOutcome('doc')).resolves.toBeUndefined();
+ });
+
+ test('reports a deferred store that has not settled within the bound as unsettled', async () => {
+ vi.useFakeTimers();
+ try {
+ const state = new DocumentDurabilityState();
+ state.holdWriteAdmission();
+ state.openDeferredStore('doc');
+ let result: unknown;
+ const waiting = state.awaitDeferredStoreOutcome('doc').then((outcome) => {
+ result = outcome;
+ });
+
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ expect(result).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(1);
+ await waiting;
+
+ expect(result).toEqual({ kind: 'unsettled' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('reports a discard that lands within the bound', async () => {
+ vi.useFakeTimers();
+ try {
+ const state = new DocumentDurabilityState();
+ state.holdWriteAdmission();
+ const deferral = state.openDeferredStore('doc');
+ const waiting = state.awaitDeferredStoreOutcome('doc');
+
+ await vi.advanceTimersByTimeAsync(WRITE_WAIT_BUDGET_MS - 1);
+ deferral.settle({ kind: 'discarded' });
+
+ await expect(waiting).resolves.toEqual({ kind: 'discarded' });
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
});
test('does not let an older flush clear a newer in-flight snapshot', () => {
diff --git a/packages/server/src/document-durability-state.ts b/packages/server/src/document-durability-state.ts
index d4df9d571..b767b5449 100644
--- a/packages/server/src/document-durability-state.ts
+++ b/packages/server/src/document-durability-state.ts
@@ -1,3 +1,4 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
import { existsSync, readFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { atomicTempPath } from '@inkeep/open-knowledge-core/server';
@@ -28,16 +29,34 @@ export interface StoreAttemptToken {
export type StorePublishOutcome = 'published' | 'stale' | 'reentrant';
+export type DeferredStoreOutcome =
+ | { readonly kind: 'completed' }
+ | { readonly kind: 'failed'; readonly failure: StoreFailure }
+ | { readonly kind: 'discarded' };
+
+export type DeferredStoreWait = DeferredStoreOutcome | { readonly kind: 'unsettled' };
+
+export interface DeferredStoreSettlement {
+ settle(outcome: DeferredStoreOutcome): void;
+}
+
export function assertNeverStorePublishOutcome(outcome: never): never {
throw new Error(`[StorePublishOutcome] unhandled variant: ${JSON.stringify(outcome)}`);
}
+export function assertNeverDeferredStoreWait(wait: never): never {
+ throw new Error(`[DeferredStoreWait] unhandled variant: ${JSON.stringify(wait)}`);
+}
+
export const OK_DOC_REMOVED = 'OK_DOC_REMOVED';
export const OK_PATH_UNRESOLVABLE = 'OK_PATH_UNRESOLVABLE';
export const OK_STORE_REFUSED = 'OK_STORE_REFUSED';
+export const OK_STORE_DISCARDED = 'OK_STORE_DISCARDED';
const IN_FLIGHT_FLUSH_TTL_MS = 60_000;
+export const WRITE_WAIT_BUDGET_MS = 20_000;
+
export const DISPLACED_VERSION_TTL_MS = 30 * 60_000;
export const DISPLACED_VERSION_LIMIT = 8;
@@ -272,6 +291,10 @@ export class DocumentDurabilityState {
private nextDisplacedExpiryAt = Number.POSITIVE_INFINITY;
private activeBranch: string;
private batchInProgress = false;
+ private writeAdmissionHolds = 0;
+ private readonly writeAdmissionWaiters = new Set<() => void>();
+ private readonly writeWaitDeadline = new AsyncLocalStorage<number>();
+ private readonly deferredStoreOutcomes = new Map<string, Promise<DeferredStoreOutcome>>();
constructor(initialBranch = 'main', options: DocumentDurabilityStateOptions = {}) {
this.activeBranch = initialBranch;
@@ -806,6 +829,91 @@ export class DocumentDurabilityState {
return this.batchInProgress;
}
+ holdWriteAdmission(): () => void {
+ this.writeAdmissionHolds++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.writeAdmissionHolds--;
+ if (this.writeAdmissionHolds > 0) return;
+ const waiters = [...this.writeAdmissionWaiters];
+ this.writeAdmissionWaiters.clear();
+ for (const wake of waiters) wake();
+ };
+ }
+
+ isWriteAdmissionHeld(): boolean {
+ return this.writeAdmissionHolds > 0;
+ }
+
+ runWithinWriteWaitBudget<T>(fn: () => T, budgetMs = WRITE_WAIT_BUDGET_MS): T {
+ return this.writeWaitDeadline.run(Date.now() + budgetMs, fn);
+ }
+
+ private remainingWriteWait(timeoutMs: number): number {
+ const deadline = this.writeWaitDeadline.getStore();
+ if (deadline === undefined) return timeoutMs;
+ return Math.max(0, Math.min(timeoutMs, deadline - Date.now()));
+ }
+
+ async whenWriteAdmitted(timeoutMs = WRITE_WAIT_BUDGET_MS): Promise<boolean> {
+ if (!this.isWriteAdmissionHeld()) return true;
+ const bound = this.remainingWriteWait(timeoutMs);
+ if (bound === 0) return false;
+ let wake: () => void = () => {};
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ wake();
+ }, bound);
+ try {
+ while (this.isWriteAdmissionHeld() && !timedOut) {
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ this.writeAdmissionWaiters.add(resolve);
+ });
+ this.writeAdmissionWaiters.delete(wake);
+ }
+ return !this.isWriteAdmissionHeld();
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ openDeferredStore(docName: string): DeferredStoreSettlement {
+ const { promise, resolve } = Promise.withResolvers<DeferredStoreOutcome>();
+ this.deferredStoreOutcomes.set(docName, promise);
+ return {
+ settle: (outcome) => {
+ if (this.deferredStoreOutcomes.get(docName) === promise) {
+ this.deferredStoreOutcomes.delete(docName);
+ }
+ resolve(outcome);
+ },
+ };
+ }
+
+ async awaitDeferredStoreOutcome(
+ docName: string,
+ timeoutMs = WRITE_WAIT_BUDGET_MS,
+ ): Promise<DeferredStoreWait | undefined> {
+ const pending = this.deferredStoreOutcomes.get(docName);
+ if (pending === undefined || !this.isWriteAdmissionHeld()) return undefined;
+ const unsettled = { kind: 'unsettled' } as const;
+ const bound = this.remainingWriteWait(timeoutMs);
+ if (bound === 0) return unsettled;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expired = new Promise<typeof unsettled>((resolve) => {
+ timer = setTimeout(() => resolve(unsettled), bound);
+ });
+ try {
+ return await Promise.race([pending, expired]);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
markAgentWriteStore(docName: string): void {
this.agentWriteStores.add(docName);
}
diff --git a/packages/server/src/persistence-deferred-store.test.ts b/packages/server/src/persistence-deferred-store.test.ts
index 50415d3b7..95fe2508f 100644
--- a/packages/server/src/persistence-deferred-store.test.ts
+++ b/packages/server/src/persistence-deferred-store.test.ts
@@ -85,6 +85,7 @@ describe('batch-gated L1 persistence', () => {
beforeEach(() => {
durabilityState = new DocumentDurabilityState();
+ durabilityState.holdWriteAdmission();
tmpDir = mkdtempSync(join(tmpdir(), 'ok-deferred-store-'));
mkdirSync(tmpDir, { recursive: true });
setBatchInProgress(false);
@@ -116,6 +117,7 @@ describe('batch-gated L1 persistence', () => {
expect(readFileSync(docPath, 'utf-8')).toBe('initial\n');
expect(acks).toHaveLength(0);
+ const outcome = durabilityState.awaitDeferredStoreOutcome(docName);
setBatchInProgress(false);
await persistence.flushDeferredStores('within-branch');
@@ -123,6 +125,8 @@ describe('batch-gated L1 persistence', () => {
expect(readFileSync(docPath, 'utf-8')).toContain('queued edit');
expect(acks).toHaveLength(1);
expect(acks[0]?.docName).toBe(docName);
+ await expect(outcome).resolves.toEqual({ kind: 'completed' });
+ await expect(durabilityState.awaitDeferredStoreOutcome(docName)).resolves.toBeUndefined();
document.destroy();
});
@@ -208,10 +212,17 @@ describe('batch-gated L1 persistence', () => {
setBatchInProgress(true);
await storeDocument(persistence, badDoc, badDocName);
await storeDocument(persistence, goodDoc, goodDocName);
+ const badOutcome = durabilityState.awaitDeferredStoreOutcome(badDocName);
+ const goodOutcome = durabilityState.awaitDeferredStoreOutcome(goodDocName);
setBatchInProgress(false);
await expect(persistence.flushDeferredStores('within-branch')).resolves.toBeUndefined();
expect(readFileSync(goodPath, 'utf-8')).toContain('good queued edit');
+ await expect(badOutcome).resolves.toEqual({
+ kind: 'failed',
+ failure: expect.objectContaining({ message: expect.any(String) }),
+ });
+ await expect(goodOutcome).resolves.toEqual({ kind: 'completed' });
badDoc.destroy();
goodDoc.destroy();
@@ -271,14 +282,45 @@ describe('batch-gated L1 persistence', () => {
setBatchInProgress(true);
await storeDocument(persistence, document, docName);
expect(readFileSync(docPath, 'utf-8')).toBe('branch A base\n');
+ const outcome = durabilityState.awaitDeferredStoreOutcome(docName);
writeFileSync(docPath, 'target branch content\n', 'utf-8');
switchReconciledBaseScope('branch-b');
setBatchInProgress(false);
- await persistence.flushDeferredStores('discard-stale');
+ const discard = persistence.flushDeferredStores('discard-stale');
+ const afterDiscardCall = durabilityState.awaitDeferredStoreOutcome(docName);
+ await discard;
+ await expect(afterDiscardCall).resolves.toBeUndefined();
expect(readFileSync(docPath, 'utf-8')).toBe('target branch content\n');
expect(acks).toHaveLength(0);
+ await expect(outcome).resolves.toEqual({ kind: 'discarded' });
+ });
+
+ test('a within-branch flush discards a store deferred on another branch', async () => {
+ const docName = 'branch-mismatch';
+ const docPath = join(tmpDir, `${docName}.md`);
+ writeFileSync(docPath, 'branch A base\n', 'utf-8');
+ const persistence = createPersistenceExtension({
+ contentDir: tmpDir,
+ projectDir: tmpDir,
+ gitEnabled: false,
+ });
+ const document = new Y.Doc();
+
+ switchReconciledBaseScope('branch-a');
+ await loadDocument(persistence, document, docName);
+ document.transact(() => replaceDocParagraph(document, 'branch A edit'), BROWSER_ORIGIN);
+ setBatchInProgress(true);
+ await storeDocument(persistence, document, docName);
+ const outcome = durabilityState.awaitDeferredStoreOutcome(docName);
+
+ switchReconciledBaseScope('branch-b');
+ setBatchInProgress(false);
+ await persistence.flushDeferredStores('within-branch');
+
+ expect(readFileSync(docPath, 'utf-8')).toBe('branch A base\n');
+ await expect(outcome).resolves.toEqual({ kind: 'discarded' });
document.destroy();
});
@@ -295,6 +337,8 @@ describe('batch-gated L1 persistence', () => {
const secondDoc = new Y.Doc();
let queuedSecondStore = false;
let discardFlush: Promise<void> | undefined;
+ let secondOutcome: Promise<unknown> | undefined;
+ let secondPendingAfterDiscardCall: Promise<unknown> | undefined;
const persistence = createPersistenceExtension({
contentDir: tmpDir,
@@ -306,8 +350,10 @@ describe('batch-gated L1 persistence', () => {
setBatchInProgress(true);
void storeDocument(persistence, secondDoc, secondDocName);
+ secondOutcome = durabilityState.awaitDeferredStoreOutcome(secondDocName);
setBatchInProgress(false);
discardFlush = persistence.flushDeferredStores('discard-stale');
+ secondPendingAfterDiscardCall = durabilityState.awaitDeferredStoreOutcome(secondDocName);
},
});
@@ -318,6 +364,7 @@ describe('batch-gated L1 persistence', () => {
setBatchInProgress(true);
await storeDocument(persistence, firstDoc, firstDocName);
+ const firstOutcome = durabilityState.awaitDeferredStoreOutcome(firstDocName);
setBatchInProgress(false);
await persistence.flushDeferredStores('within-branch');
@@ -326,6 +373,9 @@ describe('batch-gated L1 persistence', () => {
expect(queuedSecondStore).toBe(true);
expect(readFileSync(firstPath, 'utf-8')).toContain('first queued edit');
expect(readFileSync(secondPath, 'utf-8')).toBe('second base\n');
+ await expect(firstOutcome).resolves.toEqual({ kind: 'completed' });
+ await expect(secondPendingAfterDiscardCall).resolves.toBeUndefined();
+ await expect(secondOutcome).resolves.toEqual({ kind: 'discarded' });
firstDoc.destroy();
secondDoc.destroy();
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index fc60b4a46..f815964ef 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -67,6 +67,8 @@ import { resolveDirectoryRoot, resolveNativePath } from './directory-root.ts';
import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
import {
assertNeverStorePublishOutcome,
+ type DeferredStoreOutcome,
+ type DeferredStoreSettlement,
DocumentDurabilityState,
OK_DOC_REMOVED,
OK_PATH_UNRESOLVABLE,
@@ -491,6 +493,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
branch: string;
document: Y.Doc;
lastTransactionOrigin: unknown;
+ settlement: DeferredStoreSettlement;
}
>();
@@ -2003,10 +2006,19 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
branch: durabilityState.getActiveBranch(),
document,
lastTransactionOrigin,
+ settlement:
+ deferredStores.get(documentName)?.settlement ??
+ durabilityState.openDeferredStore(documentName),
});
}
+ function discardDeferredStores(): void {
+ for (const entry of deferredStores.values()) entry.settlement.settle({ kind: 'discarded' });
+ deferredStores.clear();
+ }
+
async function flushDeferredStores(mode: 'within-branch' | 'discard-stale' = 'within-branch') {
+ if (mode === 'discard-stale') discardDeferredStores();
if (deferredStoreDrainInFlight) {
pendingDeferredStoreFlushMode =
pendingDeferredStoreFlushMode === 'discard-stale' || mode === 'discard-stale'
@@ -2018,12 +2030,17 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
deferredStoreDrainInFlight = (async () => {
let drainMode = mode;
while (true) {
+ if (drainMode === 'discard-stale') discardDeferredStores();
const entries = [...deferredStores.entries()];
deferredStores.clear();
if (drainMode !== 'discard-stale') {
for (const [documentName, entry] of entries) {
- if (entry.branch !== durabilityState.getActiveBranch()) continue;
+ if (entry.branch !== durabilityState.getActiveBranch()) {
+ entry.settlement.settle({ kind: 'discarded' });
+ continue;
+ }
+ let outcome: DeferredStoreOutcome = { kind: 'completed' };
try {
await storeDocumentNow({
document: entry.document,
@@ -2031,6 +2048,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
lastTransactionOrigin: entry.lastTransactionOrigin,
});
} catch (err) {
+ outcome = { kind: 'failed', failure: toStoreFailure(err) };
const verbose = process.env.OK_TELEMETRY_VERBOSE === '1';
let rawMessage = '';
try {
@@ -2073,6 +2091,8 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
{ err, documentName },
`[persistence] Deferred store failed for ${documentName}`,
);
+ } finally {
+ entry.settlement.settle(outcome);
}
}
}
diff --git a/packages/server/src/server-factory.conflict-authority.test.ts b/packages/server/src/server-factory.conflict-authority.test.ts
index ad0887296..cbe5cf33a 100644
--- a/packages/server/src/server-factory.conflict-authority.test.ts
+++ b/packages/server/src/server-factory.conflict-authority.test.ts
@@ -12,6 +12,7 @@ import {
SyncConflictsSuccessSchema,
} from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
import { configureTestGitRepository } from '../../../test-support/configure-git-fixture.test-helper.ts';
import { bootServer } from './boot.ts';
import { ConfigSchema } from './config/schema.ts';
@@ -493,7 +494,23 @@ describe('PRD-8318: a merge-native conflict resolved with raw git unfreezes the
});
held.serverInstance.durabilityState.setBatchInProgress(true);
- expect(await writeDocProbe(held.port, SCRATCH_DOC, `# ${DEFERRED_MARKER}\n`)).toBe(200);
+ const scratch = await held.serverInstance.hocuspocus.openDirectConnection(SCRATCH_DOC);
+ try {
+ await scratch.transact((doc) => {
+ const paragraph = new Y.XmlElement('paragraph');
+ paragraph.insert(0, [new Y.XmlText(DEFERRED_MARKER)]);
+ doc.getXmlFragment('default').push([paragraph]);
+ });
+ const debounceId = `onStoreDocument-${SCRATCH_DOC}`;
+ await pollUntil(
+ () => held.serverInstance.hocuspocus.debouncer.isDebounced(debounceId),
+ 15_000,
+ 'the edit to schedule a store',
+ );
+ await held.serverInstance.hocuspocus.debouncer.executeNow(debounceId);
+ } finally {
+ await scratch.disconnect();
+ }
expect(readScratch()).toContain(CONTROL_MARKER);
expect(readScratch()).not.toContain(DEFERRED_MARKER);
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 198fc9c67..41faea0c5 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -2119,6 +2119,7 @@ export function createServer(options: ServerOptions): ServerInstance {
sessionManager = new AgentSessionManager(hocuspocus, {
...options.agentSessionOptions,
assertDocumentScope: assertDocumentProjectScope,
+ awaitWriteAdmission: () => durabilityState.whenWriteAdmitted(),
});
const sm = sessionManager;
unregisterWorkloadProviders.push(
@@ -4385,6 +4386,7 @@ export function createServer(options: ServerOptions): ServerInstance {
refreshStartupEmbeds();
}
+ let releaseHeadBatchAdmission = () => {};
try {
headWatcher = await startHeadWatcher(
projectDir,
@@ -4395,6 +4397,8 @@ export function createServer(options: ServerOptions): ServerInstance {
await persistence.flushPendingGitCommit();
setBatchInProgress(true);
+ releaseHeadBatchAdmission();
+ releaseHeadBatchAdmission = durabilityState.holdWriteAdmission();
if (shadowRef.current) {
const currentBranch = getActiveBranch();
@@ -4459,30 +4463,37 @@ export function createServer(options: ServerOptions): ServerInstance {
if (info.batchKind === 'within-branch') {
setBatchInProgress(false);
- await drainEventBuffer();
-
- if (info.headMoved && info.newHead) {
- const changes = resolveUpstreamChanges(
- projectDir,
- resolve(contentDir),
- info.oldHead,
- info.newHead,
- );
- if (changes.size > 0) {
- dropPendingDocs(changes.keys());
- for (const [docName, author] of changes) {
- recordContributor(
- docName,
- gitAuthorWriterId(author.email),
- author.name,
- author.email,
- formatReconcileSubject(docName),
- );
+ try {
+ await drainEventBuffer();
+
+ if (info.headMoved && info.newHead) {
+ const changes = resolveUpstreamChanges(
+ projectDir,
+ resolve(contentDir),
+ info.oldHead,
+ info.newHead,
+ );
+ if (changes.size > 0) {
+ dropPendingDocs(changes.keys());
+ for (const [docName, author] of changes) {
+ recordContributor(
+ docName,
+ gitAuthorWriterId(author.email),
+ author.name,
+ author.email,
+ formatReconcileSubject(docName),
+ );
+ }
+ await persistence.flushContributors();
}
- await persistence.flushContributors();
+ }
+ } finally {
+ try {
+ await persistence.flushDeferredStores('within-branch');
+ } finally {
+ releaseHeadBatchAdmission();
}
}
- await persistence.flushDeferredStores('within-branch');
try {
await conflicts.pruneMergeNativeAgainstGit();
} catch (err) {
@@ -4715,10 +4726,14 @@ export function createServer(options: ServerOptions): ServerInstance {
deferredStoresFlushed = true;
cc1Broadcaster?.emitBranchSwitched(newBranch);
} finally {
- derivedDocumentIndex.abortBranchSwitch(branchTransition);
- if (!deferredStoresFlushed) {
- setBatchInProgress(false);
- await persistence.flushDeferredStores('discard-stale');
+ try {
+ derivedDocumentIndex.abortBranchSwitch(branchTransition);
+ if (!deferredStoresFlushed) {
+ setBatchInProgress(false);
+ await persistence.flushDeferredStores('discard-stale');
+ }
+ } finally {
+ releaseHeadBatchAdmission();
}
}
}